@mdfriday/foundry 26.5.2 → 26.5.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/esm/index.js CHANGED
@@ -1,2 +1,2 @@
1
1
  /* @mdfriday/foundry - ES Modules (minified) */
2
- var ConfigError,Config,DefaultRootConfig,Root,__defProp=Object.defineProperty,__getOwnPropNames=Object.getOwnPropertyNames,__require=(e=>"undefined"!=typeof require?require:"undefined"!=typeof Proxy?new Proxy(e,{get:(e,t)=>("undefined"!=typeof require?require:e)[t]}):e)(function(e){if("undefined"!=typeof require)return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')}),__esm=(e,t)=>function(){return e&&(t=(0,e[__getOwnPropNames(e)[0]])(e=0)),t},__export=(e,t)=>{for(var r in t)__defProp(e,r,{get:t[r],enumerable:!0})},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,r,i,s,n,a,o,l,c){this.configSourceFs=e,this.provider=t,this.root=r,this.dir=i,this.module=s,this.service=n,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,lang,languages,DefaultLanguageConfig,Language,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),{})}}),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}}),init_lang=__esm({"pkg/lang/index.ts"(){init_data(),init_service3(),init_service3(),serviceInstance||(serviceInstance=new DefaultLanguageService),lang=serviceInstance,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[r,i]of Object.entries(this.configs))i.weight<t&&(t=i.weight,e=r);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 r=this.configs[t];if(!r)throw new Error(`Language "${t}" not found`);return r.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[r,i]of Object.entries(e.taxonomies))"string"==typeof i&&(t[r]=i);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,r]of Object.entries(this.taxonomies))if(r===e)return t}getSingularForms(){return Object.keys(this.taxonomies)}getPluralForms(){return Object.values(this.taxonomies)}setupViews(){this.views=function(e){const t=[];for(const[r,i]of Object.entries(e))t.push({singular:r,plural:i,pluralTreeKey:cleanTreeKey(i)});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,r]of Object.entries(this.socialConfig.userConfig)){const i=this.getPlatformTemplate(t);i?e.push({id:t,title:i.title,url:r.link}):e.push({id:t,title:t.charAt(0).toUpperCase()+t.slice(1),url:r.link})}return e}getSocialLink(e){const t=this.socialConfig.userConfig[e];if(!t)return;const r=this.getPlatformTemplate(e);return r?{id:e,title:r.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 DEFAULT_PUBLISH_DIR,Dir,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()}}}});import path from"path";var DefaultConfigProvider,ConfigLoader,init_dir=__esm({"internal/domain/config/entity/dir.ts"(){DEFAULT_PUBLISH_DIR="public",Dir=class{workingDir;themesDir;publishDir;constructor(e,t,r=DEFAULT_PUBLISH_DIR){this.workingDir=e,this.themesDir=t,this.publishDir=r}getWorkingDir(){return path.resolve(this.workingDir)}getThemesDir(){return path.resolve(this.themesDir)}getThemesCacheDir(){return path.resolve(this.themesDir,".cache")}getPublishDir(){return path.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[r,i]of Object.entries(e))t[r.toLowerCase()]=i;return t}getNestedKeyAndMap(e,t){let r;this.keyCache.has(e)?r=this.keyCache.get(e):(r=e.split("."),this.keyCache.set(e,r));let i=this.root;for(let e=0;e<r.length-1;e++){const s=r[e];if(!(s in i)){if(!t)return["",null];i[s]={}}const n=i[s];if("object"!=typeof n||null===n)return["",null];i=n}return[r[r.length-1],i]}getString(e){const t=this.get(e);return String(t||"")}getInt(e){const t=this.get(e),r=Number(t);return isNaN(r)?0:Math.floor(r)}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[r,i]of Object.entries(t))e[r]=String(i);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,r]=this.getNestedKeyAndMap(e.toLowerCase(),!1);return null!==r?r[t]:void 0}set(e,t){const r=e.toLowerCase();if(""===r)return void(t&&"object"==typeof t?Object.assign(this.root,this.prepareParams(t)):this.root[r]=t);const[i,s]=this.getNestedKeyAndMap(r,!0);null!==s&&(i in s&&"object"==typeof s[i]&&"object"==typeof t&&null!==t?Object.assign(s[i],t):s[i]=t)}keys(){return Object.keys(this.root)}merge(e,t){const r=e.toLowerCase();if(""===r)return void(t&&"object"==typeof t&&Object.assign(this.root,this.prepareParams(t)));const[i,s]=this.getNestedKeyAndMap(r,!0);null!==s&&(i in s&&"object"==typeof s[i]&&"object"==typeof t&&null!==t?Object.assign(s[i],t):s[i]=t)}setDefaults(e){const t=this.prepareParams(e);for(const[e,r]of Object.entries(t))e in this.root||(this.root[e]=r)}setDefaultMergeStrategy(){}walkParams(e){const t=r=>{if(r&&"object"==typeof r&&!Array.isArray(r)){if(e(r))return!0;for(const e of Object.values(r))if(t(e))return!0}return!1};t(this.root)}isSet(e){const[t,r]=this.getNestedKeyAndMap(e.toLowerCase(),!1);return null!==r&&t in r}}}});import*as path2 from"path";var ConfigSourceDescriptor,init_loader=__esm({"internal/domain/config/factory/loader.ts"(){init_provider(),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 r;r=path2.isAbsolute(e)?e:path2.join(t,e);let i="";if(""!==path2.extname(e)&&await this.fileExists(r)&&(i=r),""===i)throw new Error("Unable to locate config file or config directory.");const s=await this.loadConfigFromFile(i);this.cfg.set("",s)}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(),r=await t.open(e);try{const e=new Uint8Array(1048576),{bytesRead:t}=await r.read(e),i=(new TextDecoder).decode(e.slice(0,t));try{return JSON.parse(i)}catch{return{}}}finally{await r.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}}}});import*as path3 from"path";async function loadConfigWithParams(e,t,r,i,s={}){const n={workingDir:path3.resolve(r),modulesDir:path3.resolve(i),publishDir:path3.resolve(DEFAULT_PUBLISH_DIR),cacheDir:""};n.cacheDir=await async function(e,t){if(""!==t)return t;const r=process.env.HOME||process.env.USERPROFILE||"",i=path3.join(r,".cache","mdf");try{return await e.mkdirAll(i,493),i}catch{return path3.join("/tmp","hugo-cache")}}(e,n.cacheDir);const a=new ConfigLoader(function(e,t){return new ConfigSourceDescriptor(e,t)}(e,t),n);try{const t=await a.loadConfigByDefault();for(const[e,r]of Object.entries(s))t.set(e,r);const r=path3.resolve(t.get("publishDir")||DEFAULT_PUBLISH_DIR);return await e.mkdirAll(r,511),function(e,t,r,i,s,n,a,o,l,c){return new Config(e,t,r,i,s,n,a,o,l,c)}(e,t,function(e,t={}){const r=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(r,t)}(t.get(""),t.getParams("params")),function(e,t,r){return new Dir(e,t,r)}(n.workingDir,n.modulesDir,r),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[r,i]of Object.entries(e))if(i&&"object"==typeof i){const e=i;e.link&&(t.userConfig[r]={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[r,i]of Object.entries(e)){const s=i,n=languages.getNameByCode(r)||r;t[r]={languageCode:r,languageName:n,title:s.title||e.title||"",weight:void 0!==s.weight?s.weight:0,contentDir:s.contentDir||"content",disabled:void 0!==s.disabled&&s.disabled,params:s.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,Mount,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()}}),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")}});import*as path4 from"path";var LogLevel,Logger,init_mount=__esm({"internal/domain/module/vo/mount.ts"(){Mount=class e{constructor(e,t,r=""){this.sourcePath=e,this.targetPath=t,this.language=r}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"(){LogLevel=(e=>(e.DEBUG="debug",e.INFO="info",e.WARN="warn",e.ERROR="error",e.FATAL="fatal",e))(LogLevel||{})}});import*as util from"util";var globalLoggerManager,init_logger=__esm({"pkg/log/logger.ts"(){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"],r=t.indexOf(this.config.level);return t.indexOf(e)>=r}getCaller(){if(!this.config.enableCaller)return;const e=(new Error).stack;if(!e)return;const t=e.split("\n")[4];if(!t)return;const r=t.match(/at .* \((.+):(\d+):(\d+)\)/);if(r){const[,e,t]=r;return`${e.split("/").pop()}:${t}`}const i=t.match(/at (.+):(\d+):(\d+)/);if(i){const[,e,t]=i;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 r={level:e,timestamp:(new Date).toISOString(),message:t,...this.fields},i=this.getCaller();i&&(r.caller=i);const s=this.config.jsonFormat?JSON.stringify(r):this.formatPlainText(r);"error"===e||"fatal"===e?process.stderr.write(s+"\n"):process.stdout.write(s+"\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 r=Object.keys(e).filter(e=>!["level","timestamp","message","caller"].includes(e)).map(t=>`${t}=${JSON.stringify(e[t])}`).join(" ");return r&&t.push(r),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 r=new e(this.config);return r.fields={...this.fields,...t},r}}}}),init_http=__esm({"pkg/log/http.ts"(){}});function initLogger(e){globalLoggerManager.setGlobalConfig(e)}function getDomainLogger(e,t){return globalLoggerManager.getLogger(e,t)}function getComponentLogger(e,t,r){return globalLoggerManager.getComponentLogger(e,t,r)}function setGlobalLogLevel(e){globalLoggerManager.setLogLevel(e)}var 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 r=e+(t?JSON.stringify(t):"");if(!this.loggers.has(r)){const s=(i=this.globalConfig,new Logger(i)),n={domain:e,...t},a=s.with(n);this.loggers.set(r,a)}var i;return this.loggers.get(r)}getComponentLogger(e,t,r){const i={component:t,...r};return this.getLogger(e,i)}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")}});import*as path5 from"path";import*as http from"http";import*as https from"https";function newHttpClient(e,t,r,i){return i||new NodeHttpClient(e,t,r)}var log2,JsZipExtractor,WebZipExtractor,init_httpclient=__esm({"internal/domain/module/vo/httpclient.ts"(){init_type2(),init_log(),log=getDomainLogger("module",{component:"httpclient"}),NodeHttpClient=class{constructor(e,t=3e4,r={}){this.fs=e,this.timeout=t,this.headers=r}defaultTimeout=3e4;defaultHeaders={"User-Agent":"MDFriday-CLI/1.0.0"};async download(e,t,r){return new Promise((i,s)=>{try{const n=new URL(e),a="https:"===n.protocol,o=a?https:http,l={...this.defaultHeaders,...this.headers,...r?.headers},c={hostname:n.hostname,port:n.port||(a?443:80),path:n.pathname+n.search,method:"GET",headers:l,timeout:r?.timeout||this.timeout},h=o.request(c,async e=>{if(!e.statusCode||e.statusCode<200||e.statusCode>=300)return void s(new ModuleError(`HTTP ${e.statusCode}: ${e.statusMessage}`,"HTTP_ERROR"));const n=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 h=await this.fs.create(t),u=[];e.on("data",e=>{if(u.push(e),a+=e.length,r?.onProgress&&n>0){const e=Date.now(),t=Math.round(a/n*100);if(e-o>=100&&t!==l||t-l>=5){const i={loaded:a,total:n,percentage:t};try{r.onProgress(i),l=t}catch(e){log.error(`Progress callback error: ${e}`)}o=e}}}),e.on("end",async()=>{try{const e=Buffer.concat(u),t=new Uint8Array(e);if(await h.write(t),await h.sync(),await h.close(),r?.onProgress&&n>0){const e={loaded:n,total:n,percentage:100};try{r.onProgress(e)}catch(e){log.warn(`Progress callback error: ${e}`)}}i()}catch(e){const t=e instanceof Error?e.message:String(e);s(new ModuleError(`File write failed: ${t}`,"WRITE_FAILED"))}}),e.on("error",e=>{log.error(`Response error: ${e.message}`),s(new ModuleError(`Download failed: ${e.message}`,"DOWNLOAD_FAILED"))})}catch(e){const t=e instanceof Error?e.message:String(e);s(new ModuleError(`File system error: ${t}`,"FS_ERROR"))}});h.on("error",e=>{log.error("Request error:",e),s(new ModuleError(`Request failed: ${e.message}`,"REQUEST_FAILED"))}),h.on("timeout",()=>{h.destroy(),log.error(`Request timeout for ${e}`),s(new ModuleError("Request timeout","TIMEOUT"))}),h.end()}catch(e){const t=e instanceof Error?e.message:String(e);s(new ModuleError(`Download failed: ${t}`,"DOWNLOAD_FAILED"))}})}async get(e,t){return new Promise((r,i)=>{try{const s=new URL(e),n="https:"===s.protocol,a=n?https:http,o={...this.defaultHeaders,...this.headers,...t?.headers},l={hostname:s.hostname,port:s.port||(n?443:80),path:s.pathname+s.search,method:"GET",headers:o,timeout:t?.timeout||this.timeout},c=a.request(l,e=>{const t=[],s={};Object.entries(e.headers).forEach(([e,t])=>{s[e]=Array.isArray(t)?t.join(", "):t||""}),e.on("data",e=>{t.push(e)}),e.on("end",()=>{const i=Buffer.concat(t),n=i.buffer.slice(i.byteOffset,i.byteOffset+i.byteLength);r({data:n,headers:s,status:e.statusCode||0})}),e.on("error",e=>{i(new ModuleError(`Response error: ${e.message}`,"RESPONSE_ERROR"))})});c.on("error",e=>{i(new ModuleError(`GET request failed: ${e.message}`,"REQUEST_FAILED"))}),c.on("timeout",()=>{c.destroy(),i(new ModuleError("GET request timeout","TIMEOUT"))}),c.end()}catch(e){const t=e instanceof Error?e.message:String(e);i(new ModuleError(`GET request failed: ${t}`,"REQUEST_FAILED"))}})}}}});import JSZip from"jszip";import*as path6 from"path";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 log3,FsModuleCache,init_zipextractor=__esm({"internal/domain/module/vo/zipextractor.ts"(){init_type2(),init_log(),log2=getDomainLogger("module",{component:"zipextractor"}),JsZipExtractor=class{constructor(e){this.fs=e}async extract(e,t){try{const r=await this.fs.open(e),i=(await r.stat()).size(),s=new Uint8Array(i),n=await r.read(s);await r.close(),await this.extractZipData(n.buffer,t)}catch(t){const r=t instanceof Error?t.message:String(t);throw log2.error(`ZIP extraction failed for ${e}: ${r}`),new ModuleError(`ZIP extraction failed: ${r}`,"EXTRACTION_FAILED")}}async list(e){try{const t=await this.fs.open(e),r=await t.stat(),i=new Uint8Array(r.size()),s=await t.read(i);return await t.close(),await this.listZipContents(s.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 r=new JSZip,i=await r.loadAsync(e),s=[];i.forEach((e,t)=>{t.dir||s.push(e)});const n=[];let a=0;i.forEach((e,r)=>{n.push(this.extractSingleEntry(e,r,t).then(()=>{a++}))}),await Promise.all(n)}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,r){const i=path6.join(r,e);if(t.dir)await this.fs.mkdirAll(i,493);else{const e=path6.dirname(i);e!==r&&await this.fs.mkdirAll(e,493);const s=await t.async("uint8array"),n=await this.fs.create(i);await n.write(s),await n.close()}}async listZipContents(e){try{const t=new JSZip,r=await t.loadAsync(e),i=[];return r.forEach(e=>{i.push(e)}),i}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")}}}}});import*as path7 from"path";function newModuleCache(e,t){return new FsModuleCache(e,t)}var Module2,ProjectModule,init_cache=__esm({"internal/domain/module/vo/cache.ts"(){init_type2(),init_log(),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),r=await this.fs.open(t),i=await r.stat(),s=new Uint8Array(i.size());await r.read(s),await r.close();const n=(new TextDecoder).decode(s);return JSON.parse(n)}catch(t){if(t.message?.includes("ENOENT")||t.message?.includes("no such file"))return log3.info(`Cache miss: ${e}`,t),null;const r=t instanceof Error?t.message:String(t);throw log3.error(`Cache read error for ${e}: ${r}`),new ModuleError(`Failed to read cache: ${r}`,"CACHE_READ_FAILED")}}async set(e,t){try{await this.fs.mkdirAll(this.cacheDir,493);const r=this.getCacheFilePath(e),i=JSON.stringify(t,null,2),s=(new TextEncoder).encode(i),n=await this.fs.create(r);await n.write(s),await n.sync(),await n.close()}catch(t){const r=t instanceof Error?t.message:String(t);throw log3.error(`Cache write error for ${e}: ${r}`),new ModuleError(`Failed to write cache: ${r}`,"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 r=t instanceof Error?t.message:String(t);throw log3.error(`Cache delete error for ${e}: ${r}`),new ModuleError(`Failed to delete cache: ${r}`,"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 r of e)try{const e=path7.join(this.cacheDir,r);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[]}}}}});import*as path8 from"path";function newModule2(e,t,r,i){return new Module2(e,t,r,i||null,!1)}var Lang,init_module3=__esm({"internal/domain/module/vo/module.ts"(){init_type2(),init_mount(),Module2=class e{constructor(e,t,r,i=null,s=!1){this.fs=e,this.absoluteDir=t,this.modulePath=r,this.parentModule=i,this.mountDirs=[],this.metadata=null,this.isProject=s}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 r=path8.join(this.absoluteDir,e);try{(await this.fs.stat(r)).isDir()&&t.push({sourcePath:e,targetPath:e})}catch(e){}}this.mountDirs=t.map(e=>{return t=e.sourcePath,r=e.targetPath,new Mount(t,r);var t,r})}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 r of t)r instanceof Mount&&r.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()}}}});import path9 from"path";var Themes,log4,Modules,init_lang2=__esm({"internal/domain/module/entity/lang.ts"(){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(path9.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 r=e.indexOf("?");if(-1===r)return e;const i=e.substring(0,r),s=new URLSearchParams(e.substring(r+1));s.delete("version");const n=s.toString();return n?`${i}?${n}`:i}}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()))}}}});import{parse as parseToml}from"smol-toml";import*as path10 from"path";function newModules(e,t,r,i){return new Modules(e,t,r,i)}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(),log4=getDomainLogger("module",{component:"modules"}),Modules=class{constructor(e,t,r,i){var s;this.info=e,this.httpClient=t,this.zipExtractor=r,this.moduleCache=i,this.projectModule=function(e){const t=e.osFs(),r=e.projDir(),i=e.defaultLanguageKey(),s=new Module2(t,r,"project-root",null,!0),n=new ProjectModule(s);n.applyDefaultMounts(),i&&n.setDefaultLanguage(i);const a=e.otherLanguageKeys();for(const t of a)try{const r=e.getRelDir(ComponentFolderContent,t);if(r&&""!==r){const e=new Mount(r,ComponentFolderContent,t);n.appendMount(e)}}catch(e){console.warn(`Failed to get relative directory for language ${t}:`,e)}return n}(this.info),this.lang=(s=this.all(),new Lang(s))}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 r=0;r<t.length;r++){const i=t[r],{cleanUrl:s,version:n}=this.parseVersionFromImportPath(i);let a=i;"latest"===n&&(a=await this.resolveLatestVersion(i)),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),r=t.searchParams.get("version")||"latest";return t.searchParams.delete("version"),{cleanUrl:t.toString(),version:r}}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 r=this.themesCache.get(t);if(!r){const e=await this.httpClient.get(t),i=(new TextDecoder).decode(e.data),s=JSON.parse(i);r=Themes.fromJson(s),this.themesCache.set(t,r)}const i=r.resolveLatestVersion(e);return i!==e?log4.info(`Resolved latest version: ${e} -> ${i}`):log4.warn(`Could not resolve latest version for ${e}, using original path`),i}catch(t){return log4.error(`Failed to resolve latest version for ${e}:`,t),e}}async downloadModule(e,t){try{let r=e.version;if("latest"===e.version){const t=await this.resolveLatestVersion(e.path),{version:i}=this.parseVersionFromImportPath(t);r=i}const i=await this.moduleCache.get(e.path);if(i&&"completed"===i.downloadStatus&&this.isCacheValidForVersion(i.version,r)){const t=await this.createModuleFromCache(e,i);if(await t.exists())return log4.info(`Using cached module ${e.path} version ${i.version}`),t}i&&"completed"===i.downloadStatus&&!this.isCacheValidForVersion(i.version,r)&&log4.info(`Cache version mismatch for ${e.path}: cached=${i.version}, requested=${r||"latest"}`);const s=this.getModuleDir(e.path),n=path10.join(s,"module.zip"),a={path:e.path,version:e.version||"latest",url:e.url,dir:s,downloadStatus:"downloading",downloadedAt:new Date};await this.moduleCache.set(e.path,a);try{const r=this.addTimestampToUrl(e.url);await this.httpClient.download(r,n,{onProgress:e=>{t?.({percentage:e.percentage})}}),await this.zipExtractor.extract(n,s),a.downloadStatus="completed",a.downloadedAt=new Date;try{const e=await this.info.osFs().stat(n);a.size=e.size()}catch(e){}try{await this.info.osFs().remove(n)}catch(e){}await this.moduleCache.set(e.path,a);const i=newModule2(this.info.osFs(),s,e.path);return i.setMetadata(a),await i.applyMounts(e),i}catch(t){a.downloadStatus="failed",await this.moduleCache.set(e.path,a);const r=t instanceof Error?t.message:String(t);throw new ModuleError(`Failed to download module ${e.path}: ${r}`,"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,r){try{if(this.downloadedModules.has(t))return;const{cleanUrl:e,version:i}=this.parseVersionFromImportPath(t),s={path:t,url:this.getDownloadUrl(e),...i&&{version:i}},n=await this.downloadModule(s,r);this.modules.push(n),this.downloadedModules.add(t);try{const e=await this.parseThemeToml(n);for(const t of e){if(this.downloadedModules.has(t)){log4.info(`Module ${t} already downloaded, skipping`);continue}log4.info(`Recursively downloading module dependency: ${t}`);const e=t,{cleanUrl:i,version:s}=this.parseVersionFromImportPath(e);let a=e;"latest"===s&&(a=await this.resolveLatestVersion(e)),await this.addModule(n,a,e=>{r?.({percentage:.5*e.percentage})})}}catch(e){const r=e instanceof Error?e.message:String(e);log4.warn(`Failed to process recursive imports for module ${t}: ${r}`)}}catch(e){const r=e instanceof Error?e.message:String(e);throw new ModuleError(`Failed to add module ${t}: ${r}`,"ADD_MODULE_FAILED")}}async createModuleFromCache(e,t){const r=newModule2(this.info.osFs(),t.dir,e.path);return r.setMetadata(t),await r.applyMounts(e),r}getModuleDir(e){const t=e.replace(/[/\\:*?"<>|]/g,"_").replace(/^_+|_+$/g,"");return path10.join(this.info.moduleDir(),t)}getDownloadUrl(e){return e}isCacheValidForVersion(e,t){return!t||e===t}addTimestampToUrl(e){try{const t=new URL(e),r=Date.now().toString();return t.searchParams.set("_t",r),t.toString()}catch(t){const r=e.includes("?")?"&":"?";return`${e}${r}_t=${Date.now()}`}}getModuleByPath(e){return this.modules.find(t=>t.path()===e)||null}isModuleDownloaded(e){return this.downloadedModules.has(e)}async getModuleStatus(e){const t=await this.moduleCache.get(e);return t?.downloadStatus||"pending"}async removeModule(e){try{const t=this.modules.findIndex(t=>t.path()===e);if(t>=0){const r=this.modules[t];try{await this.info.osFs().removeAll(r.dir())}catch(e){}this.modules.splice(t,1),this.downloadedModules.delete(e),await this.moduleCache.delete(e)}}catch(t){const r=t instanceof Error?t.message:String(t);throw new ModuleError(`Failed to remove module ${e}: ${r}`,"REMOVE_MODULE_FAILED")}}async clearAll(){try{for(const e of this.modules)try{await this.info.osFs().removeAll(e.dir())}catch(e){}this.modules=[],this.downloadedModules.clear(),await this.moduleCache.clear()}catch(e){const t=e instanceof Error?e.message:String(e);throw new ModuleError(`Failed to clear modules: ${t}`,"CLEAR_MODULES_FAILED")}}getSourceLang(e){return this.lang.getSourceLang(e)}async parseThemeToml(e){try{const t=path10.join(e.dir(),"theme.toml");try{if((await this.info.osFs().stat(t)).isDir())return[]}catch(e){return[]}let r;try{const e=await this.info.osFs().open(t);try{const t=[],i=new Uint8Array(4096);for(;;){const r=await e.read(i);if(0===r.bytesRead)break;t.push(i.slice(0,r.bytesRead))}const s=t.reduce((e,t)=>e+t.length,0),n=new Uint8Array(s);let a=0;for(const e of t)n.set(e,a),a+=e.length;r=new TextDecoder("utf-8").decode(n)}finally{await e.close()}}catch(t){const r=t instanceof Error?t.message:String(t);return log4.warn(`Failed to read theme.toml for module ${e.path()}: ${r}`),[]}const i=parseToml(r);return i.module?.imports?(log4.info(`Found ${i.module.imports.length} module imports in ${e.path()}/theme.toml`),i.module.imports.map(e=>e.path)):[]}catch(t){const r=t instanceof Error?t.message:String(t);return log4.warn(`Failed to parse theme.toml for module ${e.path()}: ${r}`),[]}}}}}),init_module5=__esm({"internal/domain/module/factory/module.ts"(){init_module4(),init_type2(),init_httpclient(),init_zipextractor(),init_cache(),init_log(),log5=getDomainLogger("module",{component:"factory"})}}),init_module6=__esm({"internal/domain/module/index.ts"(){init_type2(),init_type2(),init_mount(),init_httpclient(),init_zipextractor(),init_cache(),init_module3(),init_module4(),init_module5()}}),init_type3=__esm({"internal/domain/fs/type.ts"(){FsError=class extends Error{constructor(e,t){super(e),this.code=t,this.name="FsError"}},ErrFileClosed=new FsError("File is closed","FILE_CLOSED"),new FsError("out of range","OUT_OF_RANGE"),new FsError("too large","TOO_LARGE"),ErrFileNotFound=new FsError("file not found","FILE_NOT_FOUND"),new FsError("file exists","FILE_EXISTS"),new FsError("destination exists","DESTINATION_EXISTS"),ErrSkipDir=new Error("skip directory"),new FsError("walkway already walked","ALREADY_WALKED"),ErrNoFilesystems=new(OverlayFsError=class extends FsError{constructor(e,t){super(e,t),this.name="OverlayFsError"}})("no filesystems to write to","NO_FILESYSTEMS"),new OverlayFsError("operation not supported","OPERATION_NOT_SUPPORTED")}}),init_originfs=__esm({"internal/domain/fs/entity/originfs.ts"(){OriginFs=class{source;origin;publishDir;constructor(e,t,r){this.source=e,this.origin=t,this.publishDir=r}getSource(){return this.source}getOrigin(){return this.origin}publish(){return this.publishDir}}}});function newFileMeta(e,t){return new FileMeta(e,t)}var FileInfo,init_filemeta=__esm({"internal/domain/fs/vo/filemeta.ts"(){init_log(),getDomainLogger("fs",{component:"filemeta"}),FileMeta=class{filename;componentRoot;componentDir;openFunc;constructor(e="",t=null){this.filename=e,this.componentRoot="",this.componentDir="",this.openFunc=t}fileName(){return this.filename}relativeFilename(){if(""===this.componentRoot)return this.filename;const e=this.filename.indexOf(this.componentRoot);if(-1===e)throw new Error(`filename ${this.filename} has no root ${this.componentRoot}`);let t=this.filename.substring(e+this.componentRoot.length);return t.startsWith("/")||(t="/"+t),t}component(){return this.componentDir}root(){return this.componentRoot}async open(){if(null===this.openFunc)throw new Error("OpenFunc not set");return await this.openFunc()}setFileName(e){this.filename=e}setComponentRoot(e){this.componentRoot=e}setComponentDir(e){this.componentDir=e}setOpenFunc(e){this.openFunc=e}merge(e){e&&(e.filename&&!this.filename&&(this.filename=e.filename),e.componentRoot&&!this.componentRoot&&(this.componentRoot=e.componentRoot),e.componentDir&&!this.componentDir&&(this.componentDir=e.componentDir),e.openFunc&&!this.openFunc&&(this.openFunc=e.openFunc))}}}});function newFileInfo(e,t){const r=newFileMeta(t),i=new FileInfo(e,r);return isMetaProvider(e)&&i.meta().merge(e.meta()),i}function newFileInfoWithMeta(e,t){const r=new FileInfo(e,t);return isMetaProvider(e)&&r.meta().merge(e.meta()),r}function isMetaProvider(e){return e&&"function"==typeof e.meta}var File,init_fileinfo=__esm({"internal/domain/fs/vo/fileinfo.ts"(){init_filemeta(),FileInfo=class{fileInfo;_fileMeta;constructor(e,t){this.fileInfo=e,this._fileMeta=t}meta(){return this._fileMeta}type(){return this.fileInfo.mode()}info(){return this.fileInfo}setMeta(e){this._fileMeta=e}name(){return this.fileInfo.name()}size(){return this.fileInfo.size()}mode(){return this.fileInfo.mode()}modTime(){return this.fileInfo.modTime()}isDir(){return this.fileInfo.isDir()}sys(){return this.fileInfo.sys()}fileName(){return this._fileMeta.fileName()}relativeFilename(){return this._fileMeta.relativeFilename()}component(){return this._fileMeta.component()}root(){return this._fileMeta.root()}async open(){return await this._fileMeta.open()}}}});import*as path11 from"path";var DirFile,BaseFs,init_file=__esm({"internal/domain/fs/vo/file.ts"(){init_filemeta(),init_fileinfo(),File=class{file;fileMeta;fs;_isDir;constructor(e,t,r,i=!1){this.file=e,this.fileMeta=t,this.fs=r,this._isDir=i}isNop(){return null===this.file}async close(){if(null!==this.file)return await this.file.close()}async readDir(e){const t=[];if(this._isDir&&this.file){const r=await this.file.readdir(e);for(const e of r){const r=this.joinPath(this.fileMeta.fileName(),e.name()),i=newFileMeta(r,async()=>await this.fs.open(r));i.merge(this.fileMeta);const s=newFileInfo(e,r);s.setMeta(i),t.push(s)}}return t}meta(){return this.fileMeta}joinPath(e,t){return e.endsWith("/")?e+t:e+"/"+t}async read(e){if(null===this.file)throw new Error("File is null");return await this.file.read(e)}async readAt(e,t){if(null===this.file)throw new Error("File is null");return await this.file.readAt(e,t)}async seek(e,t){if(null===this.file)throw new Error("File is null");return await this.file.seek(e,t)}async write(e){if(null===this.file)throw new Error("File is null");return await this.file.write(e)}async writeAt(e,t){if(null===this.file)throw new Error("File is null");return await this.file.writeAt(e,t)}name(){return path11.basename(this.fileMeta.fileName())}async readdir(e){if(null===this.file)throw new Error("File is null");return await this.readDir(e)}async readdirnames(e){if(null===this.file)throw new Error("File is null");return await this.file.readdirnames(e)}async stat(){if(null===this.file)throw new Error("File is null");return await this.file.stat()}async sync(){if(null!==this.file)return await this.file.sync()}async truncate(e){if(null===this.file)throw new Error("File is null");return await this.file.truncate(e)}async writeString(e){if(null===this.file)throw new Error("File is null");return await this.file.writeString(e)}}}}),init_dir2=__esm({"internal/domain/fs/vo/dir.ts"(){init_file(),DirFile=class extends File{virtualOpener;filter;constructor(e,t=null,r=null){super(e.isNop()?null:e,e.meta(),e.fs,!0),this.virtualOpener=t,this.filter=r}async readDir(e){if(!this.isNop()){let t=await super.readDir(e);return null!==this.filter&&(t=await this.filter(t)),t}return await this.readVirtualDir()}async readVirtualDir(){if(null!==this.virtualOpener)return await this.virtualOpener();throw new Error("virtual dir opener not found")}setFilter(e){this.filter=e}setVirtualOpener(e){this.virtualOpener=e}getFilter(){return this.filter}getVirtualOpener(){return this.virtualOpener}}}});import*as path12 from"path";function newBaseFs(e,t){return new BaseFs(e,t)}var log8,Walkway,init_basefs=__esm({"internal/domain/fs/entity/basefs.ts"(){init_filemeta(),init_fileinfo(),init_file(),init_dir2(),init_log(),getDomainLogger("fs",{component:"basefs"}),BaseFs=class{fs;roots;constructor(e,t){this.fs=e,this.roots=t}toAbsolutePath(e){if(0===this.roots.length)return e;const t=this.roots[0];return""===e?t:path12.isAbsolute(e)?e.startsWith(t)?e:path12.join(t,e.substring(1)):path12.join(t,e)}isSameRootedPath(e){const t=this.roots[0];return e.startsWith(path12.join(t,path12.sep))||e===t}async stat(e){const t=this.toAbsolutePath(e);if(!this.isSameRootedPath(t))throw new Error(`path ${e} is outside of the BaseFs root`);try{const r=await this.fs.stat(t);if(r.isDir()){const i=newFileInfo(r,t);return i.meta().setOpenFunc(async()=>await this.openDir(e)),i}const i=newFileInfo(r,t),s=this.getRoot(t);return i.meta().setComponentRoot(s),i.meta().setOpenFunc(async()=>await this.openInternal(e)),i}catch(e){throw e}}async open(e){const t=this.toAbsolutePath(e);return(await this.fs.stat(t)).isDir()?await this.openDir(e):await this.openInternal(e)}async openInternal(e,t=!1){const r=this.toAbsolutePath(e),i=await this.fs.open(r),s=this.getRoot(r),n=newFileMeta(r);return n.setComponentRoot(s),t?function(e,t,r){return new File(e,t,r,!0)}(i,n,this.fs):function(e,t,r){return new File(e,t,r)}(i,n,this.fs)}getRoot(e){for(const t of this.roots)if(e.startsWith(t))return t;return""}async openDir(e){const t=await this.openInternal(e,!0),r=this.toAbsolutePath(e),i=this.getRoot(r),s=newFileMeta(r);return s.setComponentRoot(i),function(e,t,r){const i=new File(e,t,r,!0);return new DirFile(i)}(t,s,this.fs)}async create(e){const t=this.toAbsolutePath(e);return await this.fs.create(t)}async mkdir(e,t){const r=this.toAbsolutePath(e);return await this.fs.mkdir(r,t)}async mkdirAll(e,t){const r=this.toAbsolutePath(e);return await this.fs.mkdirAll(r,t)}async openFile(e,t,r){const i=this.toAbsolutePath(e);return await this.fs.openFile(i,t,r)}async remove(e){const t=this.toAbsolutePath(e);return await this.fs.remove(t)}async removeAll(e){const t=this.toAbsolutePath(e);return await this.fs.removeAll(t)}async rename(e,t){const r=this.toAbsolutePath(e),i=this.toAbsolutePath(t);return await this.fs.rename(r,i)}name(){return`BaseFs(${this.fs.name()})`}async chmod(e,t){const r=this.toAbsolutePath(e);return await this.fs.chmod(r,t)}async chown(e,t,r){const i=this.toAbsolutePath(e);return await this.fs.chown(i,t,r)}async chtimes(e,t,r){const i=this.toAbsolutePath(e);return await this.fs.chtimes(i,t,r)}}}});import*as path13 from"path";var log9,StaticCopier,log10,init_walkway=__esm({"internal/domain/fs/vo/walkway.ts"(){init_type3(),init_fileinfo(),init_filemeta(),init_log(),log8=getDomainLogger("fs",{component:"walkway"}),Walkway=class{fs;root;cb;cfg;walked=!1;constructor(e,t){if(!e)throw new Error("fs must be set");if(!t.walkFn)throw new Error("walkFn must be set");this.fs=e,this.cb=t,this.root="",this.cfg={}}async walkWith(e,t){return this.cfg=t,this.root=e,await this.walk()}async walk(){if(this.walked)throw new Error("this walkway is already walked");return this.walked=!0,await this.walkRecursive(this.root,this.cfg.info,this.cfg.dirEntries)}checkErr(e,t){return!(!this.isNotExistError(t)||this.cfg.failOnNotExist||(log8.warn(`File "${e}" not found, skipping.`),0))}isNotExistError(e){return e.message.includes("ENOENT")||e.message.includes("no such file")||"ENOENT"===e.code}async walkRecursive(e,t,r){if(!t)try{const r=await this.fs.stat(e),i=newFileMeta(e);i.setOpenFunc(async()=>await this.fs.open(e)),t=newFileInfoWithMeta(r,i)}catch(t){if(e===this.root&&this.isNotExistError(t)){if(this.cfg.failOnNotExist)throw new FsError(`walk: root not found: ${t.message}`,"WALK_ROOT_NOT_FOUND");return}if(this.checkErr(e,t))return;throw new FsError(`walk: stat: ${t.message}`,"WALK_STAT_FAILED")}try{const r=await this.cb.walkFn(e,t);if(r instanceof Error)throw r}catch(e){if(t.isDir()&&e===ErrSkipDir)return;throw e}if(t.isDir()){if(!r)try{const t=await this.fs.open(e),i=await t.readdir(-1);await t.close(),r=i.map(e=>e),this.cfg.sortDirEntries&&r.sort((e,t)=>e.name().localeCompare(t.name()))}catch(t){if(this.checkErr(e,t))return;throw new FsError(`walk: readdir: ${t.message}`,"WALK_READDIR_FAILED")}if(this.cfg.ignoreFile&&(r=r.filter(e=>!this.cfg.ignoreFile(e.fileName()))),this.cb.hookPre)try{r=await this.cb.hookPre(t,e,r)}catch(e){if(e===ErrSkipDir)return;throw e}for(const t of r){const r=path13.join(e,t.name());try{await this.walkRecursive(r,t)}catch(e){if(!t.isDir()||e!==ErrSkipDir)throw e}}if(this.cb.hookPost)try{await this.cb.hookPost(t,e,r)}catch(e){if(e===ErrSkipDir)return;throw e}}}}}}),init_static_copier=__esm({"internal/domain/fs/vo/static-copier.ts"(){init_log(),log9=getDomainLogger("fs",{component:"static-copier"}),StaticCopier=class{fromFss;toFs;constructor(e,t){this.fromFss=e,this.toFs=t}async copy(){this.fromFss&&0!==this.fromFss.length?this.toFs?await this.doWithPublishDirs(this.toFs,async e=>{for(const t of this.fromFss)await this.copyStaticTo(t,e)}):log9.error("No publish filesystem found"):log9.error("No static filesystems found")}async doWithPublishDirs(e,t){try{await t("/")}catch(e){throw log9.error("Error in doWithPublishDirs:",e),e}}async copyStaticTo(e,t){try{return await this.walkSourceFiles(e,t)}catch(e){throw log9.error(`Error copying static files to ${t}:`,e),e}}async walkSourceFiles(e,t){let r=0;try{await this.walkFileSystem(e,"/",async(i,s)=>{s||(await this.copyFile(e,i,this.toFs,t),r++)})}catch(e){throw log9.error("Error walking source files:",e),e}return r}async walkFileSystem(e,t,r){try{const i=await e.open(t);if(!(await i.stat()).isDir())return await i.close(),void await r(t,!1);const s=await i.readdir(-1);await i.close();for(const i of s){const s=this.joinPath(t,i.name());i.isDir()?(await r(s,!0),await this.walkFileSystem(e,s,r)):await r(s,!1)}}catch(e){log9.error(`Could not read directory ${t}:`,e)}}async copyFile(e,t,r,i){let s=null,n=null;try{const a=t.startsWith("/")?t.slice(1):t,o=this.joinPath(i,a),l=this.dirname(o);"/"!==l&&await r.mkdirAll(l,493),s=await e.open(t);const c=await s.stat(),h=new Uint8Array(c.size());await s.read(h),n=await r.create(o),await n.write(h)}catch(e){log9.warn(`Failed to copy static file ${t}:`,e)}finally{if(n)try{await n.close()}catch(e){log9.warn(`Failed to close target file: ${e}`)}if(s)try{await s.close()}catch(e){log9.warn(`Failed to close source file: ${e}`)}}}joinPath(...e){return e.map(e=>e.replace(/^\/+|\/+$/g,"")).filter(e=>e.length>0).join("/").replace(/^/,"/")}dirname(e){const t=e.split("/").filter(e=>e.length>0);return t.length<=1?"/":"/"+t.slice(0,-1).join("/")}}}});async function createFileMetaInfo(e,t){try{const r=await t.stat(e),i=newFileMeta(e);return i.setOpenFunc(async()=>await t.open(e)),newFileInfoWithMeta(r,i)}catch(t){throw new Error(`Failed to stat file ${e}: ${t.message}`)}}var Fs2,defaultDirMerger,OverlayOptions,init_incremental_file_collector=__esm({"internal/domain/fs/vo/incremental-file-collector.ts"(){init_fileinfo(),init_filemeta(),init_log(),log10=getDomainLogger("fs",{component:"incremental-file-collector"})}}),init_fs=__esm({"internal/domain/fs/entity/fs.ts"(){init_basefs(),init_walkway(),init_static_copier(),init_incremental_file_collector(),init_fs3(),Fs2=class{originFs;prompts;workflows;content;layouts;statics;assets;i18n;work;service;constructor(e,t,r,i,s,n,a,o,l){this.originFs=e,this.prompts=t,this.workflows=r,this.content=i,this.layouts=s,this.statics=n,this.assets=a,this.i18n=o,this.work=l,this.service=new Service3}os(){return this.originFs.getOrigin()}workFs(){return this.work}workflowFs(){return this.workflows}promptFs(){return this.prompts}contentFs(){return this.content}layoutsFs(){return this.layouts}staticFs(){return this.statics}assetsFs(){return this.assets}publishFs(){return this.originFs.publish()}copyStatic(e,t){return new StaticCopier(e,t).copy()}newFileMetaInfo(e){return this.service.newFileMetaInfo(e)}newFileMetaInfoWithContent(e){return this.service.newFileMetaInfoWithContent(e)}async getFileMetaInfos(e){return async function(e,t){const r=new Map;let i=!1;for(const s of e)for(const e of t)try{const t=await createFileMetaInfo(s,e);if(r.set(s,t),i=!0,i)break}catch(t){log10.error(`Failed to create FileMetaInfo for ${s} with fs=${e}:`,t)}return r}(e,this.content)}newBasePathFs(e,t){return newBaseFs(e,[t])}async walkPrompts(e,t,r){return await this.walk(this.prompts,e,t,r)}async walkWorkflows(e,t,r){return await this.walk(this.workflows,e,t,r)}async walkLayouts(e,t,r){return await this.walk(this.layouts,e,t,r)}async walkContent(e,t,r,i){await this.walk(e,t,r,i)}async walkStatics(e,t,r){return await this.walk(this.statics,e,t,r)}async walkI18n(e,t,r){return await this.walk(this.i18n,e,t,r)}async walk(e,t,r,i){const s=function(e,t){return new Walkway(e,t)}(e,r);return""===t&&(t="/"),await s.walkWith(t,i)}}}});function newOverlayOptions(e,t=!1,r){const i={fss:e,firstWritable:t};return void 0!==r&&(i.dirsMerger=r),new OverlayOptions(i)}function createDefaultOverlayOptions(e){return newOverlayOptions(e,!1,defaultDirMerger)}var OverlayDir,dirPool,init_overlayoptions=__esm({"internal/domain/fs/vo/overlayoptions.ts"(){defaultDirMerger=(e,t)=>{const r=[...e];for(const i of t){let t=!1;for(const r of e)if(i.name()===r.name()){t=!0;break}t||r.push(i)}return r},OverlayOptions=class e{fss;firstWritable;dirsMerger;constructor(e){this.fss=[...e.fss],this.firstWritable=e.firstWritable??!1,this.dirsMerger=e.dirsMerger??defaultDirMerger}withFilesystems(...t){return new e({fss:[...this.fss,...t],firstWritable:this.firstWritable,dirsMerger:this.dirsMerger})}withFirstWritable(t){return new e({fss:this.fss,firstWritable:t,dirsMerger:this.dirsMerger})}withDirsMerger(t){return new e({fss:this.fss,firstWritable:this.firstWritable,dirsMerger:t})}getWritableFs(){return this.firstWritable&&0!==this.fss.length?this.fss[0]:null}isValid(){return void 0!==this.dirsMerger}getFilesystemCount(){return this.fss.length}getFilesystem(e){return e<0||e>=this.fss.length?null:this.fss[e]}hasFilesystem(e){return this.fss.includes(e)}getFilesystems(){return this.fss}}}});var OverlayFs,init_overlaydir=__esm({"internal/domain/fs/entity/overlaydir.ts"(){init_type3(),init_overlayoptions(),OverlayDir=class{_name;fss;dirOpeners;info;merge;err;offset;fis;closed;constructor(e={}){this._name=e.name||"",this.fss=e.fss?[...e.fss]:[],this.dirOpeners=e.dirOpeners?[...e.dirOpeners]:[],void 0!==e.info&&(this.info=e.info),this.merge=e.merge||defaultDirMerger,this.offset=0,this.fis=[],this.closed=!1}name(){return this._name}isClosed(){return this.closed||0===this.fss.length&&0===this.dirOpeners.length}async readdir(e){if(this.isClosed())throw ErrFileClosed;if(this.err)throw this.err;0===this.offset&&await this.loadDirectoryEntries();const t=this.fis.slice(this.offset);if(e<=0){if(this.err=new Error("EOF"),this.offset>0&&0===t.length)throw this.err;return[...t]}if(0===t.length)throw this.err=new Error("EOF"),this.err;const r=t.slice(0,e);return this.offset+=r.length,r}async readdirnames(e){if(this.isClosed())throw ErrFileClosed;return(await this.readdir(e)).map(e=>e.name())}async loadDirectoryEntries(){for(let e=0;e<this.fss.length;e++){const t=this.fss[e];await this.readFromFilesystem(t,null)}for(let e=0;e<this.dirOpeners.length;e++){const t=await this.dirOpeners[e]();await this.readFromFilesystem(null,t)}}async readFromFilesystem(e,t){let r=t;try{if(!r&&e){const t="/"===this._name?"":this._name;r=await e.open(t)}if(!r)return;const t=await r.readdir(-1);this.fis=this.merge(this.fis,t)}catch(e){}finally{r&&!t&&await r.close()}}async stat(){if(this.isClosed())throw ErrFileClosed;if(this.info)return await this.info();if(this.fss.length>0)return await this.fss[0].stat(this._name);throw new OverlayFsError("no filesystem available for stat","NO_FILESYSTEM")}async close(){this.closed=!0,this.fss=[],this.dirOpeners=[],this.fis=[],delete this.info,this.offset=0,delete this.err}notSupported(e){throw new OverlayFsError(`operation ${e} not supported on directory "${this._name}"`,"OPERATION_NOT_SUPPORTED")}async read(e){this.notSupported("read")}async readAt(e,t){this.notSupported("readAt")}async seek(e,t){this.notSupported("seek")}async write(e){this.notSupported("write")}async writeAt(e,t){this.notSupported("writeAt")}async sync(){this.notSupported("sync")}async truncate(e){this.notSupported("truncate")}async writeString(e){this.notSupported("writeString")}},dirPool=new class{pool=[];get(){return this.pool.length>0?this.pool.pop():new OverlayDir}release(e){e.fss=[],e.dirOpeners=[],e.fis=[],delete e.info,e.offset=0,e._name="",delete e.err,e.closed=!1,this.pool.push(e)}}}});function newOverlayFs(e){return new OverlayFs(e)}var VirtualFileInfo,VirtualFile,globalVirtualFile,init_overlayfs=__esm({"internal/domain/fs/entity/overlayfs.ts"(){init_type3(),init_overlayoptions(),init_overlaydir(),init_log(),getDomainLogger("fs",{component:"overlayfs"}),OverlayFs=class e{fss;mergeDirs;firstWritable;constructor(e){this.fss=[...e.fss],this.mergeDirs=e.dirsMerger,this.firstWritable=e.firstWritable}name(){return"overlayfs"}filesystem(e){return e<0||e>=this.fss.length?null:this.fss[e]}numFilesystems(){return this.fss.length}append(...t){const r=new OverlayOptions({fss:[...this.fss,...t],firstWritable:this.firstWritable,dirsMerger:this.mergeDirs});return new e(r)}withDirsMerger(t){const r=new OverlayOptions({fss:this.fss,firstWritable:this.firstWritable,dirsMerger:t});return new e(r)}writeFs(){if(0===this.fss.length)throw ErrNoFilesystems;return this.fss[0]}async collectDirs(e,t){for(const r of this.fss)await this.collectDirsRecursive(r,e,t)}async collectDirsRecursive(e,t,r){try{(await e.stat(t)).isDir()&&r(e)}catch(e){}const i=e;if(i.filesystem&&i.numFilesystems)for(let e=0;e<i.numFilesystems();e++){const s=i.filesystem(e);s&&await this.collectDirsRecursive(s,t,r)}}async statInternal(e,t){for(let r=0;r<this.fss.length;r++){const i=this.fss[r],[s,n,a,o]=await this.statRecursive(i,e,t);if(null===o||!this.isNotExistError(o))return[s,n,a,o]}return[null,null,!1,ErrFileNotFound]}async statRecursive(e,t,r){try{const r=await e.stat(t);return[e,r,!1,null]}catch(t){if(!this.isNotExistError(t))return[e,null,!1,t]}const i=e;if(i.filesystem&&i.numFilesystems)for(let e=0;e<i.numFilesystems();e++){const s=i.filesystem(e);if(s){const[e,i,n,a]=await this.statRecursive(s,t,r);if(null===a||!this.isNotExistError(a))return[e,i,n,a]}}return[null,null,!1,ErrFileNotFound]}isNotExistError(e){return e.message.includes("ENOENT")||e.message.includes("no such file")||e===ErrFileNotFound}async create(e){if(!this.firstWritable)throw new OverlayFsError("filesystem is read-only","READ_ONLY");return await this.writeFs().create(e)}async mkdir(e,t){if(!this.firstWritable)throw new OverlayFsError("filesystem is read-only","READ_ONLY");return await this.writeFs().mkdir(e,t)}async mkdirAll(e,t){if(!this.firstWritable)throw new OverlayFsError("filesystem is read-only","READ_ONLY");return await this.writeFs().mkdirAll(e,t)}async open(e){if(0===this.fss.length)throw ErrFileNotFound;const[t,r,,i]=await this.statInternal(e,!1);if(i)throw i;if(r.isDir()){const t=[];if(await this.collectDirs(e,e=>{t.push(e)}),0===t.length)throw ErrFileNotFound;return 1===t.length?await t[0].open(e):await async function(e,t,r,i){if(!r)throw new OverlayFsError("info function must not be null","INFO_REQUIRED");const s=dirPool.get(),n={name:e,fss:[...i],info:r,merge:t||defaultDirMerger};return Object.assign(s,new OverlayDir(n)),s}(e,this.mergeDirs,async()=>r,t)}return await t.open(e)}async openFile(e,t,r){const i=!!(1&t)||!!(2&t);if(i&&!this.firstWritable)throw new OverlayFsError("filesystem is read-only","READ_ONLY");return i?await this.writeFs().openFile(e,t,r):await this.open(e)}async remove(e){if(!this.firstWritable)throw new OverlayFsError("filesystem is read-only","READ_ONLY");return await this.writeFs().remove(e)}async removeAll(e){if(!this.firstWritable)throw new OverlayFsError("filesystem is read-only","READ_ONLY");return await this.writeFs().removeAll(e)}async rename(e,t){if(!this.firstWritable)throw new OverlayFsError("filesystem is read-only","READ_ONLY");return await this.writeFs().rename(e,t)}async stat(e){const t="/"===e?"":e,[,r,,i]=await this.statInternal(t,!1);if(i)throw i;return r}async chmod(e,t){if(!this.firstWritable)throw new OverlayFsError("filesystem is read-only","READ_ONLY");return await this.writeFs().chmod(e,t)}async chown(e,t,r){if(!this.firstWritable)throw new OverlayFsError("filesystem is read-only","READ_ONLY");return await this.writeFs().chown(e,t,r)}async chtimes(e,t,r){if(!this.firstWritable)throw new OverlayFsError("filesystem is read-only","READ_ONLY");return await this.writeFs().chtimes(e,t,r)}}}});var Service3,Factory,init_filevitural=__esm({"internal/domain/fs/vo/filevitural.ts"(){init_fs3(),init_fileinfo(),VirtualFileInfo=class{_name;_content;_modTime;constructor(e,t="This is a virtual file."){this._name=e,this._content=t,this._modTime=new Date}name(){return this._name}size(){return Buffer.byteLength(this._content,"utf8")}mode(){return 420}modTime(){return this._modTime}isDir(){return!1}sys(){return null}getContent(){return this._content}},VirtualFile=class{_fileName;_fileContent;_fileInfo=null;constructor(e,t){this._fileName=e,this._fileContent=t}fullName(){return this._fileName}async open(){return{name:()=>this._fileName,close:async()=>{},read:async e=>{const t=Buffer.from(this._fileContent,"utf8"),r=Math.min(e.length,t.length);return t.copy(e,0,0,r),{bytesRead:r,buffer:e}},readAt:async(e,t)=>{const r=Buffer.from(this._fileContent,"utf8"),i=Math.min(t,r.length),s=Math.min(e.length,r.length-i);return s>0&&r.copy(e,0,i,i+s),{bytesRead:s,buffer:e}},seek:async(e,t)=>e,write:async e=>({bytesWritten:e.length,buffer:e}),writeAt:async(e,t)=>({bytesWritten:e.length,buffer:e}),readdir:async e=>[],readdirnames:async e=>[],stat:async()=>this.getFileInfo(),sync:async()=>{},truncate:async e=>{},writeString:async e=>({bytesWritten:Buffer.byteLength(e,"utf8")})}}getFileInfo(){return this._fileInfo||(this._fileInfo=new VirtualFileInfo(this._fileName,this._fileContent)),this._fileInfo}},globalVirtualFile=null}}),init_service4=__esm({"internal/domain/fs/entity/service.ts"(){init_filevitural(),Service3=class{newFileMetaInfo(e){return function(e){const t=(globalVirtualFile||(globalVirtualFile=new VirtualFile("/content/file.txt","This is a virtual file.")),globalVirtualFile.getFileInfo()),r=newFileMeta(e);return new FileInfo(t,r)}(e)}newFileMetaInfoWithContent(e){return function(e){const t=function(e){const t=Math.floor(1e6*Math.random()).toString().padStart(6,"0");return new VirtualFile(`/content/file_${t}.md`,e)}(e),r=t.getFileInfo(),i=newFileMeta(t.fullName(),()=>t.open());return i.setComponentRoot("content"),i.setComponentDir("content"),new FileInfo(r,i)}(e)}}}});function createReadOnlyOverlayFs(e){return(new Factory).createReadOnly(e)}var RootMapping,FilesystemsCollector,init_overlayfs_factory=__esm({"internal/domain/fs/vo/overlayfs-factory.ts"(){init_overlayoptions(),init_overlayfs(),Factory=class{create(e){return newOverlayFs(createDefaultOverlayOptions(e))}createWithOptions(e){return function(e){const t=new OverlayOptions(e);return new OverlayFs(t)}(e)}createReadOnly(e){return newOverlayFs(createDefaultOverlayOptions(e))}createWritable(e){const t=function(e){return newOverlayOptions(e,!0,void 0)}(e);return newOverlayFs(t)}createWithMerger(e,t){return newOverlayFs(createDefaultOverlayOptions(e).withDirsMerger(t))}}}});import*as path14 from"path";var log13,OsFileInfo,OsFile,OsFs,init_filesystemscollector=__esm({"internal/domain/fs/vo/filesystemscollector.ts"(){init_overlayfs_factory(),init_basefs(),init_log(),getDomainLogger("fs",{component:"filesystemscollector"}),RootMapping=class{from;to;toBase;constructor(e,t,r=""){this.from=e,this.to=t,this.toBase=r}fs(e){return newBaseFs(e,[this.to])}},FilesystemsCollector=class{sourceProject;overlayMountsPrompt;overlayMountsWorkflow;overlayMountsContent;overlayMountsLayouts;overlayMountsStatics;overlayMountsAssets;overlayMountsI18n;constructor(e){this.sourceProject=e,this.overlayMountsPrompt=createReadOnlyOverlayFs([]),this.overlayMountsWorkflow=createReadOnlyOverlayFs([]),this.overlayMountsContent=[],this.overlayMountsLayouts=createReadOnlyOverlayFs([]),this.overlayMountsStatics=createReadOnlyOverlayFs([]),this.overlayMountsAssets=createReadOnlyOverlayFs([]),this.overlayMountsI18n=createReadOnlyOverlayFs([])}async collect(e){const t=e.all();for(const e of t){const t=[],r=[],i=[],s=[],n=[],a=[],o=[],l=t=>path14.isAbsolute(t)?["",t]:[e.dir(),this.absPathify(e.dir(),t)],c=e.mounts();for(const e of c){const[c,h]=l(e.source()),u=new RootMapping(e.target(),h,c).fs(this.sourceProject);this.isPrompts(e.target())?r.push(u):this.isWorkflows(e.target())?t.push(u):this.isContent(e.target())?i.push(u):this.isLayouts(e.target())?s.push(u):this.isStatics(e.target())?n.push(u):this.isAssets(e.target())?a.push(u):this.isI18n(e.target())&&o.push(u)}if(t.length>0&&(this.overlayMountsWorkflow=this.overlayMountsWorkflow.append(...t)),r.length>0&&(this.overlayMountsPrompt=this.overlayMountsPrompt.append(...r)),e.isProjectModule())for(const e of i){let t=createReadOnlyOverlayFs([]);t=t.append(e),this.overlayMountsContent.push(t)}s.length>0&&(this.overlayMountsLayouts=this.overlayMountsLayouts.append(...s)),n.length>0&&(this.overlayMountsStatics=this.overlayMountsStatics.append(...n)),a.length>0&&(this.overlayMountsAssets=this.overlayMountsAssets.append(...a)),o.length>0&&(this.overlayMountsI18n=this.overlayMountsI18n.append(...o))}}isPrompts(e){return"prompts"===e||e.startsWith("prompts/")||e.startsWith("/prompts/")}isWorkflows(e){return"workflows"===e||e.startsWith("workflows/")||e.startsWith("/workflows/")}isContent(e){return"content"===e||e.startsWith("content/")||e.startsWith("/content/")}isLayouts(e){return"layouts"===e||e.startsWith("layouts/")||e.startsWith("/layouts/")}isStatics(e){return"static"===e||e.startsWith("static/")||e.startsWith("/static/")}isAssets(e){return"assets"===e||e.startsWith("assets/")||e.startsWith("/assets/")}isI18n(e){return"i18n"===e||e.startsWith("i18n/")||e.startsWith("/i18n/")}absPathify(e,t){return path14.resolve(e,t)}}}});import*as fs from"fs/promises";import*as path15 from"path";var init_osfs=__esm({"internal/domain/fs/vo/osfs.ts"(){init_log(),log13=getDomainLogger("fs",{component:"osfs"}),OsFileInfo=class{constructor(e,t){this.stats=e,this._name=t}name(){return this._name}size(){return this.stats.size}mode(){return this.stats.mode}modTime(){return this.stats.mtime}isDir(){return this.stats.isDirectory()}sys(){return this.stats}},OsFile=class{constructor(e,t="r"){this.filePath=e,this.flags=t}handle=null;closed=!1;position=0;async ensureOpen(){this.handle||this.closed||(this.handle=await fs.open(this.filePath,this.flags))}async close(){if(this.handle){try{await this.handle.close()}catch(e){throw log13.error(`❌ Error closing file handle for ${this.filePath}:`,e),e}this.handle=null}this.closed=!0}async read(e){if(this.closed)throw new Error("File is closed");if(await this.ensureOpen(),!this.handle)throw new Error("Failed to open file");const t=await this.handle.read(e,0,e.length,this.position);return this.position+=t.bytesRead,{bytesRead:t.bytesRead,buffer:e}}async readAt(e,t){if(this.closed)throw new Error("File is closed");if(await this.ensureOpen(),!this.handle)throw new Error("Failed to open file");return{bytesRead:(await this.handle.read(e,0,e.length,t)).bytesRead,buffer:e}}async seek(e,t){if(this.closed)throw new Error("File is closed");switch(t){case 0:default:this.position=e;break;case 1:this.position+=e;break;case 2:if(await this.ensureOpen(),this.handle){const t=await this.handle.stat();this.position=t.size+e}}return this.position}async write(e){if(this.closed)throw new Error("File is closed");if(await this.ensureOpen(),!this.handle)throw new Error("Failed to open file");const t=await this.handle.write(e,0,e.length,this.position);return this.position+=t.bytesWritten,{bytesWritten:t.bytesWritten,buffer:e}}async writeAt(e,t){if(this.closed)throw new Error("File is closed");if(await this.ensureOpen(),!this.handle)throw new Error("Failed to open file");return{bytesWritten:(await this.handle.write(e,0,e.length,t)).bytesWritten,buffer:e}}name(){return this.filePath}async readdir(e){if(this.closed)throw new Error("File is closed");const t=await fs.readdir(this.filePath,{withFileTypes:!0}),r=[],i=e>0?Math.min(e,t.length):t.length;for(let e=0;e<i;e++){const i=t[e],s=path15.join(this.filePath,i.name),n=await fs.stat(s);r.push(new OsFileInfo(n,i.name))}return r}async readdirnames(e){if(this.closed)throw new Error("File is closed");const t=await fs.readdir(this.filePath);return e>0?t.slice(0,e):t}async stat(){if(this.closed)throw new Error("File is closed");const e=await fs.stat(this.filePath);return new OsFileInfo(e,path15.basename(this.filePath))}async sync(){if(this.closed)throw new Error("File is closed");await this.ensureOpen(),this.handle&&await this.handle.sync()}async truncate(e){if(this.closed)throw new Error("File is closed");await this.ensureOpen(),this.handle&&(await this.handle.truncate(e),this.position>e&&(this.position=e))}async writeString(e){const t=Buffer.from(e,"utf8");return{bytesWritten:(await this.write(t)).bytesWritten}}},OsFs=class{async create(e){return await fs.writeFile(e,""),new OsFile(e,"w+")}async mkdir(e,t){await fs.mkdir(e,{mode:t})}async mkdirAll(e,t){await fs.mkdir(e,{mode:t,recursive:!0})}async open(e){return await fs.access(e),(await fs.stat(e)).isDirectory(),new OsFile(e,"r")}async openFile(e,t,r){let i="r";return 1&t&&(i="w"),2&t&&(i="r+"),64&t&&(i="w"),512&t&&(i="w"),1024&t&&(i="a"),new OsFile(e,i)}async remove(e){(await fs.stat(e)).isDirectory()?await fs.rmdir(e):await fs.unlink(e)}async removeAll(e){await fs.rm(e,{recursive:!0,force:!0})}async rename(e,t){await fs.rename(e,t)}async stat(e){const t=await fs.stat(e);return new OsFileInfo(t,path15.basename(e))}name(){return"OsFs"}async chmod(e,t){await fs.chmod(e,t)}async chown(e,t,r){await fs.chown(e,t,r)}async chtimes(e,t,r){await fs.utimes(e,t,r)}}}});var init_overlay_factory=__esm({"internal/domain/fs/vo/overlay-factory.ts"(){init_originfs(),init_fs3(),init_basefs()}});async function createFs(e,t){const r=function(e){const t=e.osFs,r=e.osFs,i=newBaseFs(e.osFs,[e.publish]);return new OriginFs(t,r,i)}(e),i=await async function(e,t){const r=(i=e.getSource(),new FilesystemsCollector(i));var i;return await r.collect(t),r}(r,t),s=newBaseFs(e.osFs,[e.path]);return new Fs2(r,i.overlayMountsPrompt,i.overlayMountsWorkflow,i.overlayMountsContent,i.overlayMountsLayouts,i.overlayMountsStatics,i.overlayMountsAssets,i.overlayMountsI18n,s)}var PageKind,BufWriter,TableOfContentsImpl,HeaderImpl,TOCBuilder,AutoIDGenerator,HighlightResultImpl,DefaultHighlighter,Item,boolRe,intRe,floatRe,_ItemType_name,_ItemType_index,eof,summaryDivider,summaryDividerOrg,delimTOML,delimYAML,delimOrg,leftDelimSc,leftDelimScNoMarkup,rightDelimScNoMarkup,leftDelimScWithMarkup,rightDelimScWithMarkup,leftComment,rightComment,inlineIdentifier,sectionHandlers,sectionHandler,Iterator,pageLexer,init_fs2=__esm({"internal/domain/fs/factory/fs.ts"(){init_fs(),init_overlay_factory(),init_basefs()}}),init_fs3=__esm({"internal/domain/fs/index.ts"(){init_type3(),init_type3(),init_originfs(),init_fs(),init_basefs(),init_overlayfs(),init_overlaydir(),init_service4(),init_filemeta(),init_fileinfo(),init_filevitural(),init_file(),init_dir2(),init_walkway(),init_filesystemscollector(),init_static_copier(),init_overlayoptions(),init_overlayfs_factory(),init_osfs(),init_fs2(),init_overlay_factory()}}),init_type4=__esm({"internal/domain/content/type.ts"(){PageKind={PAGE:"page",HOME:"home",SECTION:"section",TAXONOMY:"taxonomy",TERM:"term",RSS:"rss",SITEMAP:"sitemap",SITEMAP_INDEX:"sitemapindex",ROBOTS_TXT:"robotstxt",STATUS_404:"404"}}}),init_type5=__esm({"internal/domain/markdown/type.ts"(){}}),init_config4=__esm({"internal/domain/markdown/vo/config.ts"(){}}),init_context=__esm({"internal/domain/markdown/vo/context.ts"(){BufWriter=class{buffer;position;capacity;constructor(e=1024){this.capacity=e,this.buffer=new Uint8Array(this.capacity),this.position=0}async write(e){this.ensureCapacity(e.length),this.buffer.set(e,this.position),this.position+=e.length}async writeString(e){const t=(new TextEncoder).encode(e);await this.write(t)}async writeByte(e){this.ensureCapacity(1),this.buffer[this.position]=e,this.position++}bytes(){return this.buffer.slice(0,this.position)}length(){return this.position}truncate(e){if(e<0||e>this.position)throw new Error("Invalid truncate size");this.position=e}ensureCapacity(e){const t=this.position+e;if(t<=this.capacity)return;const r=Math.max(2*this.capacity,t),i=new Uint8Array(r);i.set(this.buffer),this.buffer=i,this.capacity=r}}}}),init_tableofcontents=__esm({"internal/domain/markdown/vo/tableofcontents.ts"(){TableOfContentsImpl=class{constructor(e=[]){this.fragments=e}toHTML(e,t,r){if(0===this.fragments.length)return"";const i=this.filterByLevel(this.fragments,e,t);if(0===i.length)return"";const s=r?"ol":"ul";return`<${s}>\n${this.renderFragments(i,r)}</${s}>\n`}filterByLevel(e,t,r){return e.filter(e=>e.level>=t&&e.level<=r).map(e=>{const i={id:e.id,text:e.text,level:e.level};return e.children&&(i.children=this.filterByLevel(e.children,t,r)),i})}renderFragments(e,t){const r=t?"ol":"ul";return e.map(e=>{let i=` <li><a href="#${e.id}">${this.escapeHTML(e.text)}</a>`;return e.children&&e.children.length>0&&(i+=`\n <${r}>\n${this.renderFragments(e.children,t)} </${r}>`),i+="</li>",i}).join("\n")}escapeHTML(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#x27;")}addFragment(e){this.fragments.push(e)}getFragments(){return[...this.fragments]}},HeaderImpl=class{constructor(e,t,r=[],i=[],s=[]){this._name=e,this._level=t,this._links=r,this._paragraphs=i,this._listParagraphs=s}name(){return this._name}level(){return this._level}links(){return[...this._links]}paragraphs(){return[...this._paragraphs]}listParagraphs(){return[...this._listParagraphs]}addLink(e){this._links.push(e)}addParagraph(e){this._paragraphs.push(e)}addListParagraph(e){this._listParagraphs.push(e)}},TOCBuilder=class{fragments=[];stack=[];addHeading(e,t,r){for(;this.stack.length>0&&this.stack[this.stack.length-1].level>=t;)this.stack.pop();const i={id:r,text:e,level:t,children:[]};if(0===this.stack.length)this.fragments.push(i);else{const e=this.stack[this.stack.length-1];e.children||(e.children=[]),e.children.push(i)}this.stack.push(i)}build(){return new TableOfContentsImpl(this.fragments)}reset(){this.fragments=[],this.stack=[]}},AutoIDGenerator=class{usedIds=new Set;generateID(e,t="github"){let r;switch(t){case"github":default:r=this.githubStyle(e);break;case"github-ascii":r=this.githubAsciiStyle(e);break;case"blackfriday":r=this.blackfridayStyle(e)}if(this.usedIds.has(r)){let e=1,t=`${r}-${e}`;for(;this.usedIds.has(t);)e++,t=`${r}-${e}`;r=t}return this.usedIds.add(r),r}githubStyle(e){return e.toLowerCase().replace(/[^\w\u4e00-\u9fff\s-]/g,"").replace(/\s+/g,"-").replace(/^-+|-+$/g,"")}githubAsciiStyle(e){return e.toLowerCase().replace(/[^\w\s-]/g,"").replace(/\s+/g,"-").replace(/^-+|-+$/g,"")}blackfridayStyle(e){return e.toLowerCase().replace(/[^a-z0-9\s-]/g,"").replace(/\s+/g,"-").replace(/^-+|-+$/g,"")}reset(){this.usedIds.clear()}}}}),init_highlight=__esm({"internal/domain/markdown/vo/highlight.ts"(){HighlightResultImpl=class{constructor(e,t){this.wrappedContent=e,this.innerContent=t}wrapped(){return this.wrappedContent}inner(){return this.innerContent}},DefaultHighlighter=class{constructor(e){this.config=e}async highlight(e,t,r){if(!t||"text"===t||"plain"===t)return this.escapeHTML(e);const i=this.escapeHTML(e),s=`language-${t}`;return this.config.lineNos?this.addLineNumbers(i,s):`<code class="${s}">${i}</code>`}async highlightCodeBlock(e,t){const r=e.type(),i=e.inner(),s=await this.highlight(i,r,t);return new HighlightResultImpl(`<pre>${s}</pre>`,s)}async renderCodeblock(e,t,r){const i=await this.highlightCodeBlock(r);await t.writeString(i.wrapped())}isDefaultCodeBlockRenderer(){return!0}escapeHTML(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#x27;")}addLineNumbers(e,t){const r=e.split("\n").map((e,r)=>{const i=r+this.config.lineNoStart;return this.config.lineNumbersInTable?`<tr><td class="line-number">${i}</td><td class="line-code"><code class="${t}">${e}</code></td></tr>`:`<span class="line-number">${i}</span><code class="${t}">${e}</code>`});return this.config.lineNumbersInTable?`<table class="code-table"><tbody>${r.join("")}</tbody></table>`:r.join("\n")}}}}),init_item=__esm({"pkg/md/parser/item.ts"(){Item=class{Type;Err;low;high;segments;firstByte;isString;content;bytes;constructor(){this.Type=0,this.Err=null,this.low=0,this.high=0,this.segments=[],this.firstByte=0,this.isString=!1,this.content="",this.bytes=[]}Pos(){return this.segments.length>0?this.segments[0].Low:this.low}Val(e){if(0===this.segments.length)return e.slice(this.low,this.high);if(1===this.segments.length)return e.slice(this.segments[0].Low,this.segments[0].High);const t=[];for(const r of this.segments)t.push(e.slice(r.Low,r.High));const r=t.reduce((e,t)=>e+t.length,0),i=new Uint8Array(r);let s=0;for(const e of t)i.set(e,s),s+=e.length;return i}ValStr(e){return(new TextDecoder).decode(this.Val(e))}ValTyped(e){const t=this.ValStr(e);if(this.isString)return t;if(boolRe.test(t))return"true"===t;if(intRe.test(t)){const e=parseInt(t,10);return isNaN(e)?t:e}if(floatRe.test(t)){const e=parseFloat(t);return isNaN(e)?t:e}return t}IsText(){return 18===this.Type||17===this.Type}IsIndentation(){return 17===this.Type}IsNonWhitespace(e){return this.ValStr(e).trim().length>0}IsShortcodeName(){return 13===this.Type}IsInlineShortcodeName(){return 14===this.Type}IsLeftShortcodeDelim(){return 10===this.Type||8===this.Type}IsRightShortcodeDelim(){return 11===this.Type||9===this.Type}IsShortcodeClose(){return 12===this.Type}IsShortcodeParam(){return 15===this.Type}IsShortcodeParamVal(){return 16===this.Type}IsShortcodeMarkupDelimiter(){return 10===this.Type||11===this.Type}IsFrontMatter(){return this.Type>=3&&this.Type<=6}IsDone(){return 0===this.Type||1===this.Type}IsEOF(){return 1===this.Type}IsError(){return 0===this.Type}ToString(e){const t=this.Val(e),r=this.ValStr(e),i=function(e){const t=e;return t<0||t>=_ItemType_index.length-1?`ItemType(${t})`:_ItemType_name.slice(_ItemType_index[t],_ItemType_index[t+1])}(this.Type);switch(!0){case 1===this.Type:return"EOF";case 0===this.Type:return r;case 17===this.Type:return`${i}:[${s=r,s.replace(/ /g,"␣").replace(/\t/g,"→")}]`;case this.Type>19:return`<${r}>`;case t.length>50:return`${i}:${r.substring(0,20)}...`;default:return`${i}:[${r}]`}var s}},boolRe=/^(true|false)$/,intRe=/^[-+]?\d+$/,floatRe=/^[-+]?\d*\.\d+$/,_ItemType_name="tErrortEOFTypeLeadSummaryDividerTypeFrontMatterYAMLTypeFrontMatterTOMLTypeFrontMatterJSONTypeFrontMatterORGTypeIgnoretLeftDelimScNoMarkuptRightDelimScNoMarkuptLeftDelimScWithMarkuptRightDelimScWithMarkuptScClosetScNametScNameInlinetScParamtScParamValtIndentationtTexttKeywordMarker",_ItemType_index=[0,6,10,32,51,70,89,107,117,137,158,180,203,211,218,231,239,250,262,267,281]}});function isSpace(e){return 32===e||9===e}function isAlphaNumericOrHyphen(e){return isAlphaNumeric(e)||45===e}function isEndOfLine(e){return 13===e||10===e}function isAlphaNumeric(e){return 95===e||e>=65&&e<=90||e>=97&&e<=122||e>=48&&e<=57}function lexFrontMatterJSON(e){e.backup();let t=!1,r=0;for(;;){const i=e.next();switch(!0){case i===eof:return e.errorf("unexpected EOF parsing JSON front matter");case 123===i:t||r++;break;case 125===i:t||r--;break;case 34===i:t=!t;break;case 92===i:e.next()}if(0===r)break}return e.consumeCRLF(),e.emit(5),()=>e.lexMainSection()}function lexFrontMatterOrgMode(e){if(e.summaryDivider=summaryDividerOrg,e.backup(),!e.hasPrefix(delimOrg))return()=>e.lexMainSection();e:for(;;){const t=e.next();switch(!0){case 10===t:if(!e.hasPrefix(delimOrg))break e;break;case t===eof:break e}}return e.emit(6),()=>e.lexMainSection()}function lexIntroSection(e){return e.lexIntroSection()}var init_pagelexer=__esm({"pkg/md/parser/pagelexer.ts"(){init_item(),eof=-1,new Uint8Array([239,187,191]),summaryDivider=(new TextEncoder).encode("\x3c!--more--\x3e"),summaryDividerOrg=(new TextEncoder).encode("# more"),delimTOML=(new TextEncoder).encode("+++"),delimYAML=(new TextEncoder).encode("---"),delimOrg=(new TextEncoder).encode("#+"),leftDelimSc=(new TextEncoder).encode("{{"),leftDelimScNoMarkup=(new TextEncoder).encode("{{<"),rightDelimScNoMarkup=(new TextEncoder).encode(">}}"),leftDelimScWithMarkup=(new TextEncoder).encode("{{%"),rightDelimScWithMarkup=(new TextEncoder).encode("%}}"),leftComment=(new TextEncoder).encode("/*"),rightComment=(new TextEncoder).encode("*/"),inlineIdentifier=(new TextEncoder).encode("inline "),sectionHandlers=class{l;skipAll;handlers;skipIndexes;constructor(e){this.l=e,this.skipAll=!1,this.handlers=[],this.skipIndexes=[]}skip(){if(this.skipAll)return-1;this.skipIndexes=[];let e=!1;for(const t of this.handlers){if(t.skipAll)continue;const r=t.skip();-1!==r&&(e=!0,this.skipIndexes.push(r))}return e?function(...e){let t=-1;for(const r of e)r<0||(-1===t||r<t)&&(t=r);return t}(...this.skipIndexes):(this.skipAll=!0,-1)}lex(e){if(this.skipAll)return null;this.l.pos>this.l.start&&this.l.emit(18);for(const t of this.handlers){if(t.skipAll)continue;const[r,i]=t.lexFunc(e,t.l);if(null===r||i)return r}return this.l.pos++,e}},sectionHandler=class{l;skipAll;skipFunc;lexFunc;constructor(e,t,r){this.l=e,this.skipAll=!1,this.skipFunc=t,this.lexFunc=r}skip(){if(this.skipAll)return-1;const e=this.skipFunc(this.l);return-1===e&&(this.skipAll=!0),e}},Iterator=class{items;lastPos;constructor(e){this.items=e,this.lastPos=-1}Next(){return this.lastPos++,this.Current()}Current(){if(this.lastPos>=this.items.length){const e=new Item;return e.Type=0,e.Err=new Error("no more tokens"),e}return this.items[this.lastPos]}Backup(){if(this.lastPos<0)throw new Error("need to go forward before going back");this.lastPos--}Pos(){return this.lastPos}IsValueNext(){const e=this.Peek();return 0!==e.Type&&1!==e.Type}Peek(){return this.items[this.lastPos+1]}PeekWalk(e){for(let t=this.lastPos+1;t<this.items.length&&e(this.items[t]);t++);}Consume(e){for(let t=0;t<e;t++){const e=this.Next();if(0===e.Type||1===e.Type){this.Backup();break}}}LineNumber(e){const t=new Uint8Array([10]),r=e.slice(0,this.Current().low);let i=0;for(let e=0;e<r.length;e++)r[e]===t[0]&&i++;return i+1}},pageLexer=class{input;stateStart;state;pos;start;width;sectionHandlers;cfg;summaryDivider;summaryDividerChecked;lexerShortcodeState;items;err;inFrontMatter;parenDepth;constructor(e,t,r){this.input=e,this.stateStart=t,this.state=null,this.pos=0,this.start=0,this.width=0,this.cfg=r,this.summaryDivider=null,this.summaryDividerChecked=!1,this.err=null,this.items=[],this.inFrontMatter=!1,this.parenDepth=0,this.lexerShortcodeState={currLeftDelimItem:8,currRightDelimItem:9,isInline:!1,currShortcodeName:"",closingState:0,elementStepNum:0,paramElements:0,paramState:0,openShortcodes:{}},this.lexSummaryDivider=this.lexSummaryDivider.bind(this),this.lexMainSection=this.lexMainSection.bind(this),this.lexIdentifierInShortcode=this.lexIdentifierInShortcode.bind(this),this.lexEndOfShortcode=this.lexEndOfShortcode.bind(this),this.lexShortcodeLeftDelim=this.lexShortcodeLeftDelim.bind(this),this.lexShortcodeRightDelim=this.lexShortcodeRightDelim.bind(this),this.lexShortcodeParam=this.lexShortcodeParam.bind(this),this.lexShortcodeValue=this.lexShortcodeValue.bind(this),this.lexShortcodeValueQuoted=this.lexShortcodeValueQuoted.bind(this),this.lexShortcodeValueUnquoted=this.lexShortcodeValueUnquoted.bind(this),this.lexInsideShortcode=this.lexInsideShortcode.bind(this),this.lexDone=this.lexDone.bind(this),this.sectionHandlers=function(e){const t=new sectionHandlers(e),r=new sectionHandler(e,e=>e.index(leftDelimSc),(e,t)=>{if(!t.isShortCodeStart())return[e,!1];if(t.lexerShortcodeState.isInline){const e=t.input.slice(t.pos+3),r=function(e){for(let t=0;t<e.length;t++)if(!isSpace(e[t])){if(47===e[t])return t;break}return-1}(e);if(r!==t.input.length-1){const i=(new TextDecoder).decode(e.slice(r+1)).trim();if(-1===r||!i.startsWith(t.lexerShortcodeState.currShortcodeName+" "))return[t.errorf("inline shortcodes do not support nesting"),!0]}}return t.hasPrefix(leftDelimScWithMarkup)?(t.lexerShortcodeState.currLeftDelimItem=10,t.lexerShortcodeState.currRightDelimItem=11):(t.lexerShortcodeState.currLeftDelimItem=8,t.lexerShortcodeState.currRightDelimItem=9),[t.lexShortcodeLeftDelim,!0]}),i=new sectionHandler(e,e=>e.summaryDividerChecked||!e.summaryDivider?-1:e.index(e.summaryDivider),(e,t)=>t.summaryDivider&&t.hasPrefix(t.summaryDivider)?(t.summaryDividerChecked=!0,t.pos+=t.summaryDivider.length,t.consumeSpace(),t.emit(2),[e,!0]):[e,!1]);return t.handlers=[r,i],t.skipIndexes=new Array(t.handlers.length),t}(this)}Iterator(){return e=this.items,new Iterator(e);var e}Input(){return this.input}run(){for(this.state=this.stateStart;null!==this.state;)this.state=this.state(this);return this}next(){if(this.pos>=this.input.length)return this.width=0,eof;const e=this.input[this.pos];return this.width=1,this.pos+=this.width,e}peek(){const e=this.next();return this.backup(),e}backup(){this.pos-=this.width}append(e){e.Pos()<this.input.length&&(7===e.Type&&239===this.input[e.Pos()]?e.firstByte=239:e.firstByte=this.input[e.Pos()]),this.items.push(e)}emit(e){const t=()=>{this.start=this.pos};if(18===e)for(let r=this.pos-1;r>=this.start;r--){const i=this.input[r];if(32!==i&&9!==i&&13!==i&&10!==i)break;if(r===this.start&&10!==i){const e=new Item;return e.Type=17,e.low=this.start,e.high=this.pos,this.append(e),void t()}if(10===i&&r<this.pos-1){const i=new Item;i.Type=e,i.low=this.start,i.high=r+1,this.append(i);const s=new Item;return s.Type=17,s.low=r+1,s.high=this.pos,this.append(s),void t()}if(10===i&&r===this.pos-1)break}const r=new Item;r.Type=e,r.low=this.start,r.high=this.pos,r.low<this.input.length&&(7===e&&239===this.input[r.low]?r.firstByte=239:r.firstByte=this.input[r.low]),this.append(r),t()}emitString(e){const t=new Item;t.Type=e,t.low=this.start,t.high=this.pos,t.isString=!0,this.pos>this.start&&(t.firstByte=this.input[this.start]),this.items.push(t),this.start=this.pos}isEOF(){return this.pos>=this.input.length}ignoreEscapesAndEmit(e,t){let r=this.start,i=r;const s=[];for(;r<this.pos;){const e=1;92===this.input[r]&&(r>i&&s.push({Low:i,High:r}),i=r+e),r+=e}if(i<this.pos&&s.push({Low:i,High:this.pos}),s.length>0){const t=new Item;t.Type=e,t.segments=s,s[0].High>s[0].Low&&(t.firstByte=this.input[s[0].Low]),this.items.push(t),this.start=this.pos}this.start=this.pos}current(){return this.input.slice(this.start,this.pos)}ignore(){this.start=this.pos}errorf(e,...t){const r=new Error(e.replace(/%[a-z]/g,()=>String(t.shift()))),i=new Item;return i.Type=0,i.Err=r,i.low=this.start,i.high=this.pos,this.append(i),null}consumeCRLF(){let e=!1;const t=this.peek();return 13===t?(this.next(),10===this.peek()&&(this.next(),e=!0)):10===t&&(this.next(),e=!0),e}consumeToSpace(){for(;;){const e=this.next();if(e===eof||isSpace(e))return void this.backup()}}consumeSpace(){for(;;){const e=this.next();if(e===eof||!this.isUnicodeSpace(e))return void this.backup()}}isUnicodeSpace(e){return 32===e||9===e||10===e||12===e||13===e||133===e||160===e||8192===e||8193===e||8194===e||8195===e||8196===e||8197===e||8198===e||8199===e||8200===e||8201===e||8202===e||8232===e||8233===e||8239===e||8287===e||12288===e}index(e){const t=this.input.slice(this.pos),r=e.length,i=t.length;if(r>i)return-1;e:for(let s=0;s<=i-r;s++){for(let i=0;i<r;i++)if(t[s+i]!==e[i])continue e;return s}return-1}hasPrefix(e){if(this.pos+e.length>this.input.length)return!1;for(let t=0;t<e.length;t++)if(this.input[this.pos+t]!==e[t])return!1;return!0}isShortCodeStart(){return this.hasPrefix(leftDelimScWithMarkup)||this.hasPrefix(leftDelimScNoMarkup)}lexFrontMatterSection(e,t,r,i){for(let e=0;e<2;e++)if(this.next()!==t)return this.errorf(`invalid ${r} delimiter`);let s,n=this.consumeCRLF();for(this.ignore();;){if(!n&&(s=this.next(),s===eof))return this.errorf(`EOF looking for end ${r} front matter delimiter`);if((n||isEndOfLine(s))&&this.hasPrefix(i)){this.emit(e),this.pos+=3,this.consumeCRLF(),this.ignore();break}n=!1}return()=>this.lexMainSection()}currentLeftShortcodeDelimItem(){return this.lexerShortcodeState.currLeftDelimItem}currentRightShortcodeDelimItem(){return this.lexerShortcodeState.currRightDelimItem}currentLeftShortcodeDelim(){return 10===this.lexerShortcodeState.currLeftDelimItem?leftDelimScWithMarkup:leftDelimScNoMarkup}currentRightShortcodeDelim(){return 11===this.lexerShortcodeState.currRightDelimItem?rightDelimScWithMarkup:rightDelimScNoMarkup}lexIdentifier(){for(;;)if(!isAlphaNumericOrHyphen(this.next()))return this.backup(),0===(new TextDecoder).decode(this.input.slice(this.start,this.pos)).length||this.emit(15),null}lexMainSection(){if(this.isEOF())return()=>this.lexDone();const e=this.sectionHandlers.skip();if(-1===e)return this.pos=this.input.length,()=>this.lexDone();e>0&&(this.pos+=e);const t=this.sectionHandlers.lex(this.lexMainSection);return null!==t?t:(this.pos=this.input.length,this.lexDone)}lexInlineShortcodeContent(){for(;;){if(this.pos>=this.input.length)return this.errorf("unclosed inline shortcode");if(this.hasPrefix(leftDelimScWithMarkup)||this.hasPrefix(leftDelimScNoMarkup))return this.errorf("inline shortcodes do not support nesting");if(this.hasPrefix(this.currentRightShortcodeDelim()))return this.backup(),this.pos>this.start&&this.emit(18),()=>this.lexShortcodeRightDelim();this.next()}}lexIdentifierInShortcode(){let e=!1;for(;;){const t=this.next();switch(!0){case isAlphaNumericOrHyphen(t):case 47===t:break;case 46===t:if(this.lexerShortcodeState.isInline=this.hasPrefix(inlineIdentifier),!this.lexerShortcodeState.isInline)return this.errorf("period in shortcode name only allowed for inline identifiers");break;default:this.backup();const r=(new TextDecoder).decode(this.input.slice(this.start,this.pos));return this.lexerShortcodeState.closingState>0&&!this.lexerShortcodeState.openShortcodes[r]?this.errorf(`closing tag for shortcode '${r}' does not match start tag`):(this.lexerShortcodeState.closingState>0&&(this.lexerShortcodeState.openShortcodes[r]=!1,e=!0),this.lexerShortcodeState.closingState=0,this.lexerShortcodeState.currShortcodeName=r,this.lexerShortcodeState.openShortcodes[r]=!0,this.lexerShortcodeState.elementStepNum++,this.lexerShortcodeState.isInline?this.emit(14):this.emit(13),e?()=>this.lexEndOfShortcode():this.lexInsideShortcode)}}}lexEndOfShortcode(){return this.lexerShortcodeState.isInline=!1,this.hasPrefix(this.currentRightShortcodeDelim())?()=>this.lexShortcodeRightDelim():!0!==isSpace(this.next())?this.errorf("unclosed shortcode"):(this.ignore(),()=>this.lexEndOfShortcode())}lexShortcodeLeftDelim(){return this.pos+=this.currentLeftShortcodeDelim().length,this.isComment()?()=>this.lexComment():(this.emit(this.lexerShortcodeState.currLeftDelimItem),this.lexerShortcodeState.elementStepNum=0,this.lexerShortcodeState.paramElements=0,this.lexerShortcodeState.paramState=0,this.start=this.pos,this.lexInsideShortcode)}peekString(e){const t=(Uint8Array,e.length);if(this.pos+t>this.input.length)return null;const r=this.input.slice(this.pos,this.pos+t);if(e instanceof Uint8Array){for(let i=0;i<t;i++)if(r[i]!==e[i])return null;return(new TextDecoder).decode(r)}{const t=(new TextDecoder).decode(r);return t===e?t:null}}lexSummaryDivider(){if(!this.hasPrefix(summaryDivider))return null;if(this.start<this.pos){const e=new Item;e.Type=18,e.low=this.start,e.high=this.pos,e.low<this.input.length&&(e.firstByte=this.input[e.low]),this.append(e)}const e=new Item;return e.Type=2,e.low=this.pos,e.high=this.pos+summaryDivider.length,e.low<this.input.length&&(e.firstByte=this.input[e.low]),this.append(e),this.pos+=summaryDivider.length,this.start=this.pos,()=>this.lexMainSection()}handleBOM(){if(this.pos+3<=this.input.length){const e=this.input.slice(this.pos,this.pos+3);if(239===e[0]&&187===e[1]&&191===e[2]){const e=new Item;return e.Type=7,e.low=this.pos,e.high=this.pos+3,e.firstByte=239,this.append(e),this.pos+=3,this.start=this.pos,!0}}return!1}lexIntroSection(){this.summaryDivider=summaryDivider,0===this.pos&&this.handleBOM();e:for(;;){const e=this.next();if(e===eof)break;switch(!0){case 43===e:if(this.hasPrefix(delimTOML.slice(1)))return()=>this.lexFrontMatterSection(4,e,"TOML",delimTOML);this.backup();break e;case 45===e:if(this.hasPrefix(delimYAML.slice(1)))return()=>this.lexFrontMatterSection(3,e,"YAML",delimYAML);this.backup();break e;case 123===e:return lexFrontMatterJSON;case 35===e:return lexFrontMatterOrgMode;case 65279===e:this.emit(7);break;case!isSpace(e)&&!isEndOfLine(e):break e}}return()=>this.lexMainSection()}lexInsideShortcode(){if(this.hasPrefix(this.currentRightShortcodeDelim()))return this.lexShortcodeRightDelim;const e=this.next();if(e===eof)return this.errorf("unclosed shortcode action");if(isSpace(e)||isEndOfLine(e))this.ignore();else{if(61===e){this.consumeSpace(),this.ignore();const e=this.peek();return 34===e||92===e?this.lexShortcodeQuotedParamVal(92!==e,16):96===e?this.lexShortCodeParamRawStringVal(16):this.lexShortcodeParamVal}if(47===e){if(""===this.lexerShortcodeState.currShortcodeName)return this.errorf("got closing shortcode, but none is open");this.lexerShortcodeState.closingState++,this.lexerShortcodeState.isInline=!1,this.emit(12)}else{if(92!==e)return this.lexerShortcodeState.elementStepNum>0&&(isAlphaNumericOrHyphen(e)||34===e||96===e)?(this.backup(),this.lexShortcodeParam(!1)):isAlphaNumeric(e)?(this.backup(),this.lexIdentifierInShortcode):this.errorf(`unrecognized character in shortcode action: U+${e.toString(16).toUpperCase()} '${String.fromCharCode(e)}'. Note: Parameters with non-alphanumeric args must be quoted`);if(this.ignore(),34===this.peek()||96===this.peek())return this.lexShortcodeParam(!0)}}return this.lexInsideShortcode}lexShortcodeParam(e){let t,r=!0,i=!1;for(;;){if(t=this.next(),r){if(34===t||96===t&&!e)return 2===this.lexerShortcodeState.paramElements?this.errorf("got quoted positional parameter. Cannot mix named and positional parameters"):(this.lexerShortcodeState.paramElements=1,this.backup(),34===t?()=>this.lexShortcodeQuotedParamVal(!e,15):()=>this.lexShortCodeParamRawStringVal(15));if(96===t&&e)return this.errorf("unrecognized escape character");r=!1}else if(61===t){this.backup(),i=!0;break}if(!isAlphaNumericOrHyphen(t)&&46!==t){this.backup();break}}if(0===this.lexerShortcodeState.paramElements)this.lexerShortcodeState.paramElements++,i&&this.lexerShortcodeState.paramElements++;else{if(i&&1===this.lexerShortcodeState.paramElements)return this.errorf(`got named parameter '${(new TextDecoder).decode(this.current())}'. Cannot mix named and positional parameters`);if(!i&&2===this.lexerShortcodeState.paramElements)return this.errorf(`got positional parameter '${(new TextDecoder).decode(this.current())}'. Cannot mix named and positional parameters`)}return this.emit(15),this.lexInsideShortcode}lexShortcodeParamVal(){const e=this.next();if(isSpace(e))return this.ignore(),()=>this.lexShortcodeParamVal();switch(this.backup(),e){case 34:return this.next(),this.ignore(),()=>this.lexShortcodeQuotedParamVal(!1,16);case 96:return this.next(),this.ignore(),()=>this.lexShortCodeParamRawStringVal(16);default:return()=>this.lexShortcodeValueUnquoted()}}lexShortcodeValueUnquoted(){for(;;){const e=this.next();if(e===eof||isSpace(e)||this.isRightShortcodeDelim())return this.backup(),this.pos>this.start&&this.emit(16),this.lexInsideShortcode}}lexShortcodeQuotedParamVal(e,t){let r=!1,i=!1,s=0;e:for(;;){const t=this.next();switch(!0){case 92===t:if(34===this.peek()){if(r&&!e){this.backup();break e}r&&(i=!0,s=1)}else if(96===this.peek())return this.errorf("unrecognized escape character");break;case t===eof:case 10===t:return this.errorf(`unterminated quoted string in shortcode parameter-argument: '${(new TextDecoder).decode(this.current())}'`);case 34===t:if(0===s){if(r){this.backup();break e}r=!0,this.ignore()}else s=0}}i?this.ignoreEscapesAndEmit(t,!0):this.emitString(t);const n=this.next();return 92===n?34===this.peek()&&(this.ignore(),this.next(),this.ignore()):34===n?this.ignore():this.backup(),this.lexInsideShortcode}lexShortCodeParamRawStringVal(e){let t=!1;e:for(;;)switch(this.next()){case 96:if(t){this.backup();break e}t=!0,this.ignore();break;case eof:return this.errorf(`unterminated raw string in shortcode parameter-argument: '${(new TextDecoder).decode(this.input.slice(this.start,this.pos))}'`)}return this.emitString(e),this.next(),this.ignore(),this.lexInsideShortcode}lexDone(){return this.pos>this.start&&this.emit(18),this.emit(1),null}lexShortcodeRightDelim(){return this.pos+=this.currentRightShortcodeDelim().length,this.emit(this.lexerShortcodeState.currRightDelimItem),this.lexerShortcodeState.closingState=0,()=>this.lexMainSection()}lexShortcodeValue(){switch(this.next()){case eof:return this.errorf("unterminated quoted string in shortcode parameter");case 32:case 9:return this.ignore(),()=>this.lexShortcodeValue();case 34:return this.ignore(),()=>this.lexShortcodeValueQuoted();default:return this.backup(),()=>this.lexShortcodeValueUnquoted()}}lexShortcodeValueQuoted(){for(;;)switch(this.next()){case eof:return this.errorf("unterminated quoted string in shortcode parameter");case 92:34===this.peek()&&this.next();break;case 34:return this.backup(),this.emitString(16),this.next(),this.ignore(),this.lexInsideShortcode}}isRightShortcodeDelim(){return this.hasPrefix(this.currentRightShortcodeDelim())}lexComment(){const e=this.index(new Uint8Array([...rightComment,...this.currentRightShortcodeDelim()]));return e<=1?this.errorf("comment must be closed"):(this.emit(18),this.pos+=leftComment.length,this.ignore(),this.pos+=e-leftComment.length,this.emit(18),this.pos+=rightComment.length,this.ignore(),this.pos+=this.currentRightShortcodeDelim().length,this.emit(18),this.lexMainSection)}isComment(){return!(this.pos+2>this.input.length)&&47===this.input[this.pos]&&42===this.input[this.pos+1]}}}});var log14,init_pageparser=__esm({"pkg/md/parser/pageparser.ts"(){init_item(),init_pagelexer(),init_pagelexer()}});var log15,SourceParseInfo,log16,ShortcodeImpl,ShortcodeParser,SHORTCODE_PLACEHOLDER_PREFIX,init_pageparser2=__esm({"internal/domain/markdown/vo/pageparser.ts"(){init_log(),init_pageparser(),log14=getDomainLogger("markdown",{component:"pageparser"})}}),init_parseinfo=__esm({"internal/domain/markdown/vo/parseinfo.ts"(){init_pageparser2(),init_item(),init_pagelexer(),init_log(),log15=getDomainLogger("markdown",{component:"parseinfo"}),SourceParseInfo=class{source;posMainContent=-1;itemsStep1=[];handlers;constructor(e,t){this.source=e,this.handlers=t,this.validateHandlers()}validateHandlers(){if(!this.handlers.frontMatterHandler())throw new Error("no front matter handler");if(!this.handlers.summaryHandler())throw new Error("no summary handler");if(!this.handlers.shortcodeHandler())throw new Error("no shortcode handler");if(!this.handlers.bytesHandler())throw new Error("no bytes handler")}isEmpty(){return 0===this.itemsStep1.length}async parse(){const e=function(e,t={}){const[r,i]=function(e,t){const[r,i]=function(e,t){const r=function(e,t,r){return new pageLexer(e,lexIntroSection,r)}(e,0,t);return r.run(),[r,null]}(e,t);return i?[[],i]:[r.items,r.err]}(e,t);if(i)throw log14.error("Error parsing bytes:",i),i;return r}(this.source,{});this.itemsStep1=e}async handle(){if(this.isEmpty())return;const e=new Iterator(this.itemsStep1);for(;;){const t=e.Next();try{if(7===t.Type)log15.info(`Ignoring item at position ${t.Pos()}: ${t.ValStr(this.source)}`);else if(t.IsFrontMatter()){await this.handlers.frontMatterHandler()(t);const r=e.Peek();r.IsDone()||(this.posMainContent=r.Pos())}else if(2===t.Type)await this.handlers.summaryHandler()(t,e);else if(t.IsLeftShortcodeDelim()){e.Backup();const t=e.Current();await this.handlers.shortcodeHandler()(t,e)}else{if(t.IsEOF())break;if(t.IsError())throw log15.error(`Error parsing item at position ${t.Pos()}: ${t.Err}`),this.createError(t.Err||new Error("Unknown parsing error"),t);await this.handlers.bytesHandler()(t)}}catch(e){throw this.createError(e,t)}}}getMainContentPosition(){return this.posMainContent}getItems(){return this.itemsStep1}getSource(){return this.source}createError(e,t){const r=function(e,t,r){const i="string"==typeof t?(s=t,(new TextEncoder).encode(s)):t;var s;if(r<0)return{filename:e,line:1,column:1,offset:0};let n=1,a=1;for(let e=0;e<Math.min(r,i.length);e++)10===i[e]?(n++,a=1):a++;return{filename:e,line:n,column:a,offset:r}}("",this.source,t.Pos()),i=new Error(`${e.message} at line ${r.line}, column ${r.column}`);return i.position=r,i}}}});function createShortcodePlaceholder(e,t,r){return`${SHORTCODE_PLACEHOLDER_PREFIX}${e}${t}${r}HBHB`}function indexNonWhiteSpace2(e,t){const r=t.charCodeAt(0);for(let t=0;t<e.length;t++)if(!isSpace2(e[t])&&e[t]===r)return t;return-1}function isSpace2(e){return 32===e||9===e||13===e||10===e}var MediaType,INTERNAL_SUMMARY_DIVIDER_PRE,Content,RenderingResultImpl,ResultImpl,log18,MarkdownImpl,init_shortcode=__esm({"internal/domain/markdown/vo/shortcode.ts"(){init_log(),log16=getDomainLogger("markdown",{component:"vo/shortcode"}),ShortcodeImpl=class{name;params;pos;length;rawContent;placeholder;inline;closed;inner;ordinal;indentation;doMarkup;isClosing;info;templs;constructor(e=0,t="",r=null,i=0,s=0,n=!1,a=!1){this.ordinal=e,this.name=t,this.params=r,this.pos=i,this.length=s,this.rawContent="",this.inline=n,this.closed=a,this.doMarkup=!1,this.isClosing=!1,this.placeholder="",this.inner=[]}needsInner(){return!this.inline}},ShortcodeParser=class{shortcodes=[];nameSet=new Set;source;ordinal=0;pid;openShortcodes=new Map;paramElements=0;constructor(e,t=Date.now()){this.source=e,this.pid=t}parseItem(e,t){const r=this.extractShortcode(this.ordinal,0,t);if(!r)throw new Error("Failed to extract shortcode");r.pos=e.Pos()+e.ValStr(this.source).length,r.length=t.Current().Pos()+t.Current().ValStr(this.source).length-r.pos;const i=this.source.slice(r.pos,r.pos+r.length);return r.rawContent=(new TextDecoder).decode(i),r.name&&this.nameSet.add(r.name),r.params??=[],r.placeholder=createShortcodePlaceholder("s",this.pid,this.ordinal),this.ordinal++,this.shortcodes.push(r),r}extractShortcode(e,t,r){const i=new ShortcodeImpl(e);if(r.Pos()>0){r.Backup();const e=r.Next();e.IsIndentation()&&(i.indentation=e.ValStr(this.source))}let s=0,n=0;const a=t+1;let o=!1;const l="failed to extract shortcode";let c=0;for(;;){const e=r.Next();if(e.IsLeftShortcodeDelim()){const t=r.Peek();if(t.IsRightShortcodeDelim())throw new Error("shortcode has no name");if(t.IsShortcodeClose())continue;if(s>0){r.Backup();const e=this.extractShortcode(n,a,r);n++,e&&e.name&&(this.nameSet.add(e.name),Array.isArray(i.inner)||(i.inner=[]),i.inner.push(e))}else i.doMarkup=e.IsShortcodeMarkupDelimiter();s++}else if(e.IsRightShortcodeDelim()){if(!i.inline&&!i.needsInner())return this.openShortcodes.set(i.name,!1),i}else{if(e.IsShortcodeClose()){o=!0;const e=r.Peek();if(!i.inline&&!i.needsInner()){if(e.IsError())continue;throw new Error(`${l}: shortcode "${i.name}" does not evaluate .Inner or .InnerDeindent, yet a closing tag was provided`)}return e.IsRightShortcodeDelim()?r.Consume(1):(i.isClosing=!0,r.Consume(2)),i.inline||this.openShortcodes.set(i.name,!1),i}if(e.IsText()){Array.isArray(i.inner)||(i.inner=[]);const t=e.ValStr(this.source);i.inner.push(t)}else if(e.IsShortcodeName()||e.IsInlineShortcodeName()){if(i.name=e.ValStr(this.source).trim(),i.inline=e.IsInlineShortcodeName(),this.openShortcodes.has(i.name)&&this.openShortcodes.get(i.name))throw new Error(`shortcode ${i.name} nested in itself`);if(i.inline||this.openShortcodes.set(i.name,!0),i.inline){const e=this.source.slice(r.Pos()+3),t=indexNonWhiteSpace2(e,"/");if(t!==this.source.length-1){const r=(new TextDecoder).decode(e.slice(t+1));if(-1===t||!r.startsWith(i.name+" "))throw new Error("inline shortcodes do not support nesting")}}}else if(e.IsShortcodeParam()){if(!r.IsValueNext()){log16.warn(`${l}: shortcode "${i.name}" has a parameter without a value`);continue}if(r.Peek().IsShortcodeParamVal())if(null===i.params||void 0===i.params){const t={},s=e.ValStr(this.source);r.Next(),t[s]=r.Current().ValTyped(this.source),i.params=t}else{if(Array.isArray(i.params))throw new Error(`${l}: invalid state: invalid param type Array for shortcode "${i.name}", expected a map`);{const t=e.ValStr(this.source);r.Next(),i.params[t]=r.Current().ValTyped(this.source)}}else if(null===i.params||void 0===i.params){const t=[];t.push(e.ValTyped(this.source)),i.params=t}else{if(!Array.isArray(i.params))throw new Error(`${l}: invalid state: invalid param type Object for shortcode "${i.name}", expected an array`);i.params.push(e.ValTyped(this.source))}}else if(e.IsShortcodeParamVal()){if(0===c&&(c=1),Array.isArray(i.params))i.params.push(e.ValTyped(this.source));else if(null===i.params||void 0===i.params){const t=[];t.push(e.ValTyped(this.source)),i.params=t}}else if(e.IsDone()){if(!e.IsError()&&!o&&i.needsInner())throw new Error(`${l}: shortcode "${i.name}" must be closed or self-closed`);r.Backup();break}}}return i.inline||this.openShortcodes.set(i.name,!1),i}getShortcodes(){return this.shortcodes}getNames(){return Array.from(this.nameSet)}},SHORTCODE_PLACEHOLDER_PREFIX="HAHAHUGOSHORTCODE",createShortcodePlaceholder("TOC",0,0)}}),init_type6=__esm({"pkg/media/type.ts"(){MediaType=class{type;mainType;subType;delimiter;firstSuffix;mimeSuffix;suffixesCSV;constructor(e){this.type=e.type,this.mainType=e.mainType,this.subType=e.subType,this.delimiter=e.delimiter,this.firstSuffix=e.firstSuffix,this.mimeSuffix=e.mimeSuffix,this.suffixesCSV=e.suffixesCSV}sub(){if(this.subType)return this.subType;const e=this.type.split("/");return 2===e.length?e[1].split("+")[0]:""}getMimeSuffix(){if(this.mimeSuffix)return this.mimeSuffix;const e=this.type.indexOf("+");return-1!==e?this.type.substring(e+1):void 0}getSuffixList(){return this.suffixesCSV?this.suffixesCSV.split(","):[]}}}}),init_content=__esm({"internal/domain/markdown/vo/content.ts"(){init_type6(),init_log(),getDomainLogger("markdown",{component:"content"}),INTERNAL_SUMMARY_DIVIDER_PRE=(new TextEncoder).encode("\n\nHUGOMORE42\n\n"),Content=class{hasSummaryDivider=!1;summaryTruncated=!1;rawSource;items=[];renderer;constructor(e,t){this.rawSource=e,this.renderer=t}isEmpty(){return!this.rawSource||0===this.rawSource.length}setSummaryDivider(){this.hasSummaryDivider=!0}getHasSummaryDivider(){return this.hasSummaryDivider}setSummaryTruncated(){this.summaryTruncated=!0}getTruncated(){return this.summaryTruncated}addReplacement(e,t){const r={val:e,source:t};this.items.push(r)}addShortcode(e){this.items.push(e)}addItem(e){this.items.push(e)}addItems(...e){this.items.push(...e)}rawContent(){return(new TextDecoder).decode(this.rawSource)}pureContent(){const e=[],t=new TextDecoder,r=new TextEncoder;for(const t of this.items)if(this.isItem(t)){const r=this.rawSource.slice(t.Pos(),t.Pos()+t.Val(this.rawSource).length);e.push(r)}else this.isContentReplacement(t)?e.push(t.val):this.isShortcode(t)&&e.push(r.encode(t.placeholder));const i=e.reduce((e,t)=>e+t.length,0),s=new Uint8Array(i);let n=0;for(const t of e)s.set(t,n),n+=t.length;return t.decode(s)}pureContentWithoutPlaceholder(){const e=[],t=new TextDecoder;for(const t of this.items)if(this.isItem(t)){const r=this.rawSource.slice(t.Pos(),t.Pos()+t.Val(this.rawSource).length);e.push(r)}else this.isContentReplacement(t)?e.push(t.val):this.isShortcode(t);const r=e.reduce((e,t)=>e+t.length,0),i=new Uint8Array(r);let s=0;for(const t of e)i.set(t,s),s+=t.length;return t.decode(i)}renderedContent(e){let t=this.pureContent();if(e)for(const r of this.items)if(this.isShortcode(r)){const i=e(r);t=t.replace(r.placeholder,i)}return t}async renderedContentAsync(e){let t=await this.renderer.render(this.pureContent());if(e)for(const r of this.items)if(this.isShortcode(r))try{const i=await e(r);t=t.replace(r.placeholder,i)}catch(e){}return t}getItems(){return[...this.items]}getShortcodes(){return this.items.filter(this.isShortcode)}getTextItems(){return this.items.filter(this.isItem)}getReplacements(){return this.items.filter(this.isContentReplacement)}extractSummary(e,t){const r=(new TextDecoder).decode(e),i=this.extractSummaryFromHTML(t,r,70,this.containsCJK(r)),s=i.summaryLowHigh.high>i.summaryLowHigh.low?r.substring(i.summaryLowHigh.low,i.summaryLowHigh.high).trim():"";if(s)return this.summaryTruncated=i.truncated,{summary:s,truncated:i.truncated};const n=this.trimShortHTML(e);return this.summaryTruncated=n.length<e.length,{summary:(new TextDecoder).decode(e),truncated:this.summaryTruncated}}extractSummaryFromHTML(e,t,r,i){const s={source:t,summaryLowHigh:{low:0,high:t.length},truncated:!1};if(r<=0)return s;let n=0;const a=t.split(/\s+/);for(let e=0;e<a.length&&n<r;e++){const o=a[e].trim();if(0!==o.length&&!this.isProbablyHTMLToken(o)){if(i){const e=this.stripHTML(o),t=[...e].length;n+=e.length===e.replace(/[^\u0000-\u007F]/g,"").length?1:t}else n+=1;if(n>=r){const r=a.slice(0,e+1).join(" "),i=t.indexOf(r)+r.length;s.summaryLowHigh={low:0,high:Math.min(i,t.length)},s.truncated=!0;break}}}return s}containsCJK(e){return/[\u4e00-\u9fff\u3400-\u4dbf\u3040-\u309f\u30a0-\u30ff\uac00-\ud7af]/.test(e)}isProbablyHTMLToken(e){return">"===e||/^<\/?[A-Za-z]+>?$/.test(e)||/^[A-Za-z]+=["']/.test(e)}stripHTML(e){return e.replace(/<[^>]*>/g,"").replace(/\s+/g," ").trim()}trimShortHTML(e){const t=new TextDecoder,r=new TextEncoder;let i=t.decode(e);return 1===(i.match(/<p>/g)||[]).length&&(i=i.trim(),i.startsWith("<p>")&&i.endsWith("</p>")&&(i=i.slice(3,-4).trim())),r.encode(i)}cleanDividerPlaceholders(e){return this.hasSummaryDivider?e.replace(new RegExp("HUGOMORE42","g"),""):e}getDividedSummary(e){const t=e;if(this.hasSummaryDivider){const e=t.indexOf("HUGOMORE42");if(-1!==e)return t.substring(0,e).trim()}return""}async getRenderedSummary(e,t){if(this.hasSummaryDivider&&e)return this.getDividedSummary(e);const r=this.pureContentWithoutPlaceholder(),i=(new TextEncoder).encode(r),s=new MediaType({type:"text/html",mainType:"text",subType:"html",delimiter:".",firstSuffix:{suffix:"html",fullSuffix:".html"},mimeSuffix:"",suffixesCSV:"html"}),n=this.extractSummary(i,s);let a=n.summary;return n.truncated&&(a+="..."),t&&a.length>t&&(a=a.substring(0,t).trim()+"..."),await this.renderer.render(a)}getWordCount(){return this.pureContent().trim().split(/\s+/).filter(e=>e.length>0).length}getReadingTime(e=200){const t=this.getWordCount();return Math.ceil(t/e)}isItem(e){return"Type"in e&&"firstByte"in e&&"low"in e&&"high"in e}isShortcode(e){return"name"in e&&"placeholder"in e&&"params"in e}isContentReplacement(e){return"val"in e&&"source"in e}}}}),init_parserresult=__esm({"internal/domain/markdown/vo/parserresult.ts"(){RenderingResultImpl=class{constructor(e){this.buffer=e}bytes(){return this.buffer.bytes()}toString(){return(new TextDecoder).decode(this.bytes())}},ResultImpl=class{constructor(e,t){this.parsingResult=e,this.renderingResult=t}headers(){return this.parsingResult.headers()}tableOfContents(){return this.parsingResult.tableOfContents()}bytes(){return this.renderingResult.bytes()}}}});import*as yaml from"js-yaml";import{parse as parseToml2}from"smol-toml";var ParserResult,init_markdown3=__esm({"internal/domain/markdown/entity/markdown.ts"(){init_parserresult(),init_context(),init_parseinfo(),init_item(),init_shortcode(),init_content(),init_log(),log18=getDomainLogger("markdown",{component:"MarkdownImpl"}),MarkdownImpl=class{constructor(e,t){this.renderer=e,this.highlighter=t}async render(e,t){const r=await this.parse(e),i=await this.renderToBytes(e,t,r);return new ResultImpl(r,i)}async highlight(e,t,r){return this.highlighter.highlight(e,t,r)}async highlightCodeBlock(e,t){return this.highlighter.highlightCodeBlock(e,t)}async renderCodeblock(e,t,r){return this.highlighter.renderCodeblock(e,t,r)}isDefaultCodeBlockRenderer(){return this.highlighter.isDefaultCodeBlockRenderer()}async prepareRender(e){const t=await this.parseContent(e),r=t.frontMatter?.params,i=await this.renderer.parse(t.content.pureContent());return{frontMatter:()=>r||{},toc:()=>i.tableOfContents(),render:async e=>{const i=await t.content.renderedContentAsync(e.shortcodeRenderer),s=await t.content.getRenderedSummary(i,e.maxSummaryLength),n=t.content.getWordCount(),a=t.content.getReadingTime(e.wordsPerMinute),o={renderedContent:t.content.cleanDividerPlaceholders(i),wordCount:n,readingTime:a};return r&&(o.frontMatter=r),s&&(o.summary=s),o}}}async parseAndRenderContent(e,t={}){const r=await this.parseContent(e),i=r.frontMatter?.params;let s;s=t.shortcodeRenderer&&r.shortcodes.length>0?await r.content.renderedContentAsync(t.shortcodeRenderer):r.content.pureContent();const n=await this.renderer.render(s);if(this.hasCollectedTagsSupport()){const e=this.getCollectedTags();if(e.length>0){const t=i||{},s=Array.isArray(t.tags)?t.tags:t.tags?[t.tags]:[],n=[...new Set([...s,...e])];t.tags=n,r.frontMatter&&(r.frontMatter.params=t),log18.debug(`Merged tags: YAML [${s.join(", ")}] + inline [${e.join(", ")}] = [${n.join(", ")}]`)}}const a=r.content.getDividedSummary(n),o={renderedContent:n,wordCount:r.content.getWordCount(),readingTime:r.content.getReadingTime(t.wordsPerMinute)};return i&&(o.frontMatter=i),a&&(o.summary=a),o}hasCollectedTagsSupport(){return"function"==typeof this.renderer.getCollectedTags}getCollectedTags(){return this.hasCollectedTagsSupport()?this.renderer.getCollectedTags():[]}async parseContent(e){let t;const r=new Content(e,this.renderer),i=new ShortcodeParser(e),s=[],n=function(e,t){return new SourceParseInfo(e,t)}(e,{frontMatterHandler:()=>r=>{t=this.parseFrontMatter(r,e)},summaryHandler:()=>(t,i)=>{let s=-1;i.PeekWalk(t=>(-1!==s||t.IsDone()||(s=t.Pos()),!t.IsNonWhitespace(e)||(r.setSummaryTruncated(),!1))),r.setSummaryDivider(),r.addReplacement(INTERNAL_SUMMARY_DIVIDER_PRE,t)},shortcodeHandler:()=>(e,t)=>{const n=i.parseItem(e,t);s.push(n),r.addShortcode(n)},bytesHandler:()=>e=>{r.addItem(e)}});return await n.parse(),await n.handle(),{frontMatter:t,content:r,shortcodes:s,summary:await r.getRenderedSummary(),wordCount:r.getWordCount(),readingTime:r.getReadingTime()}}parseFrontMatter(e,t){const r=e.ValStr(t);let i,s={};switch(e.Type){case 3:i="yaml",s=this.parseYAML(r);break;case 4:i="toml",s=this.parseTOML(r);break;case 5:i="json",s=this.parseJSON(r);break;case 6:i="org",s=this.parseOrg(r);break;default:i="yaml"}return{params:s,format:i}}parseYAML(e){try{const t=yaml.load(e);return t&&"object"==typeof t&&!Array.isArray(t)?t:{}}catch(e){return{}}}parseTOML(e){try{const t=parseToml2(e);return t&&"object"==typeof t&&!Array.isArray(t)?t:{}}catch(e){return{}}}parseJSON(e){try{return JSON.parse(e)}catch(e){return{}}}parseOrg(e){const t={},r=e.split("\n");for(const e of r){const r=e.trim();if(!r.startsWith("#+"))continue;const i=r.match(/^#\+([^:]+):\s*(.*)$/);if(i){const e=i[1].trim().toLowerCase(),r=i[2].trim();t[e]=this.parseValue(r)}}return t}parseValue(e){if(e.startsWith('"')&&e.endsWith('"')||e.startsWith("'")&&e.endsWith("'"))return e.slice(1,-1);if("true"===e)return!0;if("false"===e)return!1;if(/^-?\d+$/.test(e))return parseInt(e,10);if(/^-?\d*\.\d+$/.test(e))return parseFloat(e);if(e.startsWith("[")&&e.endsWith("]")){const t=e.slice(1,-1).trim();return t?t.split(",").map(e=>this.parseValue(e.trim())):[]}return e}async parse(e){const t=(new TextDecoder).decode(e.src);return await this.renderer.parse(t)}async renderToBytes(e,t,r){const i=(new TextDecoder).decode(e.src),s=await this.renderer.render(i),n=new BufWriter;return await n.writeString(s),new RenderingResultImpl(n)}}}}),init_parserresult2=__esm({"internal/domain/markdown/factory/it/parserresult.ts"(){init_tableofcontents(),ParserResult=class{_headers=[];_toc;tokens;source;idGenerator;constructor(e,t,r){this.tokens=e,this.source=t,this.idGenerator=r||new AutoIDGenerator,this._toc=this.buildTableOfContents(),this._headers=this.extractHeaders()}headers(){return[...this._headers]}tableOfContents(){return this._toc}getTokens(){return[...this.tokens]}getSource(){return this.source}buildTableOfContents(){const e=new TOCBuilder;for(const t of this.tokens)if("heading_open"===t.type){const r=parseInt(t.tag.substring(1)),i=this.findNextTextToken(t);if(i){const t=i.content,s=this.idGenerator.generateID(t);e.addHeading(t,r,s)}}return e.build()}extractHeaders(){const e=[];for(let t=0;t<this.tokens.length;t++){const r=this.tokens[t];if("heading_open"===r.type){const i=parseInt(r.tag.substring(1)),s=this.findNextTextToken(r,t);if(s){const t=new HeaderImpl(s.content,i);e.push(t)}}}return e}findNextTextToken(e,t){for(let r=void 0!==t?t+1:this.tokens.indexOf(e)+1;r<this.tokens.length;r++){const e=this.tokens[r];if("inline"===e.type)return e;if("heading_close"===e.type)break}return null}}}}),init_slugger_fallback=__esm({"internal/domain/markdown/factory/it/util/slugger-fallback.ts"(){}});function slugifyFilePath(e,t){e=function(e){return e.startsWith("/")&&(e=e.substring(1)),e.endsWith("/")&&(e=e.slice(0,-1)),e}(e);let r=(i=e,i.match(/\.[A-Za-z0-9]+$/)?.[0]);var i;const s=e.replace(new RegExp(r+"$"),"");(t||[".md",".html",void 0].includes(r))&&(r="");let n=function(e){return e.split("/").map(e=>e.replace(/\s/g,"-").replace(/&/g,"-and-").replace(/%/g,"-percent").replace(/\?/g,"").replace(/#/g,"")).join("/").replace(/\/$/,"")}(s);return function(e,t){return e===t||e.endsWith("/"+t)}(n,"_index")&&(n=n.replace(/_index$/,"index")),n+r}function splitAnchor(e){let[t,r]=e.split("#",2);return t.endsWith(".pdf")?[t,void 0===r?"":`#${r}`]:(r=void 0===r?"":"#"+r.toLowerCase().trim().replace(/\s+/g,"-").replace(/[^\w\u4e00-\u9fa5\-]+/g,"").replace(/\-+/g,"-").replace(/^-+|-+$/g,""),[t,r])}var externalLinkRegex,wikilinkRegex,tableRegex,tableWikilinkRegex,wikilinkImageEmbedRegex,init_path=__esm({"internal/domain/markdown/factory/it/util/path.ts"(){init_slugger_fallback()}}),init_wikilink=__esm({"internal/domain/markdown/factory/it/plugins/wikilink.ts"(){init_path(),externalLinkRegex=/^https?:\/\//i,wikilinkRegex=new RegExp(/!?\[\[([^\[\]\|\#\\]+)?(#+[^\[\]\|\#\\]+)?(\\?\|[^\[\]\#]*)?\]\]/g),tableRegex=new RegExp(/^\|([^\n])+\|\n(\|)( ?:?-{3,}:? ?\|)+\n(\|([^\n])+\|\n?)+/gm),tableWikilinkRegex=new RegExp(/(!?\[\[[^\]]*?\]\]|\[\^[^\]]*?\])/g)}});function wikilinkInlineRule(e,t){const r=e.pos,i=e.posMax;if(r+5>i)return!1;const s=33===e.src.charCodeAt(r),n=s?1:0;if(91!==e.src.charCodeAt(r+n)||91!==e.src.charCodeAt(r+n+1))return!1;let a=r+n+2,o=!1;for(;a<i-1;){if(93===e.src.charCodeAt(a)&&93===e.src.charCodeAt(a+1)){o=!0;break}a++}if(!o)return!1;const l=e.src.slice(r+n+2,a);if(0===l.trim().length)return!1;const c=l.indexOf("|"),h=l.indexOf("#");let u,g="",d="";if(-1!==c){const e=l.slice(0,c);u=l.slice(c+1).trim();const t=e.indexOf("#");-1!==t?(g=e.slice(0,t).trim(),d=e.slice(t).trim()):g=e.trim()}else-1!==h?(g=l.slice(0,h).trim(),d=l.slice(h).trim()):g=l.trim();if(!t){const t=s?"wikilink_embed":"wikilink_link",r=e.push(t,"",0),i={isEmbed:s,filepath:g,anchor:d,alias:u,url:g+d};r.meta=i,r.content=u||g}return e.pos=a+2,!0}function renderWikilinkLink(e,t){const r=e[t].meta,[i,s]=splitAnchor(r.url),n=slugifyFilePath(i),a=escapeHtml(r.alias??r.filepath);return`<a class="internal" data-slug="${n}" data-wikilink="${escapeHtml(r.url)}">${a}</a>`}function renderWikilinkEmbed(e,t){const r=e[t].meta,{filepath:i,anchor:s,alias:n}=r,a=slugifyFilePath(i),o=function(e){const t=e.toLowerCase().match(/\.[a-z0-9]+$/);return t?t[0]:""}(i);if([".png",".jpg",".jpeg",".gif",".bmp",".svg",".webp"].includes(o)){const{alt:e,width:t,height:r}=function(e){if(!e)return{alt:"",width:"auto",height:"auto"};const t=wikilinkImageEmbedRegex.exec(e);return t&&t.groups?{alt:t.groups.alt||"",width:t.groups.width||"auto",height:t.groups.height||"auto"}:{alt:e,width:"auto",height:"auto"}}(n);return`<img src="${a}" alt="${escapeHtml(e)}" width="${t}" height="${r}" />`}return[".mp4",".webm",".ogv",".mov",".mkv"].includes(o)?`<video src="${a}" controls></video>`:[".mp3",".webm",".wav",".m4a",".ogg",".3gp",".flac"].includes(o)?`<audio src="${a}" controls></audio>`:[".pdf"].includes(o)?`<iframe src="${a}" class="pdf"></iframe>`:`<blockquote class="transclude" data-url="${a}" data-block="${s}"><a href="${a+s}" class="transclude-inner">Transclude of ${a}</a></blockquote>`}function escapeHtml(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#039;")}function wikilinkPlugin(e,t){!1!==t?.enable&&(e.inline.ruler.before("link","wikilink",wikilinkInlineRule),e.renderer.rules.wikilink_link=renderWikilinkLink,e.renderer.rules.wikilink_embed=renderWikilinkEmbed)}var init_wikilink_plugin=__esm({"internal/domain/markdown/factory/it/plugins/wikilink-plugin.ts"(){init_path(),wikilinkImageEmbedRegex=new RegExp(/^(?<alt>(?!^\d*x?\d*$).*?)?(\|?\s*?(?<width>\d+)(x(?<height>\d+))?)?$/)}});function tagInlineRule(e,t){const r=e.pos;if(r+2>e.posMax)return!1;if(35!==e.src.charCodeAt(r))return!1;if(r>0){const t=e.src.charCodeAt(r-1);if(32!==t&&10!==t&&9!==t)return!1}const i=e.src.slice(r),s=/^#((?:[-_\p{L}\p{Emoji}\p{M}\d])+(?:\/[-_\p{L}\p{Emoji}\p{M}\d]+)*)/u.exec(i);if(!s)return!1;const n=s[0],a=s[1];if(/^[\/\d]+$/.test(a))return!1;if(!t){const t=e.push("tag","",0),r=a.split("/").map(e=>e.trim().toLowerCase().replace(/\s+/g,"-").replace(/[^\p{L}\p{Emoji}\p{M}\d\-_]/gu,"")).join("/"),i=e.md.__tagPluginState,s={rawTag:a,slugTag:r,url:`${i?.tagBaseURL||"tags/"}${r}`};t.meta=s,t.content=a,i?.onTagFound&&i.onTagFound(r)}return e.pos=r+n.length,!0}function renderTag(e,t){const r=e[t].meta,i=r.rawTag.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#039;");return`<a href="${r.url}" class="internal tag-link">${i}</a>`}function tagPlugin(e,t){const r={enable:!0,tagBaseURL:"tags/",...t};!1!==r.enable&&(e.__tagPluginState={tagBaseURL:r.tagBaseURL,onTagFound:r.onTagFound},e.inline.ruler.before("emphasis","tag",tagInlineRule),e.renderer.rules.tag=renderTag)}var calloutMapping,calloutRegex,init_tag_plugin=__esm({"internal/domain/markdown/factory/it/plugins/tag-plugin.ts"(){new RegExp(/(?<=^| )#((?:[-_\p{L}\p{Emoji}\p{M}\d])+(?:\/[-_\p{L}\p{Emoji}\p{M}\d]+)*)/gu)}});import Token from"markdown-it/lib/token.mjs";function parseCallout(e,t){if("blockquote_open"!==e[t].type)return null;let r=t+1;for(;r<e.length&&"paragraph_open"!==e[r].type;){if("blockquote_close"===e[r].type)return null;r++}if(r>=e.length)return null;const i=r+1;if("inline"!==e[i].type)return null;const s=e[i].content,n=s.match(calloutRegex);if(!n)return null;const[a,o,l="",c]=n;var h;return{type:function(e){const t=e.toLowerCase();return calloutMapping[t]??e}(o.toLowerCase()),title:s.split("\n")[0].slice(a.length).trim()||(h=o.replace(/-/g," ")).charAt(0).toUpperCase()+h.slice(1),collapse:c,metadata:l,firstLineIdx:i}}function transformCalloutTokens(e,t,r){const i=parseCallout(e,t);if(!i)return t;const{type:s,title:n,collapse:a,metadata:o,firstLineIdx:l}=i;let c=t+1,h=1;for(;c<e.length&&h>0;)"blockquote_open"===e[c].type&&h++,"blockquote_close"===e[c].type&&h--,c++;c--,e[t].type="callout_open",e[t].tag="div",e[t].attrSet("class",`callout ${s}${a?" is-collapsible":""}${"-"===a?" is-collapsed":""}`),e[t].attrSet("data-callout",s),a&&e[t].attrSet("data-callout-fold",a),o&&e[t].attrSet("data-callout-metadata",o);const u=e[l],g=u.content.split("\n"),d=g[0],p=d.match(calloutRegex);if(p){const t=p[0],r=d.slice(t.length).trim(),i=g.slice(1);if(u.content=r,i.length>0&&i.join("\n").trim()){const t=l+1,r=new Token("paragraph_open","p",1),s=new Token("inline","",0);s.content=i.join("\n").trim(),s.children=[];const n=new Token("paragraph_close","p",-1);e.splice(t+1,0,r,s,n),c+=3}}let m=t+1;for(;m<c&&"paragraph_open"!==e[m].type;)m++;let f=m+1;for(;f<c&&"paragraph_close"!==e[f].type;)f++;const y=[],w=new Token("callout_title_open","div",1);w.attrSet("class","callout-title"),y.push(w);const S=new Token("callout_icon","div",0);S.attrSet("class","callout-icon"),y.push(S);const b=new Token("callout_title_inner_open","div",1);b.attrSet("class","callout-title-inner"),y.push(b);const _=new Token("inline","",0);_.content=n,_.children=[],y.push(_);const k=new Token("callout_title_inner_close","div",-1);if(y.push(k),a){const e=new Token("callout_fold_icon","div",0);e.attrSet("class","fold-callout-icon"),y.push(e)}const v=new Token("callout_title_close","div",-1);y.push(v),e.splice(m,f-m+1),c-=f-m+1,e.splice(t+1,0,...y),c+=y.length;const P=t+1+y.length;if(P<c){const t=new Token("callout_content_open","div",1);t.attrSet("class","callout-content"),e.splice(P,0,t),c++;const r=new Token("callout_content_close","div",-1);e.splice(c,0,r),c++}return e[c].type="callout_close",e[c].tag="div",c}function calloutRule(e){let t=0,r=0;for(;t<e.tokens.length;)"blockquote_open"===e.tokens[t].type&&parseCallout(e.tokens,t)?(transformCalloutTokens(e.tokens,t,e.md),r++,t++):t++;return r>0}function calloutPlugin(e,t){!1!=={enable:!0,...t}.enable&&(e.core.ruler.after("block","callout",calloutRule),function(e){e.renderer.rules.callout_open=(e,t)=>{const r=e[t];return`<div${r.attrs?r.attrs.map(e=>{return` ${e[0]}="${t=e[1],t.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#039;")}"`;var t}).join(""):""}>`},e.renderer.rules.callout_close=()=>"</div>\n",e.renderer.rules.callout_title_open=(e,t)=>'<div class="callout-title">',e.renderer.rules.callout_title_close=()=>"</div>",e.renderer.rules.callout_title_inner_open=()=>'<div class="callout-title-inner">',e.renderer.rules.callout_title_inner_close=()=>"</div>",e.renderer.rules.callout_icon=()=>'<div class="callout-icon"></div>',e.renderer.rules.callout_fold_icon=()=>'<div class="fold-callout-icon"></div>',e.renderer.rules.callout_content_open=()=>'<div class="callout-content">',e.renderer.rules.callout_content_close=()=>"</div>"}(e))}var init_callout_plugin=__esm({"internal/domain/markdown/factory/it/plugins/callout-plugin.ts"(){calloutMapping={note:"note",abstract:"abstract",summary:"abstract",tldr:"abstract",info:"info",todo:"todo",tip:"tip",hint:"tip",important:"tip",success:"success",check:"success",done:"success",question:"question",help:"question",faq:"question",warning:"warning",caution:"warning",attention:"warning",failure:"failure",fail:"failure",missing:"failure",danger:"danger",error:"danger",bug:"bug",example:"example",quote:"quote",cite:"quote"},calloutRegex=/^\[\!([\w-]+)\|?(.+?)?\]([+-]?)/}});function escapeHtml4(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#039;")}function mathInlineRule(e,t){const r=e.pos,i=e.posMax;if(36!==e.src.charCodeAt(r))return!1;if(r>0&&92===e.src.charCodeAt(r-1))return!1;if(36===e.src.charCodeAt(r+1))return!1;let s=r+1,n=!1;for(;s<i;){const t=e.src.charCodeAt(s);if(10===t)return!1;if(36===t&&92!==e.src.charCodeAt(s-1)){n=!0;break}s++}if(!n)return!1;const a=e.src.slice(r+1,s);if(0===a.trim().length)return!1;if(!t){const t=e.push("math_inline","math",0);t.content=a,t.markup="$"}return e.pos=s+1,!0}function mathBlockRule(e,t,r,i){let s=e.bMarks[t]+e.tShift[t],n=e.eMarks[t];if(s+2>n)return!1;if(36!==e.src.charCodeAt(s)||36!==e.src.charCodeAt(s+1))return!1;if("$$"!==e.src.slice(s,n).trim())return!1;let a=t+1,o=!1;for(;a<r;){if(s=e.bMarks[a]+e.tShift[a],n=e.eMarks[a],"$$"===e.src.slice(s,n).trim()){o=!0;break}a++}if(!o)return!1;const l=[];for(let r=t+1;r<a;r++){const t=e.bMarks[r]+e.tShift[r],i=e.eMarks[r];l.push(e.src.slice(t,i))}const c=l.join("\n");if(!i){const r=e.push("math_block","math",0);r.content=c,r.markup="$$",r.block=!0,r.map=[t,a+1]}return e.line=a+1,!0}function renderMathInline(e,t){return`<span class="math math-inline" data-math="inline">${escapeHtml4(e[t].content)}</span>`}function renderMathBlock(e,t){return`<div class="math math-display" data-math="block">${escapeHtml4(e[t].content)}</div>\n`}function latexPlugin(e,t){!1!==t?.enable&&(e.inline.ruler.before("escape","math_inline",mathInlineRule),e.block.ruler.before("fence","math_block",mathBlockRule,{alt:["paragraph","reference","blockquote","list"]}),e.renderer.rules.math_inline=renderMathInline,e.renderer.rules.math_block=renderMathBlock)}var init_latex_plugin=__esm({"internal/domain/markdown/factory/it/plugins/latex-plugin.ts"(){}});function mermaidPlugin(e,t){if(!1===t?.enable)return;const r=e.renderer.rules.fence||function(e,t,r,i,s){return s.renderToken(e,t,r)};e.renderer.rules.fence=function(t,i,s,n,a){const o=t[i],l=o.info?e.utils.unescapeAll(o.info).trim():"";if("mermaid"===(l?l.split(/\s+/g)[0]:"")){const t=o.content;return`<pre class="mermaid-wrapper"><code class="language-mermaid mermaid">${e.utils.escapeHtml(t)}</code><button class="expand-button" aria-label="Expand diagram"><svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M15 3h6v6M9 21H3v-6M21 3l-7 7M3 21l7-7"/></svg></button><div id="mermaid-container"><div id="mermaid-space"><div class="mermaid-content"></div></div></div></pre>\n`}return r(t,i,s,n,a)}}var MarkdownItRenderer,init_mermaid_plugin=__esm({"internal/domain/markdown/factory/it/plugins/mermaid-plugin.ts"(){}}),init_config5=__esm({"internal/domain/markdown/factory/it/config.ts"(){}}),init_tableofcontents2=__esm({"internal/domain/markdown/factory/it/tableofcontents.ts"(){}});import MarkdownIt from"markdown-it";var init_it=__esm({"internal/domain/markdown/factory/it/index.ts"(){init_markdown5(),init_parserresult2(),init_wikilink(),init_wikilink_plugin(),init_tag_plugin(),init_callout_plugin(),init_latex_plugin(),init_mermaid_plugin(),init_config5(),init_parserresult2(),init_tableofcontents2(),init_wikilink_plugin(),init_tag_plugin(),init_callout_plugin(),init_latex_plugin(),init_mermaid_plugin(),init_wikilink(),init_path(),init_slugger_fallback(),MarkdownItRenderer=class{md;config;idGenerator;collectedTags=new Set;constructor(e,t){this.config=e,this.idGenerator=new AutoIDGenerator,t?(this.md=t,this.config.extensions.wikilink?.enable&&this.md.use(wikilinkPlugin,{enable:!0}),this.config.extensions.parseTags&&this.md.use(tagPlugin,{enable:!0,tagBaseURL:"tags/",onTagFound:e=>this.collectedTags.add(e)}),this.config.extensions.callouts&&this.md.use(calloutPlugin,{enable:!0}),this.config.extensions.latex?.enable&&this.md.use(latexPlugin,{enable:!0}),this.config.extensions.mermaid?.enable&&this.md.use(mermaidPlugin,{enable:!0})):this.md=this.createMarkdownItInstance(),this.setupRendererRules()}setupRendererRules(){const e=this.idGenerator;this.md.renderer.rules.heading_open=function(t,r){const i=t[r+1].content,s=e.generateID(i);return t[r].attrPush(["id",s]),`<${t[r].tag} id="${s}">`}}async render(e){return this.idGenerator.reset(),this.collectedTags.clear(),this.config.extensions.wikilink?.enable&&(e=e.replace(tableRegex,e=>e.replace(tableWikilinkRegex,(e,t)=>{let r=t??"";return r=r.replace("#","\\#"),r=r.replace(/((^|[^\\])(\\\\)*)\|/g,"$1\\|"),r})).replace(wikilinkRegex,(e,...t)=>{const[r,i,s]=t,[n,a]=splitAnchor(`${r??""}${i??""}`),o=Boolean(i?.startsWith("#^"))?"^":"",l=a?`#${o}${a.trim().replace(/^#+/,"")}`:"",c=s??i?.replace("#","|")??"",h=e.startsWith("!")?"!":"";return r?.match(externalLinkRegex)?`${h}[${c.replace(/^\|/,"")}](${r})`:`${h}[[${n}${l}${c}]]`})),this.md.render(e)}getCollectedTags(){return Array.from(this.collectedTags)}async parse(e){this.idGenerator.reset();const t=await this._parse(e);return new ParserResult(t,(new TextEncoder).encode(e),this.idGenerator)}async _parse(e){return this.md.parse(e,{})}getMarkdownIt(){return this.md}addPlugin(e,t){this.md.use(e,t)}createMarkdownItInstance(){const e=new MarkdownIt({html:this.config.renderer.unsafe,breaks:!1,linkify:this.config.extensions.linkify,typographer:!this.config.extensions.typographer.disable});return this.config.extensions.typographer.disable||(e.options.quotes=[this.config.extensions.typographer.leftDoubleQuote,this.config.extensions.typographer.rightDoubleQuote,this.config.extensions.typographer.leftSingleQuote,this.config.extensions.typographer.rightSingleQuote]),this.configureBasicPlugins(e),this.config.extensions.wikilink?.enable&&e.use(wikilinkPlugin,{enable:!0}),this.config.extensions.parseTags&&e.use(tagPlugin,{enable:!0,tagBaseURL:"tags/",onTagFound:e=>this.collectedTags.add(e)}),this.config.extensions.callouts&&e.use(calloutPlugin,{enable:!0}),this.config.extensions.latex?.enable&&e.use(latexPlugin,{enable:!0}),this.config.extensions.mermaid?.enable&&e.use(mermaidPlugin,{enable:!0}),e}configureBasicPlugins(e){this.config.extensions.table&&e.enable(["table"]),this.config.extensions.strikethrough&&e.enable(["strikethrough"])}}}});var PathType,PATH_CONSTANTS,init_markdown4=__esm({"internal/domain/markdown/factory/markdown.ts"(){init_markdown3(),init_highlight(),init_it()}}),init_markdown5=__esm({"internal/domain/markdown/index.ts"(){init_type5(),init_config4(),init_context(),init_tableofcontents(),init_highlight(),init_pageparser2(),init_parseinfo(),init_shortcode(),init_content(),init_markdown3(),init_markdown4()}});import{sep as PATH_SEP}from"path";var PathComponentsImpl,PathPositionsImpl,LowHighImpl,PathComponentsFactory,Path,PathUtils,PathProcessorImpl,PathParsingNormalizer,BasicPathNormalizer,DefaultFileExtensionChecker,PathParserUtils,PathFactoryImpl,DefaultPathFactory,SimplePathPool,PathBuilder,PathFactoryUtils,PathDomain,log19,Translator,init_type7=__esm({"internal/domain/paths/type.ts"(){PathType=(e=>(e[e.File=0]="File",e[e.ContentResource=1]="ContentResource",e[e.ContentSingle=2]="ContentSingle",e[e.Leaf=3]="Leaf",e[e.Branch=4]="Branch",e))(PathType||{}),PATH_CONSTANTS={CONTENT_EXTENSIONS:[".md",".markdown",".mdown",".mkd",".mkdn",".html",".htm",".xml"],HTML_EXTENSIONS:[".html",".htm"],INDEX_NAMES:["index","_index"],PATH_SEPARATOR:"/",EXTENSION_SEPARATOR:".",LANGUAGE_SEPARATOR:".",SYSTEM_PATH_SEPARATOR:PATH_SEP,COMPONENT_FOLDER_CONTENT:"content",COMPONENT_FOLDER_STATIC:"static",COMPONENT_FOLDER_LAYOUTS:"layouts",COMPONENT_FOLDER_ARCHETYPES:"archetypes",COMPONENT_FOLDER_DATA:"data",COMPONENT_FOLDER_ASSETS:"assets",COMPONENT_FOLDER_I18N:"i18n",normalizePath:e=>{let t=e.replace(/\\/g,"/");return t.startsWith("//")&&(t=t.substring(1)),t}}}}),init_pathcomponents=__esm({"internal/domain/paths/vo/pathcomponents.ts"(){init_type7(),PathComponentsImpl=class e{constructor(e,t,r,i,s,n=!1,a){this.original=e,this.normalized=t,this.positions=r,this.identifiers=i,this.bundleType=s,this.disabled=n,this.component=a}withBundleType(t){return new e(this.original,this.normalized,this.positions,this.identifiers,t,this.disabled)}withDisabled(t){return new e(this.original,this.normalized,this.positions,this.identifiers,this.bundleType,t)}hasIdentifiers(){return this.identifiers.length>0}firstIdentifier(){return this.identifiers.length>0?this.identifiers[0]:null}lastIdentifier(){return this.identifiers.length>0?this.identifiers[this.identifiers.length-1]:null}getIdentifier(e){return e>=0&&e<this.identifiers.length?this.identifiers[e]:null}isContentComponent(e){return"content"===e||"archetypes"===e}clone(){return new e(this.original,this.normalized,{...this.positions},[...this.identifiers],this.bundleType,this.disabled,this.component)}toString(){return`PathComponents{original="${this.original}", normalized="${this.normalized}", bundleType=${PathType[this.bundleType]}, identifiers=${this.identifiers.length}}`}},PathPositionsImpl=class e{constructor(e=-1,t=-1,r=-1,i=-1){this.containerLow=e,this.containerHigh=t,this.sectionHigh=r,this.identifierLanguage=i}reset(){this.containerLow=-1,this.containerHigh=-1,this.sectionHigh=-1,this.identifierLanguage=-1}hasContainer(){return-1!==this.containerLow&&-1!==this.containerHigh}hasSection(){return this.sectionHigh>0}hasLanguageIdentifier(){return-1!==this.identifierLanguage}clone(){return new e(this.containerLow,this.containerHigh,this.sectionHigh,this.identifierLanguage)}},LowHighImpl=class{constructor(e,t){if(this.low=e,this.high=t,e>t)throw new Error(`Invalid range: low (${e}) must be <= high (${t})`)}length(){return this.high-this.low}isEmpty(){return this.low===this.high}contains(e){return e>=this.low&&e<this.high}substring(e){return e.substring(this.low,this.high)}toString(){return`[${this.low}, ${this.high})`}},PathComponentsFactory=class{static createEmpty(e="",t=0){return new PathComponentsImpl(e,e,new PathPositionsImpl,[],t,!1)}static create(e,t,r=0){return new PathComponentsImpl(e,t||e,new PathPositionsImpl,[],r,!1)}static createFull(e,t,r,i,s,n=!1){return new PathComponentsImpl(e,t,r,i,s,n)}}}}),init_path2=__esm({"internal/domain/paths/entity/path.ts"(){init_type7(),init_pathcomponents(),Path=class e{constructor(e){this.components=e}_unnormalized;shouldTrimLeadingSlash=!1;component(){if(this.components.component)return this.components.component;const e=this.components.normalized.split("/").filter(e=>e.length>0);return 0===e.length?"content":{static:"static",layouts:"layouts",themes:"themes",archetypes:"archetypes",data:"data",i18n:"i18n",assets:"assets"}[e[0]]||"content"}path(){return this.norm(this.components.normalized)}name(){return this.components.positions.containerHigh>0?this.components.normalized.substring(this.components.positions.containerHigh):this.components.normalized}originalNameNoExt(){const e=this.components.firstIdentifier();return e?this.components.original.substring(this.components.positions.containerHigh,e.low-1):this.components.original.substring(this.components.positions.containerHigh)}nameNoExt(){const e=this.components.firstIdentifier();return e?this.components.normalized.substring(this.components.positions.containerHigh,e.low-1):this.components.normalized.substring(this.components.positions.containerHigh)}nameNoLang(){return this.name()}dir(){let e="";return this.components.positions.containerHigh>0&&(e=this.components.normalized.substring(0,this.components.positions.containerHigh-1)),""===e&&(e="/"),this.norm(e)}ext(){if(0===this.components.identifiers.length)return"";const e=this.components.identifiers[this.components.identifiers.length-1],t=this.components.normalized.substring(e.low,e.high);return t?"."+t:""}lang(){return""}section(){if(this.components.positions.sectionHigh<=0)return"";const e=this.components.normalized.substring(1,this.components.positions.sectionHigh);return"_index.md"===e||"index.md"===e||e.endsWith("/_index.md")||e.endsWith("/index.md")?"":this.norm(e)}sections(){const e=this.dir();if("/"===e||""===e)return[];const t=[],r=(e.startsWith("/")?e.substring(1):e).split("/").filter(e=>e.length>0);let i="";for(const e of r)""===i?i=e:i+="/"+e,t.push(this.norm(i));return t}container(){return-1===this.components.positions.containerLow?"":this.norm(this.components.normalized.substring(this.components.positions.containerLow,this.components.positions.containerHigh-1))}containerDir(){return this.isLeafBundle()||this.isBranchBundle(),this.dir()}base(){return this.isBranchBundle()&&"/_index.md"===this.components.normalized?"/":this.isLeafBundle()?this.baseInternal(!1,!0):this.isContent()&&!this.isBundle()?this.pathNoIdentifier():this.isContent()?this.isBundle()?this.baseInternal(!1,!0):this.baseInternal(!this.isContentPage(),this.isBundle()):this.path()}baseNoLeadingSlash(){return this.base().substring(1)}baseNameNoIdentifier(){return this.isBundle()?this.container():this.nameNoIdentifier()}nameNoIdentifier(){if(0===this.components.identifiers.length)return this.name();const e=this.components.identifiers[0],t=this.components.positions.containerHigh;return this.components.normalized.substring(t,e.low-1)}pathNoLang(){return this.baseInternal(!0,!1)}pathNoIdentifier(){if(0===this.components.identifiers.length)return this.path();const e=this.components.identifiers[0],t=this.components.normalized.substring(0,e.low-1);return this.norm(t)}pathRel(e){let t=e.base();return t.endsWith("/")||(t+="/"),this.path().replace(new RegExp("^"+this.escapeRegExp(t)),"")}baseRel(e){let t=e.base();return"/"===t&&(t=""),this.base().substring(t.length+1)}trimLeadingSlash(){const t=this.components.clone(),r=new e(t);return r.setShouldTrimLeadingSlash(!0),r}identifier(e){const t=this.components.identifiers.length;if(0===t||e<0||e>=t)return"";let r;r=1===t?0:0===e?t-1:t-1-e;const i=this.identifierAsString(r);return i?"."+i:""}identifiers(){const e=[],t=this.components.identifiers.length;for(let r=0;r<t;r++){const t=this.identifier(r);t&&e.push(t)}return e}bundleType(){return this.components.bundleType}isContent(){return this.bundleType()>=1}isBundle(){return this.bundleType()>3}isBranchBundle(){return 4===this.bundleType()}isLeafBundle(){return 3===this.bundleType()}isHTML(){const e=this.ext().toLowerCase();return PATH_CONSTANTS.HTML_EXTENSIONS.some(t=>t===e)}disabled(){return this.components.disabled}forBundleType(t){const r=this.components.withBundleType(t);return new e(r)}unnormalized(){if(!this._unnormalized)if(this.components.original===this.components.normalized)this._unnormalized=this;else{const t=new PathComponentsImpl(this.components.original,this.components.original,this.components.positions,this.components.identifiers,this.components.bundleType,this.components.disabled);this._unnormalized=new e(t)}return this._unnormalized}setShouldTrimLeadingSlash(e){this.shouldTrimLeadingSlash=e}norm(e){return this.shouldTrimLeadingSlash&&e.startsWith("/")?e.substring(1):e}isContentPage(){return this.bundleType()>=2}baseInternal(e,t){if(0===this.components.identifiers.length)return this.norm(this.components.normalized);if(e&&1===this.components.identifiers.length)return this.norm(this.components.normalized);let r=this.components.identifiers[this.components.identifiers.length-1].low-1;if(t&&(r=this.components.positions.containerHigh-1),0===r&&r++,!e)return this.norm(this.components.normalized.substring(0,r));const i=this.components.identifiers[0];return this.norm(this.components.normalized.substring(0,r)+this.components.normalized.substring(i.low-1,i.high))}identifierAsString(e){const t=this.identifierIndex(e);if(-1===t)return"";const r=this.components.identifiers[t];return this.components.normalized.substring(r.low,r.high)}identifierIndex(e){return e<0||e>=this.components.identifiers.length?-1:e}escapeRegExp(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}toString(){return`Path{path="${this.path()}", component="${this.component()}", bundleType=${PathType[this.bundleType()]}}`}equals(e){return this.path()===e.path()&&this.component()===e.component()&&this.bundleType()===e.bundleType()}hashCode(){return`${this.component()}:${this.path()}:${this.bundleType()}`}},PathUtils=class{static fromString(e,t){const r=new PathComponentsImpl(t,t,{containerLow:-1,containerHigh:-1,sectionHigh:-1,identifierLanguage:-1},[],0,!1);return new Path(r)}static hasExtension(e,t){const r=e.ext(),i=t.startsWith(".")?t:"."+t;return r.toLowerCase()===i.toLowerCase()}static isUnder(e,t){const r=e.path();let i;i=t.isBranchBundle()?t.dir():t.path();const s="/"===i?"/":i+"/";return r!==i&&r.startsWith(s)}static relativeTo(e,t){return t.pathRel(e)}static compare(e,t){const r=e.path().localeCompare(t.path());if(0!==r)return r;const i=e.component().localeCompare(t.component());return 0!==i?i:e.bundleType()-t.bundleType()}}}}),init_pathparser=__esm({"internal/domain/paths/vo/pathparser.ts"(){init_type7(),init_pathcomponents(),init_path2(),PathProcessorImpl=class{normalizer;extChecker;constructor(e,t){this.normalizer=e||new PathParsingNormalizer,this.extChecker=t||new DefaultFileExtensionChecker}parse(e,t){let r=t;r&&""!==r||(r="/");const i=this.normalizer.normalize(r),s=this.createPathComponents(e,i,t);return new Path(s)}parseIdentity(e,t){const r=this.parse(e,t);return{identifierBase:()=>r.base()}}parseBaseAndBaseNameNoIdentifier(e,t){const r=this.parse(e,t);return[r.base(),r.baseNameNoIdentifier()]}createPathComponents(e,t,r){let i=e,s=t;if(t.startsWith("/")){const r=t.split("/").filter(e=>e.length>0);if(r.length>0){const t=r[0];["static","layouts","themes","archetypes","data","i18n","assets"].includes(t)&&"content"===e&&(i=t),["images","assets","static","css","js","fonts"].includes(t)&&"content"===e&&(i="static")}}const n=s.lastIndexOf("/"),a=n>=0?s.substring(n+1):s;n>=0&&s.substring(0,n);let o=this.detectBundleType(a,i);const l=this.calculatePathPositions(s),c=this.extractIdentifiers(s,a);return new PathComponentsImpl(r,s,l,c,o,!1,i)}detectBundleType(e,t){if("content"!==t&&"archetypes"!==t)return 0;let r=e.split(".")[0];return"index"===r&&this.isContentFile(e)?3:"_index"===r&&this.isContentFile(e)?4:this.isContentFile(e)?2:0}isContentFile(e){const t=this.getFileExtension(e);return["md","html","markdown","mdown","mkd","mkdn","htm"].includes(t.toLowerCase())}getFileExtension(e){const t=e.lastIndexOf(".");return t>0&&t<e.length-1?e.substring(t+1):""}calculatePathPositions(e){let t=-1,r=-1,i=-1;for(let s=e.length-1;s>=0;s--)"/"===e[s]&&(-1===i?i=s+1:-1===r&&(r=s+1),s>0&&(t=s));return new PathPositionsImpl(r,i,t,-1)}extractIdentifiers(e,t){const r=[],i=e.substring(0,e.length-t.length).length,s=t.split(".");if(s.length<=1)return r;let n=i;for(let e=0;e<s.length-1;e++)n+=s[e].length+1;const a=n,o=a+s[s.length-1].length;return r.push(new LowHighImpl(a,o)),r}},PathParsingNormalizer=class{constructor(e=!0,t=!0){this.toLowerCase=e,this.replaceSpaces=t}normalize(e){let t=e;return t=t.replace(/\\/g,"/"),this.toLowerCase&&(t=t.toLowerCase()),this.replaceSpaces&&(t=t.replace(/\s/g,"-")),t}},BasicPathNormalizer=class{constructor(e=!0,t=!0){this.toLowerCase=e,this.replaceSpaces=t}normalize(e){let t=e;return t=t.replace(/\\/g,"/"),this.toLowerCase&&(t=t.toLowerCase()),this.replaceSpaces&&(t=t.replace(/\s+/g,"-")),t}},DefaultFileExtensionChecker=class{isContentExt(e){return PATH_CONSTANTS.CONTENT_EXTENSIONS.includes(e.toLowerCase())}isHTML(e){return PATH_CONSTANTS.HTML_EXTENSIONS.includes(e.toLowerCase())}hasExt(e){for(let t=e.length-1;t>=0;t--){if("."===e[t])return!0;if("/"===e[t])return!1}return!1}},PathParserUtils=class e{static parseBasic(e){const t=e.lastIndexOf("/"),r=t>=0?e.substring(0,t):"",i=t>=0?e.substring(t+1):e,s=i.lastIndexOf("."),n=s>=0?i.substring(s):"",a=s>=0?i.substring(0,s):i;return{dir:r,name:i,ext:n,nameWithoutExt:a}}static join(...e){return e.filter(e=>e.length>0).map(e=>e.replace(/^\/+|\/+$/g,"")).join("/").replace(/\/+/g,"/")}static normalizeBasic(e){return(new BasicPathNormalizer).normalize(e)}static isBundle(t){const r=e.parseBasic(t);return PATH_CONSTANTS.INDEX_NAMES.includes(r.nameWithoutExt)}static extractSection(e){const t=e.startsWith("/")?e.substring(1):e,r=t.indexOf("/");return r>=0?t.substring(0,r):t}static removeExtension(e){const t=e.lastIndexOf(".");return t>e.lastIndexOf("/")?e.substring(0,t):e}static hasExtension(e){return(new DefaultFileExtensionChecker).hasExt(e)}}}}),init_pathfactory=__esm({"internal/domain/paths/factory/pathfactory.ts"(){init_pathparser(),init_pathcomponents(),init_path2(),PathFactoryImpl=class{processor;pool;constructor(e,t){const r=e?.normalizer?{normalize:e.normalizer}:new BasicPathNormalizer(!1!==e?.normalize,!1!==e?.replaceSpaces),i=new DefaultFileExtensionChecker;this.processor=new PathProcessorImpl(r,i),t&&(this.pool=t)}create(e,t,r){return this.pool&&this.pool.get(),this.processor.parse(e,t)}createFromComponents(e){return new Path(e)}createMany(e,t,r){return t.map(t=>this.create(e,t,r))}createWithConfig(e,t,r){const i={};return void 0!==r?.toLowerCase&&(i.normalize=r.toLowerCase),void 0!==r?.replaceSpaces&&(i.replaceSpaces=r.replaceSpaces),void 0!==r?.customNormalizer&&(i.normalizer=r.customNormalizer),this.create(e,t,i)}},DefaultPathFactory=class extends PathFactoryImpl{constructor(){super({normalize:!0,replaceSpaces:!0})}},SimplePathPool=class{pool=[];maxSize;constructor(e=100){this.maxSize=e}get(){if(this.pool.length>0)return this.pool.pop();const e=PathComponentsFactory.createEmpty();return new Path(e)}put(e){this.pool.length<this.maxSize&&this.pool.push(e)}clear(){this.pool=[]}size(){return this.pool.length}},PathBuilder=class{component="";path="";config={};factory;constructor(e){this.factory=e||new DefaultPathFactory}withComponent(e){return this.component=e,this}withPath(e){return this.path=e,this}withNormalization(e){return this.config.normalize=e,this}withSpaceReplacement(e){return this.config.replaceSpaces=e,this}withNormalizer(e){return this.config.normalizer=e,this}build(){if(!this.component||!this.path)throw new Error("Component and path must be set");return this.factory.create(this.component,this.path,this.config)}reset(){return this.component="",this.path="",this.config={},this}},PathFactoryUtils=class e{static defaultFactory=new DefaultPathFactory;static createContentPath(t){return e.defaultFactory.create("content",t)}static createStaticPath(t){return e.defaultFactory.create("static",t)}static createLayoutPath(t){return e.defaultFactory.create("layouts",t)}static createArchetypePath(t){return e.defaultFactory.create("archetypes",t)}static createDataPath(t){return e.defaultFactory.create("data",t)}static createThemePath(t){return e.defaultFactory.create("themes",t)}static createFromConfig(e){const t={};void 0!==e.normalize&&(t.normalize=e.normalize),void 0!==e.replaceSpaces&&(t.replaceSpaces=e.replaceSpaces);const r=new PathFactoryImpl(t);return e.paths.map(t=>r.create(e.component,t))}static builder(){return new PathBuilder}static createWithPool(e,t,r){return new PathFactoryImpl(void 0,r).create(e,t)}}}}),init_paths=__esm({"internal/domain/paths/index.ts"(){init_type7(),init_pathcomponents(),init_pathparser(),init_path2(),init_pathfactory(),init_type7(),init_type7(),init_type7(),init_pathfactory(),init_pathparser(),init_path2(),init_pathparser(),init_pathfactory(),init_pathfactory(),init_pathparser(),PathDomain={createContentPath:PathFactoryUtils.createContentPath,createStaticPath:PathFactoryUtils.createStaticPath,createLayoutPath:PathFactoryUtils.createLayoutPath,createArchetypePath:PathFactoryUtils.createArchetypePath,createDataPath:PathFactoryUtils.createDataPath,createThemePath:PathFactoryUtils.createThemePath,builder:PathFactoryUtils.builder,parseBasic:PathParserUtils.parseBasic,join:PathParserUtils.join,normalizeBasic:PathParserUtils.normalizeBasic,isBundle:PathParserUtils.isBundle,extractSection:PathParserUtils.extractSection,removeExtension:PathParserUtils.removeExtension,checkExtension:PathParserUtils.hasExtension,hasSpecificExtension:PathUtils.hasExtension,isUnder:PathUtils.isUnder,relativeTo:PathUtils.relativeTo,compare:PathUtils.compare,createProcessor:()=>new PathProcessorImpl,createFactory:()=>new DefaultPathFactory,createPool:e=>new SimplePathPool(e),createNormalizer:e=>new BasicPathNormalizer(e?.toLowerCase,e?.replaceSpaces)}}});import*as yaml2 from"js-yaml";var log20,init_translator=__esm({"internal/domain/content/entity/translator.ts"(){init_log(),init_paths(),log19=getDomainLogger("content",{component:"translator"}),Translator=class{contentLanguage;translateFuncs=new Map;constructor(e){this.contentLanguage=e}translate(e,t){const r=e.toLowerCase(),i=this.translateFuncs.get(r);if(i){const e=i(t);if(e)return e}log19.info(`Translation func for language ${e} not found, use default.`);const s=this.translateFuncs.get(this.contentLanguage.toLowerCase());if(s){const e=s(t);if(e)return e}return log19.info("i18n not initialized; if you need string translations, check that you have a bundle in /i18n that matches the site language or the default language."),`[i18n] ${t}`}async setupTranslateFuncs(e){try{await e.walkI18n("",{walkFn:async(e,t)=>{if(e.endsWith(".yaml")||e.endsWith(".yml"))try{const r=(PATH_CONSTANTS.normalizePath(e).split("/").pop()||"").replace(/\.(yaml|yml)$/,"").toLowerCase(),i=await this.readI18nFile(t),s=this.parseI18nContent(i),n=new Map;s.forEach(e=>{n.set(e.id,e.translation)});const a=e=>n.get(e)||(log19.warn(`i18n|MISSING_TRANSLATION|${r}|${e}`),"");this.translateFuncs.set(r,a),log19.info(`✅ Loaded i18n translations for language: ${r} (${s.length} items)`)}catch(t){log19.error(`❌ Failed to load i18n file ${e}:`,t)}}},{}),log19.info(`🌍 Translation setup complete. Loaded ${this.translateFuncs.size} languages: [${Array.from(this.translateFuncs.keys()).join(", ")}]`)}catch(e){throw e}}async readI18nFile(e){let t=null;try{t=await e.open();const r=await t.stat(),i=new Uint8Array(r.size()),s=await t.read(i),n=new TextDecoder("utf-8").decode(s.buffer);return 65279===n.charCodeAt(0)?n.slice(1):n}catch(e){throw log19.error("❌ Failed to read i18n file:",e),e}finally{if(t)try{await t.close()}catch(e){log19.warn(`Failed to close i18n file: ${e}`)}}}parseI18nContent(e){try{const t=yaml2.load(e);return Array.isArray(t)?t.filter(e=>e&&"object"==typeof e&&e.id&&e.translation).map(e=>({id:String(e.id),translation:String(e.translation)})):(log19.warn("i18n YAML content is not an array"),[])}catch(e){return log19.error("❌ Failed to parse i18n YAML content:",e),[]}}getAvailableLanguages(){return Array.from(this.translateFuncs.keys())}hasLanguage(e){return this.translateFuncs.has(e.toLowerCase())}}}});async function createContent(e){const t=new MDConverter(function(e,t){const r=new DefaultHighlighter({style:"github",lineNos:!1,lineNoStart:1,anchorLineNos:!1,lineAnchors:"",lineNumbersInTable:!0,noClasses:!0,codeFences:!0,guessSyntax:!1,tabWidth:4});return new MarkdownImpl(t||!e?new MarkdownItRenderer({extensions:{typographer:{disable:!1,leftSingleQuote:"&lsquo;",rightSingleQuote:"&rsquo;",leftDoubleQuote:"&ldquo;",rightDoubleQuote:"&rdquo;",enDash:"&ndash;",emDash:"&mdash;",ellipsis:"&hellip;",leftAngleQuote:"&laquo;",rightAngleQuote:"&raquo;",apostrophe:"&rsquo;"},footnote:!0,definitionList:!0,table:!0,strikethrough:!0,linkify:!0,linkifyProtocol:"https",taskList:!0,cjk:{enable:!1,eastAsianLineBreaks:!1,eastAsianLineBreaksStyle:"simple",escapedSpace:!1},passthrough:{enable:!1,delimiters:{inline:[],block:[]}},highlight:{style:"github",lineNos:!1,lineNoStart:1,anchorLineNos:!1,lineAnchors:"",lineNumbersInTable:!0,noClasses:!0,codeFences:!0,guessSyntax:!1,tabWidth:4},wikilink:{enable:!0,disableBrokenWikilinks:!1,markdownLinkResolution:"shortest",prettyLinks:!0},parseTags:!0,callouts:!0,latex:{enable:!0},mermaid:{enable:!0}},renderer:{unsafe:!0},parser:{autoHeadingID:!0,autoHeadingIDType:"github",wrapStandAloneImageWithinParagraph:!0,attribute:{title:!0,block:!1}},duplicateResourceFiles:!1,renderHooks:{image:{enableDefault:!0},link:{enableDefault:!0}}},void 0):e,r)}(e.markdown(),e.useInternalRenderer())),r=await async function(e){const t=new Translator(e.defaultLanguage());try{await t.setupTranslateFuncs(e)}catch(e){log20.warn("Failed to setup translator, continuing without i18n support:",e)}return t}(e),i=new PageBuilder(e,e,e,null,null,new Taxonomy2(e.views(),e),new Term(e),new Section(e),new Standalone(e),t,null),s=new PageMap(i);i.pageMapper=s,s.setupReverseIndex();const n=new Content2(e,t,s,r);return i.contentHub=n,n}var kindMapMain,init_hub=__esm({"internal/domain/content/factory/hub.ts"(){init_content3(),init_markdown5(),init_translator(),init_log(),log20=getDomainLogger("content",{component:"content"})}});function getKindMain(e){return kindMapMain[e.toLowerCase()]||""}var Identity,contentFileExtensionsSet,FileInfo7,init_kind=__esm({"internal/domain/content/vo/kind.ts"(){init_type4(),kindMapMain={[PageKind.PAGE]:PageKind.PAGE,[PageKind.HOME]:PageKind.HOME,[PageKind.SECTION]:PageKind.SECTION,[PageKind.TAXONOMY]:PageKind.TAXONOMY,[PageKind.TERM]:PageKind.TERM,[PageKind.STATUS_404]:PageKind.STATUS_404,[PageKind.SITEMAP]:PageKind.SITEMAP,taxonomyterm:PageKind.TAXONOMY}}}),init_identity=__esm({"internal/domain/content/vo/identity.ts"(){init_log(),getDomainLogger("content",{component:"identity"}),Identity=class{id;lang;langIdx;stale=!0;constructor(e,t="",r=0){this.id=e,this.lang=t,this.langIdx=r}ID(){return this.id}identifierBase(){return`${this.id}-${this.lang}`}pageLanguage(){return this.lang}pageLanguageIndex(){return this.langIdx}pageIdentity(){return this}markStale(){this.stale||(this.stale=!0)}isStale(){return this.stale}clearStale(){this.stale&&(this.stale=!1)}}}});import*as crypto from"crypto";import*as path16 from"path";function newFileInfo2(e){return FileInfo7.newFileInfo(e)}var PageByWrapper,lessPageTitle,language,weight,collatorStringCompare,PageSorterImpl,init_fileinfo2=__esm({"internal/domain/content/vo/fileinfo.ts"(){init_paths(),init_log(),getDomainLogger("content",{component:"FileInfo"}),contentFileExtensionsSet=new Set([".md"]),FileInfo7=class e{fileMetaInfo;pathInfo;bundleType;uniqueIDCache;lazyInitDone=!1;constructor(e,t){this.fileMetaInfo=e;const r=PathDomain.createProcessor();this.pathInfo=r.parse(PATH_CONSTANTS.COMPONENT_FOLDER_CONTENT,t),this.bundleType=0,this.determineBundleType()}static newFileInfo(t){const r=PATH_CONSTANTS.normalizePath(t.relativeFilename());return new e(t,r)}pageFile(){return this}shiftToResource(){this.isContent()&&(this.bundleType=1)}relPath(){const e=this.pathInfo.dir(),t=e.startsWith("/")?e.substring(1):e;return path16.join(t,this.pathInfo.name())}section(){return this.pathInfo.section()}isZero(){return null==this.fileMetaInfo}filename(){return this.fileMetaInfo.fileName()}dir(){return this.pathToDir(this.pathInfo.dir())}ext(){return this.pathInfo.ext()}logicalName(){return this.pathInfo.name()}originalBaseFileName(){return this.pathInfo.originalNameNoExt()}baseFileName(){return this.pathInfo.nameNoExt()}translationBaseName(){return this.pathInfo.nameNoIdentifier()}contentBaseName(){return this.pathInfo.baseNameNoIdentifier()}baseNameNoIdentifier(){return this.pathInfo.baseNameNoIdentifier()}root(){return this.pathInfo.dir()||"/"}uniqueID(){return this.init(),this.uniqueIDCache}fileInfo(){return this.fileMetaInfo}type(){const e=this.section();return""!==e?e:"page"}async open(){return await this.fileMetaInfo.open()}paths(){return this.pathInfo}path(){return this.pathInfo.path()}toString(){return this.baseFileName()}getBundleType(){return this.bundleType}isBundle(){return this.bundleType>=3}isLeafBundle(){return 3===this.bundleType}isBranchBundle(){return 4===this.bundleType}isContentResource(){return 1===this.bundleType}isContent(){return this.bundleType>=1}init(){if(!this.lazyInitDone){this.lazyInitDone=!0;const e=this.relPath().replace(/\\/g,"/");this.uniqueIDCache=crypto.createHash("md5").update(e).digest("hex")}}pathToDir(e){return""===e?e:path16.normalize(e.substring(1)+"/")}determineBundleType(){var e;if(e=this.pathInfo.ext(),contentFileExtensionsSet.has(e))switch(this.pathInfo.nameNoIdentifier()){case"index":this.bundleType=3;break;case"_index":this.bundleType=4;break;default:this.bundleType=2}}}}});function sortByTitle(e){pageBy(lessPageTitle).sort(e)}function pageBy(e){return new PageByWrapper(e)}var Cast,Strings,Types,FrontMatterParserImpl,init_sort=__esm({"internal/domain/content/vo/sort.ts"(){PageByWrapper=class{constructor(e){this.by=e}sort(e){!function(e,t){const r=Array.from({length:t.len()},(e,t)=>t);r.sort((e,r)=>t.less(e,r)?-1:t.less(r,e)?1:e-r);const i=[...e];for(let t=0;t<r.length;t++)e[t]=i[r[t]]}(e,new PageSorterImpl(e,this.by))}},lessPageTitle=(e,t)=>collatorStringCompare(e=>e.title(),e,t)<0,language=(e,t)=>collatorStringCompare(e=>e.pageIdentity().pageLanguage(),e,t)<0,weight=(e,t)=>e.pageWeight()<t.pageWeight(),collatorStringCompare=(e,t,r)=>{const i=e(t),s=e(r);return i<s?-1:i>s?1:0},PageSorterImpl=class{constructor(e,t){this.pages=e,this.by=t}len(){return this.pages.length}swap(e,t){[this.pages[e],this.pages[t]]=[this.pages[t],this.pages[e]]}less(e,t){return this.by(this.pages[e],this.pages[t])}}}}),init_cast=__esm({"pkg/cast/cast.ts"(){Cast=class{static toString(e){return null==e?"":"string"==typeof e?e:"number"==typeof e||"boolean"==typeof e?e.toString():String(e)}static toInt(e){if(null==e)return 0;if("number"==typeof e)return Math.floor(e);if("string"==typeof e){const t=parseInt(e,10);return isNaN(t)?0:t}return 0}static toTime(e){if(null==e)return new Date;if(e instanceof Date)return e;if("string"==typeof e){const t=new Date(e);return isNaN(t.getTime())?new Date:t}return"number"==typeof e?new Date(e):new Date}}}}),init_cast2=__esm({"pkg/cast/index.ts"(){init_cast()}}),init_string=__esm({"pkg/string/string.ts"(){Strings=class{static sliceToLower(e){return e.map(e=>e.toLowerCase())}}}}),init_string2=__esm({"pkg/string/index.ts"(){init_string()}}),init_types2=__esm({"pkg/types/types.ts"(){init_cast2(),Types=class{static toStringSlicePreserveString(e){return null==e?null:Array.isArray(e)?e.map(e=>Cast.toString(e)):"string"==typeof e?[e]:[Cast.toString(e)]}}}}),init_types3=__esm({"pkg/types/index.ts"(){init_types2()}});import path17 from"path";function getParamToLower(e,t){return getParam(e,t,!0)}function getParam(e,t,r){const i=e[t.toLowerCase()];if(null==i)return null;switch(typeof i){case"boolean":return i;case"string":return r?i.toLowerCase():i;case"number":return Number.isInteger(i)?Cast.toInt(i):i;default:return i instanceof Date?i:Array.isArray(i)&&i.every(e=>"string"==typeof e)&&r?Strings.sliceToLower(i):i}}var dimensionFlag,LeafNode,Edge,Node,Tree,init_frontmatter=__esm({"internal/domain/content/vo/frontmatter.ts"(){init_kind(),init_cast2(),init_string2(),init_types3(),FrontMatterParserImpl=class{params;langSvc;taxonomySvc;constructor(e,t,r){this.params=e,this.langSvc=t,this.taxonomySvc=r}async parse(e){const t={terms:{},params:this.params,path:"",lang:"",kind:"",title:"",description:"",weight:999};try{await this.parseCustomized(t)}catch(e){throw e}try{await this.parseTerms(t)}catch(e){throw e}try{await this.parseTitle(t)}catch(e){throw e}try{await this.parseDescription(t)}catch(e){throw e}try{await this.parseWeight(t)}catch(e){throw e}try{await this.parseDate(t)}catch(e){throw e}try{await this.parseOrganization(t,e)}catch(e){throw e}try{await this.parseAuthor(t,e)}catch(e){throw e}try{await this.parseMenu(t)}catch(e){throw e}return t}async parseDate(e){if(this.params){const t=this.params.date;null!=t&&(e.date=Cast.toTime(t))}}async parseWeight(e){if(e.weight=999,this.params){const t=this.params.weight;null!=t&&(e.weight=Cast.toInt(t))}}async parseTitle(e){if(this.params){const t=this.params.title;null!=t&&(e.title=Cast.toString(t))}}async parseDescription(e){if(this.params){const t=this.params.description;null!=t&&(e.description=Cast.toString(t))}}async parseCustomized(e){if(!this.params)return;const t=this.params.path;null!=t&&(e.path=this.toSlashPreserveLeading(Cast.toString(t)));const r=this.params.lang;if(null!=r){const t=Cast.toString(r).toLowerCase();this.langSvc.isLanguageValid(t)&&(e.lang=t)}const i=this.params.kind;if(null!=i){const t=Cast.toString(i);if(""!==t){const r=getKindMain(t);if(""===r)throw new Error(`unknown kind "${t}" in front matter`);e.kind=r}}}async parseTerms(e){const t=this.taxonomySvc.views();for(const r of t){const t=Types.toStringSlicePreserveString(getParam(this.params||{},r.plural(),!1));null!==t&&(e.terms[r.plural()]=t)}}async parseOrganization(e,t){if(!this.params)return;const r=this.params.organization;if(!r||"object"!=typeof r)return;const i={};void 0!==r.name&&null!==r.name&&(i.name=Cast.toString(r.name)),void 0!==r.description&&null!==r.description&&(i.description=Cast.toString(r.description)),void 0!==r.vision&&null!==r.vision&&(i.vision=Cast.toString(r.vision)),void 0!==r.website&&null!==r.website&&(i.website=Cast.toString(r.website)),void 0!==r.logo&&null!==r.logo&&(i.logo=path17.join(t,Cast.toString(r.logo)));const s=this.parseContact(r.contact);s&&(i.contact=s);const n=this.parseSocial(r.social);n&&(i.social=n),Object.keys(i).length>0&&(e.organization=i)}async parseMenu(e){if(!this.params)return;const t=this.params.menu;if(!t||"object"!=typeof t)return;const r={};for(const[e,i]of Object.entries(t))if(!1!==i){if(Array.isArray(i)){const t=this.parseMenuItems(i);t.length>0&&(r[e]=t)}else if(i&&"object"==typeof i){const t={};for(const[e,r]of Object.entries(i))if(!1===r)t[e]=!1;else if(Array.isArray(r)){const i=this.parseMenuItems(r);i.length>0&&(t[e]=i)}Object.keys(t).length>0&&(r[e]=t)}}else r[e]=!1;Object.keys(r).length>0&&(e.menu=r)}parseMenuItems(e){const t=[];for(const r of e){if(!r||"object"!=typeof r)continue;const e={title:"",url:""};if(void 0!==r.title&&null!==r.title&&(e.title=Cast.toString(r.title),void 0!==r.url&&null!==r.url)){{const t=Cast.toString(r.url);e.url=""===t?"":t}if(void 0!==r.weight&&null!==r.weight&&(e.weight=Cast.toInt(r.weight)),Array.isArray(r.children)){const t=this.parseMenuItems(r.children);t.length>0&&(e.children=t)}t.push(e)}}return t}async parseAuthor(e,t){if(!this.params)return;const r=this.params.author;if(!r||"object"!=typeof r)return;const i={};void 0!==r.name&&null!==r.name&&(i.name=Cast.toString(r.name)),void 0!==r.description&&null!==r.description&&(i.description=Cast.toString(r.description)),void 0!==r.website&&null!==r.website&&(i.website=Cast.toString(r.website)),void 0!==r.avatar&&null!==r.avatar&&(i.avatar=path17.join(t,Cast.toString(r.avatar)));const s=this.parseContact(r.contact);s&&(i.contact=s);const n=this.parseSocial(r.social);n&&(i.social=n),Object.keys(i).length>0&&(e.author=i)}parseContact(e){if(!e||"object"!=typeof e)return null;const t={};return void 0!==e.email&&null!==e.email&&(t.email=Cast.toString(e.email)),void 0!==e.address&&null!==e.address&&(t.address=Cast.toString(e.address)),void 0!==e.phone&&null!==e.phone&&(t.phone=Cast.toString(e.phone)),Object.keys(t).length>0?t:null}parseSocial(e){if(!e||"object"!=typeof e)return null;const t={},r=["github","twitter","linkedin"];for(const i of r)void 0!==e[i]&&null!==e[i]&&(t[i]=Cast.toString(e[i]));for(const[i,s]of Object.entries(e))r.includes(i)||null==s||(t[i]=Cast.toString(s));return Object.keys(t).length>0?t:null}toSlashPreserveLeading(e){return e.replace(/\\/g,"/")}}}}),init_classifier=__esm({"internal/domain/content/vo/classifier.ts"(){init_fileinfo2()}}),init_dimensions=__esm({"pkg/doctree/dimensions.ts"(){dimensionFlag={has:(e,t)=>(e&t)===t,set:(e,t)=>e|t,index:e=>{if(0===e)throw new Error("dimension flag not set");return e-1}}}});function longestPrefix(e,t){const r=Math.min(e.length,t.length);let i=0;for(i=0;i<r&&e[i]===t[i];i++);return i}async function recursiveWalk(e,t){if(null!==e.leaf&&await t(e.leaf.key,e.leaf.val))return!0;let r=0,i=e.edges.length;for(;r<i;){const s=e.edges[r];if(await recursiveWalk(s.node,t))return!0;if(0===e.edges.length)return recursiveWalk(e,t);e.edges.length>=i&&r++,i=e.edges.length}return!1}var WalkableTrees,MutableTrees,init_radix=__esm({"pkg/radix/radix.ts"(){LeafNode=class{key;val;constructor(e,t){this.key=e,this.val=t}},Edge=class{label;node;constructor(e,t){this.label=e,this.node=t}},Node=class{leaf=null;prefix="";edges=[];isLeaf(){return null!==this.leaf}addEdge(e){const t=this.edges.length;let r=0;for(;r<t&&this.edges[r].label<e.label;)r++;this.edges.splice(r,0,e)}updateEdge(e,t){const r=this.edges.length;let i=0;for(;i<r&&this.edges[i].label<e;)i++;if(!(i<r&&this.edges[i].label===e))throw new Error("replacing missing edge");this.edges[i].node=t}getEdge(e){const t=this.edges.length;let r=0;for(;r<t&&this.edges[r].label<e;)r++;return r<t&&this.edges[r].label===e?this.edges[r].node:null}delEdge(e){const t=this.edges.length;let r=0;for(;r<t&&this.edges[r].label<e;)r++;r<t&&this.edges[r].label===e&&this.edges.splice(r,1)}mergeChild(){const e=this.edges[0].node;this.prefix=this.prefix+e.prefix,this.leaf=e.leaf,this.edges=e.edges}},Tree=class e{root;size;constructor(){this.root=new Node,this.size=0}static newFromMap(t){const r=new e;if(t)if(t instanceof Map)t.forEach((e,t)=>{r.insert(t,e)});else for(const[e,i]of Object.entries(t))r.insert(e,i);return r}len(){return this.size}insert(e,t){let r=null,i=this.root,s=e;for(;;){if(0===s.length){if(i.isLeaf()){const e=i.leaf.val;return i.leaf.val=t,[e,!0]}return i.leaf=new LeafNode(e,t),this.size++,[void 0,!1]}if(r=i,i=i.getEdge(s.charCodeAt(0)),null===i){const i=new Edge(s.charCodeAt(0),new Node);return i.node.leaf=new LeafNode(e,t),i.node.prefix=s,r.addEdge(i),this.size++,[void 0,!1]}const n=longestPrefix(s,i.prefix);if(n===i.prefix.length){s=s.substring(n);continue}this.size++;const a=new Node;a.prefix=s.substring(0,n),r.updateEdge(s.charCodeAt(0),a),a.addEdge(new Edge(i.prefix.charCodeAt(n),i)),i.prefix=i.prefix.substring(n);const o=new LeafNode(e,t);if(s=s.substring(n),0===s.length)return a.leaf=o,[void 0,!1];const l=new Node;return l.leaf=o,l.prefix=s,a.addEdge(new Edge(s.charCodeAt(0),l)),[void 0,!1]}}delete(e){let t=null,r=0,i=this.root,s=e;for(;;){if(0===s.length){if(!i.isLeaf())break;const e=i.leaf;return i.leaf=null,this.size--,null!==t&&0===i.edges.length&&t.delEdge(r),i!==this.root&&1===i.edges.length&&i.mergeChild(),null===t||t===this.root||1!==t.edges.length||t.isLeaf()||t.mergeChild(),[e.val,!0]}if(t=i,r=s.charCodeAt(0),i=i.getEdge(r),null===i)break;if(!s.startsWith(i.prefix))break;s=s.substring(i.prefix.length)}return[void 0,!1]}async deletePrefix(e){return await this._deletePrefix(null,this.root,e)}async _deletePrefix(e,t,r){if(0===r.length){let r=0;return await recursiveWalk(t,(e,t)=>(r++,Promise.resolve(!1))),t.isLeaf()&&(t.leaf=null),t.edges=[],null===e||e===this.root||1!==e.edges.length||e.isLeaf()||e.mergeChild(),this.size-=r,r}const i=r.charCodeAt(0),s=t.getEdge(i);return null===s||!s.prefix.startsWith(r)&&!r.startsWith(s.prefix)?0:(r=s.prefix.length>r.length?r.substring(r.length):r.substring(s.prefix.length),this._deletePrefix(t,s,r))}get(e){let t=this.root,r=e;for(;;){if(0===r.length){if(t.isLeaf())return[t.leaf.val,!0];break}if(t=t.getEdge(r.charCodeAt(0)),null===t)break;if(!r.startsWith(t.prefix))break;r=r.substring(t.prefix.length)}return[void 0,!1]}longestPrefix(e){let t=null,r=this.root,i=e;for(;r.isLeaf()&&(t=r.leaf),0!==i.length&&(r=r.getEdge(i.charCodeAt(0)),null!==r)&&i.startsWith(r.prefix);)i=i.substring(r.prefix.length);return null!==t?[t.key,t.val,!0]:["",void 0,!1]}minimum(){let e=this.root;for(;;){if(e.isLeaf())return[e.leaf.key,e.leaf.val,!0];if(!(e.edges.length>0))break;e=e.edges[0].node}return["",void 0,!1]}maximum(){let e=this.root;for(;;){const t=e.edges.length;if(!(t>0)){if(e.isLeaf())return[e.leaf.key,e.leaf.val,!0];break}e=e.edges[t-1].node}return["",void 0,!1]}async walk(e){await recursiveWalk(this.root,e)}async walkPrefix(e,t){let r=this.root,i=e;for(;;){if(0===i.length)return void await recursiveWalk(r,t);if(r=r.getEdge(i.charCodeAt(0)),null===r)return;if(!i.startsWith(r.prefix))return void(r.prefix.startsWith(i)&&await recursiveWalk(r,t));i=i.substring(r.prefix.length)}}async walkPath(e,t){let r=this.root,i=e;for(;;){if(null!==r.leaf&&await t(r.leaf.key,r.leaf.val))return;if(0===i.length)return;if(r=r.getEdge(i.charCodeAt(0)),null===r)return;if(!i.startsWith(r.prefix))break;i=i.substring(r.prefix.length)}}async toMap(){const e={};return await this.walk((t,r)=>(e[t]=r,Promise.resolve(!1))),e}}}}),init_radix2=__esm({"pkg/radix/index.ts"(){init_radix()}});function cleanKey(e){return"/"===e?"":e}function mustValidateKey(e){const t=function(e){return""===e?null:e.length<2?new Error(`too short key: "${e}"`):"/"!==e[0]?new Error(`key must start with '/': "${e}"`):"/"===e[e.length-1]?new Error(`key must not end with '/': "${e}"`):null}(e);if(t)throw t;return e}var SimpleTree,init_support=__esm({"pkg/doctree/support.ts"(){init_radix2(),WalkableTrees=class{trees;constructor(e){this.trees=e}walkPrefixRaw(e,t){for(const r of this.trees)r.walkPrefixRaw(e,t)}},MutableTrees=class{trees;constructor(e){this.trees=e}delete(e){for(const t of this.trees)t.delete(e)}deleteAll(e){for(const t of this.trees)t.deleteAll(e)}async deletePrefix(e){let t=0;for(const r of this.trees)t+=await r.deletePrefix(e);return Promise.resolve(t)}async deletePrefixAll(e){let t=0;for(const r of this.trees)t+=await r.deletePrefixAll(e);return t}lock(e){const t=this.trees.map(t=>t.lock(e));return()=>{for(const e of t)e()}}canLock(){for(const e of this.trees)if(!e.canLock())return!1;return!0}}}});function newSimpleTree(){return new SimpleTree}var TreeShiftTree,NodeShiftTree,NodeShiftTreeWalker,Shifter2,PageShifter,SourceShifter,WeightedTermTreeNode,PageTreesNode,PageTrees,init_simpletree=__esm({"pkg/doctree/simpletree.ts"(){init_radix2(),init_support(),SimpleTree=class{mu;tree;zero;constructor(){this.tree=new Tree,this.zero=void 0;let e=!1,t=0;this.mu={lock:()=>{for(;e||t>0;);e=!0},unlock:()=>{e=!1},rLock:()=>{for(;e;);t++},rUnlock:()=>{t--}}}get(e){this.mu.rLock();try{const[t,r]=this.tree.get(e);return r?t:this.zero}finally{this.mu.rUnlock()}}longestPrefix(e){this.mu.rLock();try{const[t,r,i]=this.tree.longestPrefix(e);return i?[t,r]:["",this.zero]}finally{this.mu.rUnlock()}}insert(e,t){this.mu.lock();try{return this.tree.insert(e,t),t}finally{this.mu.unlock()}}async walkPrefix(e,t,r){switch(e){case 0:break;case 1:this.mu.rLock();break;case 2:this.mu.lock()}try{let e=null;return await this.tree.walkPrefix(t,async(t,i)=>{const[s,n]=r(t,i);return n?(e=n,Promise.resolve(!0)):s}),e}finally{switch(e){case 0:break;case 1:this.mu.rUnlock();break;case 2:this.mu.unlock()}}}}}}),init_treeshifttree=__esm({"pkg/doctree/treeshifttree.ts"(){init_simpletree(),TreeShiftTree=class e{d;v;trees;constructor(e,t){if(t<=0)throw new Error("length must be > 0");this.d=e,this.v=0,this.trees=[];for(let e=0;e<t;e++)this.trees.push(newSimpleTree())}static newTreeShiftTree(t,r){return new e(t,r)}shape(t,r){if(t!==this.d)throw new Error("dimension mismatch");if(r>=this.trees.length)throw new Error("value out of range");const i=Object.create(e.prototype);return Object.assign(i,this),i.v=r,i}get(e){return this.trees[this.v].get(e)}longestPrefix(e){return this.trees[this.v].longestPrefix(e)}insert(e,t){return this.trees[this.v].insert(e,t)}async walkPrefix(e,t,r){return await this.trees[this.v].walkPrefix(e,t,r)}delete(e){for(const t of this.trees)t.tree.delete(e)}async deletePrefix(e){let t=0;for(const r of this.trees)t+=await r.tree.deletePrefix(e);return t}lock(e){if(e){for(const e of this.trees)e.mu.lock();return()=>{for(const e of this.trees)e.mu.unlock()}}for(const e of this.trees)e.mu.rLock();return()=>{for(const e of this.trees)e.mu.rUnlock()}}}}}),init_nodeshifttree=__esm({"pkg/doctree/nodeshifttree.ts"(){init_radix2(),init_dimensions(),init_support(),NodeShiftTree=class e{tree;dims;shifter;mu;constructor(e){if(!e.shifter)throw new Error("Shifter is required");this.shifter=e.shifter,this.tree=new Tree,this.dims=[0];let t=!1,r=0;this.mu={lock:()=>{for(;t||r>0;);t=!0},unlock:()=>{t=!1},rLock:()=>{for(;t;);r++},rUnlock:()=>{r--},tryLock:()=>!(t||r>0||(t=!0,0))}}static new(t){return new e(t)}delete(e){this.deleteInternal(e)}async deleteAll(e){await this.tree.walkPrefix(e,(e,t)=>{const[r,i]=this.tree.delete(e);return Promise.resolve(!1)})}async deletePrefix(e){let t=0;const r=[];await this.tree.walkPrefix(e,(e,t)=>(r.push(e),Promise.resolve(!1)));for(const e of r)this.deleteInternal(e)&&t++;return t}deleteInternal(e){let t=!1;const[r,i]=this.tree.get(e);if(i){const[i,s]=this.shifter.delete(r,this.dims);t=i,s&&this.tree.delete(e)}return t}async deletePrefixAll(e){let t=0;return await this.tree.walkPrefix(e,(e,r)=>{const[i,s]=this.tree.delete(e);return s&&t++,Promise.resolve(!1)}),t}increment(e){return this.shape(e,this.dims[e]+1)}insertIntoCurrentDimension(e,t){e=mustValidateKey(cleanKey(e));const[r,i]=this.tree.get(e);return i&&(t=this.shifter.insertInto(r,t,this.dims)),this.tree.insert(e,t),[t,!0]}insertIntoValuesDimension(e,t){e=mustValidateKey(cleanKey(e));const[r,i]=this.tree.get(e);return i&&(t=this.shifter.insert(r,t)),this.tree.insert(e,t),[t,!0]}insertRawWithLock(e,t){this.mu.lock();try{return this.tree.insert(e,t)}finally{this.mu.unlock()}}insertWithLock(e,t){this.mu.lock();try{return this.insertIntoValuesDimension(e,t)}finally{this.mu.unlock()}}len(){return this.tree.len()}canLock(){const e=this.mu.tryLock();return e&&this.mu.unlock(),e}lock(e){return e?this.mu.lock():this.mu.rLock(),()=>{e?this.mu.unlock():this.mu.rUnlock()}}longestPrefix(e,t,r){let i=e;for(;;){const[e,s,n]=this.tree.longestPrefix(i);if(n){const[i,n]=this.shift(s,t);if(n&&(!r||r(i)))return[e,i]}if(""===i||"/"===i)return["",void 0];const a=i.lastIndexOf("/");if(0===a)i="";else{if(!(a>0))break;i=i.substring(0,a)}}return["",void 0]}longestPrefixAll(e){const[t,,r]=this.tree.longestPrefix(e);return[t,r]}getRaw(e){const[t,r]=this.tree.get(e);return r?[t,!0]:[void 0,!1]}async walkPrefixRaw(e,t){await this.tree.walkPrefix(e,(e,r)=>t(e,r))}shape(e,t){const r=this.clone();return r.dims[e]=t,r}toString(){return`Root{${this.dims}}`}get(e){const[t]=this.getInternal(e);return t}forEachInDimension(e,t,r){e=cleanKey(e);const[i,s]=this.tree.get(e);s&&this.shifter.forEachInDimension(i,t,r)}has(e){const[,t]=this.getInternal(e);return t}clone(){const t=Object.create(e.prototype);return Object.assign(t,this),t.dims=[...this.dims],t}shift(e,t){const[r,i]=this.shifter.shift(e,this.dims,t);return[r,i]}getInternal(e){e=cleanKey(e);const[t,r]=this.tree.get(e);if(!r)return[void 0,!1];const[i,s]=this.shift(t,!0);return[i,s]}},NodeShiftTreeWalker=class e{tree;handle;prefix;lockType;noShift;exact;debug;walkContext;skipPrefixes=[];constructor(e){if(!e.tree)throw new Error("Tree is required");this.tree=e.tree,this.handle=e.handle,this.prefix=e.prefix||"",this.lockType=e.lockType||0,this.noShift=e.noShift||!1,this.exact=e.exact||!1,this.debug=e.debug||!1,this.walkContext=e.walkContext}extend(){const t=new e({tree:this.tree,handle:this.handle,prefix:this.prefix,lockType:this.lockType,noShift:this.noShift,exact:this.exact,debug:this.debug,walkContext:this.walkContext});return t.resetLocalState(),t}skipPrefix(...e){this.skipPrefixes.push(...e)}shouldSkip(e){for(const t of this.skipPrefixes)if(e.startsWith(t))return!0;return!1}async walk(){this.resetLocalState();let e=null;this.lockType>0&&(e=this.tree.lock(2===this.lockType));try{let e=null;const t=async(t,r)=>{if(this.shouldSkip(t))return!1;const[i,s,n]=this.toT(this.tree,r);if(!s)return!1;const[a,o]=await this.handle(t,i,n);return!(!a&&!o||(e=o,0))};return""!==this.prefix?await this.tree.tree.walkPrefix(this.prefix,t):await this.tree.tree.walk(t),e}finally{e&&e()}}resetLocalState(){this.skipPrefixes=[]}toT(e,t){if(this.noShift)return[t,!0,2];{const[r,i,s]=e.shifter.shift(t,e.dims,this.exact);return[r,i,s]}}}}}),init_doctree=__esm({"pkg/doctree/index.ts"(){init_dimensions(),init_support(),init_simpletree(),init_treeshifttree(),init_nodeshifttree()}}),init_shifter=__esm({"internal/domain/content/entity/shifter.ts"(){init_pagetrees(),init_doctree(),Shifter2=class{delete(e,t){return[e.delete(t[dimensionFlag.index(1)]),e.isEmpty()]}shift(e,t,r){const[i,s]=e.shift(t[dimensionFlag.index(1)],r);return null!==i?s?[i,!0,1]:[i,!0,2]:[new PageTreesNode,!1,2]}forEachInDimension(e,t,r){if(t!==dimensionFlag.index(1))throw new Error("only language dimension supported");r(e)}insertInto(e,t,r){return e.mergeWithLang(t,r[dimensionFlag.index(1)])}insert(e,t){return e.merge(t)}}}}),init_shifterpage=__esm({"internal/domain/content/entity/shifterpage.ts"(){init_pagetrees(),init_doctree(),init_shifter(),PageShifter=class extends Shifter2{shift(e,t,r){const[i,s]=e.shift(t[dimensionFlag.index(1)],r);return null!==i&&s?[i,!0,1]:[new PageTreesNode,!1,2]}}}}),init_shifterpagesource=__esm({"internal/domain/content/entity/shifterpagesource.ts"(){init_pagetrees(),init_doctree(),init_shifter(),SourceShifter=class extends Shifter2{shift(e,t,r){const[i,s]=e.shift(t[dimensionFlag.index(1)],r);return null!==i?s?[i,!0,1]:[i,!0,2]:[new PageTreesNode,!1,2]}}}});function newPageTreesNode2(e){const t=new PageTreesNode;return e&&t.setNode(e.pageIdentity(),e),t}var pageIDCounter,log23,Source,init_pagetrees=__esm({"internal/domain/content/entity/pagetrees.ts"(){init_doctree(),init_shifterpage(),init_shifterpagesource(),WeightedTermTreeNode=class{pageTreesNodeInstance;term;constructor(e,t){this.pageTreesNodeInstance=e,this.term=t}getPage(){return this.pageTreesNodeInstance.getPage()}getPages(){return this.pageTreesNodeInstance.getPages()}getResource(){return this.pageTreesNodeInstance.getResource()}isEmpty(){return this.pageTreesNodeInstance.isEmpty()}shift(e,t){return this.pageTreesNodeInstance.shift(e,t)}},PageTreesNode=class{nodes;constructor(){this.nodes=new Map}setNode(e,t){this.nodes.set(e,t)}merge(e){const t=new Map;for(const e of this.nodes.keys())t.set(e.pageLanguage(),e);for(const[r,i]of e.nodes.entries()){const e=t.get(r.pageLanguage());e?this.nodes.set(e,i):this.nodes.set(r,i)}return this}mergeWithLang(e,t){const r=new Map;for(const e of this.nodes.keys())r.set(e.pageLanguage(),e);for(const[i,s]of e.nodes.entries()){const e=r.get(i.pageLanguage());if(e){const r=this.nodes.get(e);r&&r.pageIdentity().pageLanguageIndex()===t&&this.remove(e)}this.nodes.set(i,s)}return this}remove(e){const t=this.nodes.get(e);return!!t&&(this.markStale(t),this.nodes.delete(e),!0)}delete(e){for(const[t,r]of this.nodes.entries())if(r.pageIdentity().pageLanguageIndex()===e)return this.remove(t);return!1}isEmpty(){return 0===this.nodes.size}shift(e,t){let r=null;for(const[t,i]of this.nodes.entries())if(null===r&&(r=i),i.pageIdentity().pageLanguageIndex()===e)return[newPageTreesNode2(i),!0];return null===r||t?[null,!1]:[newPageTreesNode2(r),!1]}getPage(){for(const e of this.nodes.values())if(e&&"function"==typeof e.kind)return[e,!0];return[null,!1]}getPages(){const e=[];for(const t of this.nodes.values())t&&"function"==typeof t.kind&&e.push(t);return e}getResource(){for(const e of this.nodes.values())return[e,!0];return[null,!1]}markStale(e){"staleVersions"in e&&e.staleVersions}},PageTrees=class{treePages;treeResources;treePagesResources;treeTaxonomyEntries;resourceTrees;constructor(){this.treePages=new NodeShiftTree({shifter:new PageShifter}),this.treeResources=new NodeShiftTree({shifter:new SourceShifter}),this.treeTaxonomyEntries=TreeShiftTree.newTreeShiftTree(0,10),this.treePagesResources=new WalkableTrees([]),this.resourceTrees=new MutableTrees([]),this.treePagesResources=new WalkableTrees([this.treePages,this.treeResources]),this.resourceTrees=new MutableTrees([this.treeResources])}createMutableTrees(){this.treePagesResources=new WalkableTrees([this.treePages,this.treeResources]),this.resourceTrees=new MutableTrees([this.treeResources])}get TreePages(){return this.treePages}get TreeResources(){return this.treeResources}get TreePagesResources(){return this.treePagesResources}get TreeTaxonomyEntries(){return this.treeTaxonomyEntries}get ResourceTrees(){return this.resourceTrees}}}});function newPageSource(e){return new Source(e)}var log24,ambiguousContentNode,ContentTreeReverseIndexMap,ContentTreeReverseIndex,pagePredicates,PageMapQueryPagesBelowPathImpl,PageMapQueryPagesInSectionImpl,PageMap,init_pagesource=__esm({"internal/domain/content/entity/pagesource.ts"(){init_log(),init_identity(),pageIDCounter=0,log23=getDomainLogger("content",{component:"pagesource"}),Source=class{id;identity;file;constructor(e){this.id=(++pageIDCounter).toString(),this.identity=new Identity(pageIDCounter),this.file=e}sourceKey(){return`${this.identity.lang}/${this.file.filename()}`.replace(/\\/g,"/")}async contentSource(){return await this.readSourceAll()}async readSourceAll(){try{const e=await this.file.open(),t=await e.stat(),r=new Uint8Array(t.size()),i=await e.read(r);return await e.close(),i.buffer}catch(e){const t=e instanceof Error?e.message:String(e);throw new Error(`Failed to read file content: ${t}`)}}async posOffset(e){try{const t=await this.contentSource();return function(e,t,r){if(r<0)return{filename:e,lineNumber:0,columnNumber:0,offset:0};const i=t.slice(0,r);let s=1;for(let e=0;e<i.length;e++)10===i[e]&&s++;let n=-1;for(let e=i.length-1;e>=0;e--)if(10===i[e]){n=e;break}return{filename:e,lineNumber:s,columnNumber:r-n,offset:r}}(this.file.filename(),t,e)}catch(e){throw new Error(`failed to read content source for "${this.file.filename()}": ${e}`)}}pageIdentity(){return this.identity}pageFile(){return this.file}staleVersions(){return[]}section(){return this.file.section()}paths(){return this.file.paths()}path(){return this.file.paths().path()}slug(){return this.pathToSlug(this.path())}pathToSlug(e){let t=e.replace(/^\//,"");return t=t.replace(/\.md$/,""),t.endsWith("/index")&&(t=t.replace(/\/index$/,"")),"index"!==t&&""!==t||(t="index"),t.endsWith("/_index")&&(t=t.replace(/\/_index$/,"")),t}opener(){return()=>this.file.open()}openReader(){return{read:async()=>new Uint8Array(0)}}async content(){try{return log23.error(`Reading content not implemented from: ${this.file.filename()}`),new Uint8Array(0)}catch(e){const t=`failed to read content source for "${this.file.filename()}": ${e}`;throw log23.error(t),new Error(t)}}}}});function addTrailingSlash(e){return e.endsWith("/")||(e+="/"),e}var log25,PagesCollector,log26,Content2,MDConverter,Content3,init_pagemap=__esm({"internal/domain/content/entity/pagemap.ts"(){init_pagetrees(),init_pagesource(),init_type7(),init_doctree(),init_sort(),init_log(),log24=getDomainLogger("content",{component:"pagemap"}),ambiguousContentNode=new PageTreesNode,ContentTreeReverseIndexMap=class{initOnce=!1;m=new Map;constructor(){}},ContentTreeReverseIndex=class{initFn;contentTreeReverseIndexMap;constructor(e){this.initFn=e,this.contentTreeReverseIndexMap=new ContentTreeReverseIndexMap}reset(){this.contentTreeReverseIndexMap=new ContentTreeReverseIndexMap}get(e){return this.contentTreeReverseIndexMap.initOnce||(this.contentTreeReverseIndexMap.m=new Map,this.initFn(this.contentTreeReverseIndexMap.m),this.contentTreeReverseIndexMap.initOnce=!0),this.contentTreeReverseIndexMap.m.get(e)||null}},pagePredicates={kindPage:e=>"page"===e.kind(),kindSection:e=>"section"===e.kind(),kindHome:e=>"home"===e.kind(),kindTerm:e=>"term"===e.kind(),shouldListLocal:e=>!e.shouldList||e.shouldList(!1),shouldListGlobal:e=>!e.shouldList||e.shouldList(!0),shouldListAny:e=>!e.shouldListAny||e.shouldListAny(),shouldLink:e=>!e.noLink||!e.noLink()},PageMapQueryPagesBelowPathImpl=class{path;keyPart;include;constructor(e,t,r=pagePredicates.shouldListLocal){this.path=e,this.keyPart=t,this.include=r}key(){return this.path+"/"+this.keyPart}},PageMapQueryPagesInSectionImpl=class extends PageMapQueryPagesBelowPathImpl{recursive;includeSelf;index;constructor(e,t,r,i,s,n){super(e,t,n),this.recursive=r,this.includeSelf=i,this.index=s}key(){return"gagesInSection/"+super.key()+"/"+this.recursive.toString()+"/"+this.index.toString()+"/"+this.includeSelf.toString()}},PageMap=class extends PageTrees{pageReverseIndex=null;pageBuilder;constructor(e){super(),this.pageBuilder=e}setupReverseIndex(){this.pageReverseIndex=new ContentTreeReverseIndex(async e=>{const t=new NodeShiftTreeWalker({tree:this.treePages,lockType:1,handle:async(t,r,i)=>{if(r){const[t,i]=r.getPage();if(!i)return[!1,null];t.pageFile&&t.pageFile()&&((t,r)=>{const i=e.get(t);i&&i!==ambiguousContentNode?e.set(t,ambiguousContentNode):i||e.set(t,r)})(t.paths().baseNameNoIdentifier(),r)}return[!1,null]}});try{await t.walk()}catch(e){log24.error(`setupReverseIndex error: ${e}`)}})}insertResourceNode(e,t){const r=this.treeResources,i=r.lock(!0);try{r.insertIntoValuesDimension(e,t)}finally{i()}}async addFi(e){if(e.fileInfo().isDir())return;const t=newPageSource(e),r=t.paths().base();switch(t.file.getBundleType()){case 0:this.insertResourceNode(r,newPageTreesNode2(t));break;case 1:const e=await this.pageBuilder.withSource(t).build();if(!e)return;this.insertResourceNode(r,newPageTreesNode2(e));break;default:const i=await this.pageBuilder.withSource(t).build();this.treePages.insertWithLock(t.paths().base(),newPageTreesNode2(i))}}async assemble(){await this.assembleStructurePages(),await this.applyAggregates(),await this.cleanPages(),await this.assembleTerms()}async assembleTerms(){for(const e of this.pageBuilder.langSvc.languageIndexes()){const t=this.treePages.shape(0,e),r=this.treeTaxonomyEntries.shape(0,e);await this.pageBuilder.term.assemble(t,r,this.pageBuilder,e)}}async cleanPages(){}async applyAggregates(){}async assembleStructurePages(){await this.addMissingTaxonomies();for(const e of this.pageBuilder.langSvc.languageIndexes()){const t=this.treePages.shape(0,e);await this.pageBuilder.section.assemble(t,this.pageBuilder,e)}await this.addMissingStandalone()}async addMissingTaxonomies(){const e=this.treePages.lock(!0);try{for(const e of this.pageBuilder.langSvc.languageIndexes()){const t=this.treePages.shape(0,e);await this.pageBuilder.taxonomy.assemble(t,this.pageBuilder,e)}}finally{e()}}async addMissingStandalone(){const e=this.treePages,t=e.lock(!0);try{await this.pageBuilder.standalone.assemble(e,this.pageBuilder)}finally{t()}}async getResourcesForPage(e){const t=[];return await this.forEachResourceInPage(e,0,!1,(e,r,i)=>{const[s,n]=r.getResource();return n&&t.push(s),[!1,null]}),t}async forEachResourceInPage(e,t,r,i){let s=e.paths().base();"/"===s&&(s="");const n=addTrailingSlash(s),a="page"!==e.kind(),o=new NodeShiftTreeWalker({tree:this.treeResources.shape(0,e.pageIdentity().pageLanguageIndex()),prefix:n,lockType:t,exact:r,handle:async(e,t,r)=>{if(a){const[t]=this.treePages.longestPrefixAll(e);if(t!==s&&this.pathDir(t)!==this.pathDir(e))return o.skipPrefix(t+"/"),[!1,null]}return i(e,t,r)}});try{await o.walk()}catch(e){log24.error(`forEachResourceInPage error: ${e}`)}}async getPagesInSection(e,t){const r=t.key(),i=this.treePages.shape(0,e);return this.getOrCreatePagesFromCacheSync(null,r,async e=>{const r=addTrailingSlash(t.path),s=[];let n="";const a=t.include,o=new NodeShiftTreeWalker({tree:i,prefix:r,handle:async(e,r,i)=>{if(t.recursive){const[e,t]=r.getPage();return t&&a(e)&&s.push(e),[!1,null]}const[l,c]=r.getPage();if(c&&a(l)&&s.push(l),!l.isPage||!l.isPage()){const t=e+"/";""!==n&&n===t||o.skipPrefix(t),n=t}return[!1,null]}});try{if(await o.walk(),t.includeSelf){const e=i.get(t.path);if(e){const[t,r]=e.getPage();r&&a(t)&&s.push(t)}}const e=s;return function(e){if(0===e.length)return;const t=e[0].pageWeight();e.every(e=>e.pageWeight()===t)?sortByTitle(e):function(e){pageBy(weight).sort(e)}(e)}(e),Promise.resolve(e)}catch(e){log24.error(`getPagesInSection error: ${e}`)}return Promise.resolve(s)})}async getOrCreatePagesFromCacheSync(e,t,r){return await r(t)}async getPagesWithTerm(e,t){const r=t.key(),i=this.treeTaxonomyEntries.shape(0,e);return await this.getOrCreatePagesFromCacheSync(null,r,async e=>{const r=[],s=t.include;try{await i.walkPrefix(0,addTrailingSlash(t.path),(e,t)=>{const[i,n]=t.getPage();return n&&s(i)&&r.push(i),[!1,null]});const e=r;return sortByTitle(e),e}catch(e){log24.error(`getPagesWithTerm error: ${e}`)}return r})}getTermsForPageInTaxonomy(e,t,r){const i=((s=r).startsWith("/")||(s="/"+s),s);var s;const n=this.treeTaxonomyEntries.shape(0,e);return this.getOrCreatePagesFromCacheSync(null,i+t,async e=>{const r=[];try{await n.walkPrefix(0,addTrailingSlash(i),(e,i)=>(e.endsWith(t)&&r.push(i.term.page),[!1,null]));const e=r;return sortByTitle(e),e}catch(e){log24.error(`getTermsForPageInTaxonomy error: ${e}`)}return r})}async getSections(e,t){const r=[];let i="";const s=this.treePages.shape(0,e),n=new NodeShiftTreeWalker({tree:s,prefix:t,handle:async(e,t,s)=>{const[a,o]=t.getPage();return o?(a.isPage&&a.isPage()||(""!==i&&e.startsWith(i)||(a.isSection&&a.isSection()&&a.shouldList&&a.shouldList(!1)&&a.parent&&a.parent()===a?r.push(a):n.skipPrefix(e+"/")),i=e+"/"),[!1,null]):[!1,null]}});try{await n.walk();const e=r;return sortByTitle(e),e}catch(e){log24.error(`getSections error: ${e}`)}return r}pathDir(e){const t=e.lastIndexOf("/");return-1===t?"":e.substring(0,t)}}}}),init_pagecollector=__esm({"internal/domain/content/entity/pagecollector.ts"(){init_content3(),init_log(),log25=getDomainLogger("content",{component:"pagecollector"}),PagesCollector=class{m;fs;processedPaths=new Set;constructor(e,t){this.m=e,this.fs=t}async collect(){try{const e="",t=this.fs.contentFs();for(const r of t){this.processedPaths.clear();const t=await r.stat(e);await this.collectDir(r,e,t)}}catch(e){log25.error(`Failed to collect directory: ${e}, continuing...`)}}async collectDir(e,t,r){try{await this.fs.walkContent(e,t,{hookPre:async(e,t,r)=>{const i=t;if(this.processedPaths.has(i))return log25.warn("Path already processed!",{path:i,dirName:e.name(),dirIsDir:e.isDir(),readdirLength:r.length}),[];if(this.processedPaths.add(i),0===r.length)return[];for(const e of r){if(e.isDir&&e.isDir())continue;const t=newFileInfo2(e);await this.m.addFi(t)}return r},walkFn:async(e,t)=>{}},{info:r})}catch(e){throw log25.error(`Failed to collect directory: ${e}`,{path:t,rootName:r.name(),rootIsDir:r.isDir(),stack:e.stack||"No stack trace available"}),new Error(`Failed to collect directory: ${e}`)}}async handleBundleLeaf(e,t,r,i){const s=t.paths(),n=async(e,r)=>{if(r.isDir())return;const i=newFileInfo2(r);r!==t.fileInfo()&&(i.isLeafBundle()&&i.paths().dir()===s.dir()||i.shiftToResource()),await this.m.addFi(i)},a=this.fs.contentFs();for(const t of a)await this.fs.walkContent(t,r,{walkFn:n},{info:e,dirEntries:i})}}}}),init_entity=__esm({"internal/domain/content/entity/index.ts"(){init_content2(),init_pagemap(),init_pagetrees(),init_pagecollector()}}),init_content2=__esm({"internal/domain/content/entity/content.ts"(){init_entity(),init_doctree(),init_fileinfo2(),init_log(),init_paths(),log26=getDomainLogger("content",{component:"content"}),Content2=class{fs;converter;pageMap;translator;pageCollected=!1;constructor(e,t,r,i){this.fs=e,this.converter=t,this.pageMap=r,this.translator=i}setTemplateSvc(e){this.pageMap.pageBuilder.templateSvc=e}async renderString(e,...t){if(t.length<1||t.length>2)throw new Error("RenderString want 1 or 2 arguments");let r=1;if(1!==t.length){const e=t[0];if("object"!=typeof e||null===e)throw new Error("first argument must be a map");throw new Error("RenderString not implemented yet")}r=0;const i=t[0],s=String(i);return newFileInfo2(this.fs.newFileMetaInfoWithContent(s)),s}async collectPages(){if(this.pageCollected)log26.info("Pages have already been collected, skipping.");else try{await this.process(),await this.assemble(),this.pageCollected=!0}catch(e){throw new Error(`process/assemble: ${e}`)}}async process(){try{const e=new PagesCollector(this.pageMap,this.fs);await e.collect()}catch(e){throw e}}async assemble(){try{await this.pageMap.assemble()}catch(e){throw e}}async getPageSources(e){let t=e.paths().base();return"/"===t&&(t=""),await this.pageMap.getResourcesForPage(e)}async globalPages(e){return await this.pageMap.getPagesInSection(e,new PageMapQueryPagesInSectionImpl("","global",!0,!0,0,pagePredicates.shouldListGlobal))}async globalRegularPages(){return await this.pageMap.getPagesInSection(0,new PageMapQueryPagesInSectionImpl("","global",!0,!0,0,e=>pagePredicates.shouldListGlobal(e)&&pagePredicates.kindPage(e)))}async walkPages(e,t){const r=this.pageMap.treePages.shape(0,e),i=new NodeShiftTreeWalker({tree:r,handle:async(e,r,i)=>{const[s,n]=r.getPage();if(!n)return[!1,null];try{await t(s)}catch(e){return[!1,e instanceof Error?e:new Error(String(e))]}return[!1,null]}});try{await i.walk()}catch(t){throw log26.error(`WalkPages failed for langIndex ${e}:`,t),t}}async walkTaxonomies(e,t){try{const r=this.pageMap.treePages.shape(0,e),i=this.pageMap.pageBuilder.taxonomy;for(const s of i.views){const n=i.pluralTreeKey(s.plural()),a=new NodeShiftTreeWalker({tree:r,prefix:addTrailingSlash(n),lockType:1,handle:async(r,i,n)=>{const[a,o]=i.getPage();if(!o)return[!1,null];if("term"===a.kind()){const i=a;if(!i.term)return[!0,new Error("term is empty")];const n=i.term.toLowerCase();try{const a=this.pageMap.treeTaxonomyEntries.shape(0,e);return await a.walkPrefix(1,addTrailingSlash(r),(e,r)=>{const[a,o]=r.getPage();return o?(t(s.plural(),n,{weight:()=>r.term.Weight(),ordinal:()=>r.term.Ordinal(),page:()=>a,owner:()=>i}).catch(e=>{log26.error("Error in taxonomy walker:",e)}),[!1,null]):[!1,null]}),[!1,null]}catch(e){return[!0,e]}}return[!1,null]}});await a.walk()}}catch(e){throw e}}getPageFromPath(e,t){try{const r=PathDomain.createProcessor().parse(PATH_CONSTANTS.COMPONENT_FOLDER_CONTENT,t);let i=this.pageMap.treePages.shape(0,e).get(r.base());if(i){const[e,t]=i.getPage();if(t)return e}return null}catch(e){return log26.error(`❌ Content.getPageFromPath error for path "${t}":`,e),null}}getPageFromFile(e,t){try{let r=this.pageMap.treePages.shape(0,e).get(t.paths().base());if(r){const[e,t]=r.getPage();if(t)return e}return null}catch(e){return log26.error(`❌ Content.getPageFromPath error for path "${t.path()}":`,e),null}}async handleChangeFiles(e){const t=[];for(const[r,i]of e)try{await this.addOrUpdateFile(i,t)}catch(e){log26.error(`Failed to process file change for ${r}:`,e)}return t}async addOrUpdateFile(e,t){if(!e.isDir())try{const r=newFileInfo2(e),i=r.paths().base();i&&t.push(i),await this.pageMap.addFi(r);const s=this.getPageFromFile(0,r);s&&s.pageIdentity&&s.pageIdentity().markStale()}catch(t){throw log26.error(`Failed to add/update file in PageMap: ${e.fileName()}`,t),t}}translate(e,t){return this.translator?this.translator.translate(e,t):(log26.warn("Translator not initialized, returning fallback translation"),`[i18n] ${t}`)}getAvailableLanguages(){return this.translator?this.translator.getAvailableLanguages():[]}hasLanguageSupport(e){return!!this.translator&&this.translator.hasLanguage(e)}}}}),init_converter=__esm({"internal/domain/content/entity/converter.ts"(){MDConverter=class{md;constructor(e){this.md=e}async convert(e,t){return this.md.render(t,e)}async parseContent(e){return this.md.parseContent(e)}async parseAndRenderContent(e,t){return this.md.parseAndRenderContent(e,t)}async prepareRender(e){return this.md.prepareRender(e)}}}});function newContent(e){return new Content3(e)}var log27,PAGE_HOME_BASE,Section,STANDALONE_PAGE_404_BASE,STANDALONE_PAGE_SITEMAP_BASE,Standalone,Output,PaginatorImpl,PagerImpl,PaginatorManagerImpl,Scratch,init_pagecontent=__esm({"internal/domain/content/entity/pagecontent.ts"(){Content3=class{rawSource;frontMatter;renderedContent="";summary="";wordCount=0;readingTime=0;toc;lazyRendered=!0;lazyRender;constructor(e){this.rawSource=e}updateWithContentResult(e){e.frontMatter&&(this.frontMatter=e.frontMatter),this.renderedContent=e.renderedContent||"",this.summary=e.summary,this.wordCount=e.wordCount||0,this.readingTime=e.readingTime||0}getRawSource(){return this.rawSource}async RenderedContent(){return await this.render(),this.renderedContent}async Summary(){return await this.render(),this.summary}async WordCount(){return await this.render(),this.wordCount}async ReadingTime(){return await this.render(),this.readingTime}async render(){return this.lazyRendered&&this.lazyRender&&(await this.lazyRender(),this.lazyRendered=!1),Promise.resolve()}isEmpty(){return!this.rawSource||0===this.rawSource.length}}}}),init_section=__esm({"internal/domain/content/entity/section.ts"(){init_pagetrees(),init_fileinfo2(),init_pagesource(),init_kind(),init_doctree(),init_log(),log27=getDomainLogger("content",{component:"section"}),PAGE_HOME_BASE="/",Section=class{home;seen;fsSvc;constructor(e){this.home=null,this.seen={},this.fsSvc=e}isHome(e){return""===e}isSectionExist(e){return!(""!==e&&!this.seen[e]&&(this.seen[e]=!0,1))}async assemble(e,t,r){this.seen={};const i=new NodeShiftTreeWalker({tree:e,lockType:2,handle:async(e,s,n)=>{if(!s)throw new Error("n is null");const[a,o]=s.getPage();if(!o)return[!1,null];if(this.isHome(e))return this.home=a,[!1,null];const l=a.kind();if(l!==getKindMain("page")&&l!==getKindMain("section"))return[!1,null];const c=a.paths().sections();for(const e of c)if(!this.isSectionExist(e))try{const s=newPageSource(newFileInfo2(this.fsSvc.newFileMetaInfo("/"+e+"/_index.md"))),n=s.paths().base();if(!i.tree.get(n)){const e=await t.withSource(s).withLangIdx(r).kindBuild();i.tree.insertIntoValuesDimension(n,newPageTreesNode2(e))}}catch(e){return[!1,e]}return[!1,null]}});try{await i.walk()}catch(e){throw log27.error("Error walking pages:",e),e}if(!this.home&&(await this.createHome(t),this.home)){const t=this.home;e.insertWithLock(t.paths().base(),newPageTreesNode2(t))}}async createHome(e){const t=newPageSource(newFileInfo2(this.fsSvc.newFileMetaInfo("/_index.md"))),r=await e.withSource(t).kindBuild();this.home=r}}}}),init_standalone=__esm({"internal/domain/content/entity/standalone.ts"(){init_pagetrees(),init_fileinfo2(),init_pagesource(),STANDALONE_PAGE_404_BASE="404",STANDALONE_PAGE_SITEMAP_BASE="_sitemap",Standalone=class{fsSvc;constructor(e){this.fsSvc=e}async assemble(e,t){const r="/"+STANDALONE_PAGE_404_BASE,i=await this.addStandalone(r,t);e.insertIntoValuesDimension(r,newPageTreesNode2(i));const s="/"+STANDALONE_PAGE_SITEMAP_BASE,n=await this.addStandalone(s,t);e.insertIntoValuesDimension(s,newPageTreesNode2(n))}async addStandalone(e,t){const r=newPageSource(newFileInfo2(this.fsSvc.newFileMetaInfo(e+".md")));return await t.withSource(r).kindBuild()}}}}),init_pageoutput=__esm({"internal/domain/content/entity/pageoutput.ts"(){init_content3(),Output=class{source;pageKind;baseName;target=null;constructor(e,t){this.source=e,this.pageKind=t,this.baseName="",this.setBasename(),this.buildTarget()}setBasename(){switch(this.pageKind){case getKindMain("404"):this.baseName="404";break;case getKindMain("sitemap"):this.baseName="sitemap";break;default:this.baseName=this.source.paths().baseNameNoIdentifier()||"index"}}buildTarget(){let e="",t="";const r="index";switch(this.pageKind){case getKindMain("home"):e=`${r}.html`,t="";break;case getKindMain("page"):const i=this.source.paths().containerDir();e=i&&"/"!==i?`${i}/${this.baseName}.html`:`/${this.baseName}.html`,t=i||"";break;case getKindMain("section"):case getKindMain("taxonomy"):case getKindMain("term"):const s=this.source.paths().dir();e=s?`${s}/${r}.html`:`${r}.html`,t=s||"";break;case getKindMain("404"):const n=this.source.paths().dir();e=n?`${n}/${this.baseName}.html`:`${this.baseName}.html`,t=n||"";break;case getKindMain("sitemap"):const a=this.source.paths().dir();e=a?`${a}/${this.baseName}.xml`:`${this.baseName}.xml`,t=a||"";break;default:e=`${r}.html`,t=""}this.target={prefix:this.source.identity.pageLanguage(),filePath:e,subResourceBaseTarget:t}}createBasicResult(){return{bytes:()=>new Uint8Array,headers:()=>[],tableOfContents:()=>({toHTML:(e,t,r)=>""})}}output(e){return{targetFileBase:()=>{if(!this.target)return"index.html";const e=this.target.filePath,t=e.lastIndexOf("/");return t>=0?e.substring(t+1):e},targetFilePath:()=>this.target.filePath,targetSubResourceDir:()=>this.target.subResourceBaseTarget,targetPrefix:()=>this.target.prefix,content:async()=>e.content?e.content.RenderedContent():"",summary:async()=>e.content?e.content.Summary():"",tableOfContents:()=>e.content&&e.content.toc?e.content.toc.toHTML(1,6,!1):"",result:()=>this.createBasicResult(),readingTime:async()=>e.content?e.content.ReadingTime():0,wordCount:async()=>e.content?e.content.WordCount():0}}}}}),init_paginator=__esm({"internal/domain/content/entity/paginator.ts"(){init_log(),getDomainLogger("content",{component:"paginator"}),PaginatorImpl=class{paginatedElements;_pagers;base;total;size;constructor(e,t,r,i){if(this.paginatedElements=e,this.base=i,this.total=t,this.size=r,this._pagers=[],e.length>0)for(let t=0;t<e.length;t++)this._pagers.push(new PagerImpl(t+1,this));else this._pagers.push(new PagerImpl(1,this))}totalPages(){return this.paginatedElements.length}pagers(){return[...this._pagers]}getElement(e){return 0===this.paginatedElements.length?[]:this.paginatedElements[e-1]||[]}getBase(){return this.base}getPagers(){return this._pagers}getAllPages(){const e=[];for(const t of this.paginatedElements)e.push(...t);return e}},PagerImpl=class{number;paginator;constructor(e,t){this.number=e,this.paginator=t}pageNumber(){return this.number}totalPages(){return this.paginator.totalPages()}url(){const e=this.pageNumber();if(e>1){const t=`/page/${e}/`;return this.pathJoin(this.paginator.getBase(),t)}return this.paginator.getBase()}pages(){return this.element()}allPages(){return this.paginator.getAllPages()}pagers(){return this.paginator.pagers()}first(){return this.paginator.getPagers()[0]}last(){const e=this.paginator.getPagers();return e[e.length-1]}hasPrev(){return this.pageNumber()>1}prev(){return this.hasPrev()?this.paginator.getPagers()[this.pageNumber()-2]:null}hasNext(){return this.pageNumber()<this.paginator.totalPages()}next(){return this.hasNext()?this.paginator.getPagers()[this.pageNumber()]:null}element(){return this.paginator.getElement(this.pageNumber())}pathJoin(e,t){return e.endsWith("/")&&(e=e.slice(0,-1)),t.startsWith("/")||(t="/"+t),e+t}},PaginatorManagerImpl=class{currentPager=null;initialized=!1;svc;page;constructor(e,t){this.svc=e,this.page=t}async current(){return this.initialized||await this.initializePaginator(),this.currentPager?this.currentPager:new PaginatorImpl([],0,10,this.page.paths().base()).pagers()[0]}setCurrent(e){this.currentPager=e}async paginate(e){if(!this.initialized){const t=this.svc.pageSize();let r;r=Array.isArray(e)&&e.length>0&&"key"in e[0]?this.newPaginatorFromPageGroups(e,t,this.page.paths().base()):this.newPaginatorFromPages(e,t,this.page.paths().base()),this.currentPager=r.pagers()[0],this.initialized=!0}return this.currentPager||this.current()}async paginator(){return this.initialized||await this.initializePaginator(),this.currentPager||this.current()}async initializePaginator(){try{const e=this.svc.pageSize();let t=[];switch(this.page.kind()){case"home":t=await this.svc.globalRegularPages();break;case"term":case"taxonomy":const e=await this.page.pages();t=e?.length?Array.from({length:e.length},(t,r)=>e[r]):[];break;default:const r=await this.page.regularPages();t=r&&r.length>0?Array.from({length:r.length},(e,t)=>r[t]):await this.svc.globalRegularPages()}const r=this.page.paths().base(),i=this.newPaginatorFromPages(t,e,r);this.currentPager=i.pagers()[0],this.initialized=!0}catch(e){const t=this.page.paths().base(),r=new PaginatorImpl([],0,10,t);this.currentPager=r.pagers()[0],this.initialized=!0}}newPaginatorFromPages(e,t,r){if(t<=0)throw new Error("paginator size must be positive");const i=this.splitPages(e,t);return new PaginatorImpl(i,e.length,t,r)}newPaginatorFromPageGroups(e,t,r){if(t<=0)throw new Error("paginator size must be positive");const i=[];if(e&&e.length>0)for(let t=0;t<e.length;t++){const r=e[t];if(r&&r.pages){const e=r.pages();if(e)for(let t=0;t<e.length;t++)i.push(e[t])}}const s=this.splitPages(i,t);return new PaginatorImpl(s,i.length,t,r)}splitPages(e,t){const r=[];for(let i=0;i<e.length;i+=t){const s=Math.min(i+t,e.length);r.push(e.slice(i,s))}return r}}}}),init_scratch=__esm({"pkg/maps/scratch.ts"(){Scratch=class{values;constructor(){this.values=new Map}add(e,t){const r=this.values.get(e);let i;return i=void 0!==r?Array.isArray(r)?[...r,t]:"number"==typeof r&&"number"==typeof t||"string"==typeof r&&"string"==typeof t?r+t:t:t,this.values.set(e,i),""}Add(e,t){return this.add(e,t)}set(e,t){return this.values.set(e,t),""}Set(e,t){return this.set(e,t)}delete(e){return this.values.delete(e),""}get(e){return this.values.get(e)}Get(e){return this.get(e)}getValues(){return this.values}setInMap(e,t,r){let i=this.values.get(e);return i&&"object"==typeof i||(i={},this.values.set(e,i)),i[t]=r,""}}}});function dir(e){const t=e.lastIndexOf("/");if(-1===t)return"";let r=e.slice(0,t+1);return r.length>1&&r.endsWith("/")&&(r=r.slice(0,-1)),r}var PageImpl,TaxonomyPageImpl,TermPageImpl,init_paths2=__esm({"pkg/paths/index.ts"(){}});import path18 from"path";var Meta,Layout,ShortcodeWithPage,BASE_FILE_BASE,BASE_DEFAULT,PARTIALS_PREFIX,TemplateError,BaseOf,init_page=__esm({"internal/domain/content/entity/page.ts"(){init_content3(),init_pageoutput(),init_paginator(),init_scratch(),init_pagemap(),init_paths2(),init_doctree(),init_sort(),init_log(),getDomainLogger("content",{component:"page"}),PageImpl=class{source;content;meta;layout;pagerManager;title_;description_="";kind_;pageMap;output_=null;store_=null;constructor(e,t,r,i,s="",n="page",a=null){this.source=e,this.content=t,this.meta=r,this.layout=i,this.title_=s,this.kind_=n,this.pageMap=a,this.pagerManager=new PaginatorManagerImpl({pageSize:()=>10,globalRegularPages:async()=>[]},this)}rawContent(){if(!this.content)return"";const e=this.content.getRawSource();return(new TextDecoder).decode(e)}pageIdentity(){return this.source.identity}pageFile(){return this.source.file}staleVersions(){return[]}section(){return this.source.file.section()}paths(){return this.source.file.paths()}path(){return this.source.file.paths().path()}slug(){return this.pathToSlug(this.path())}pathToSlug(e){let t=e.replace(/^\//,"");return t=t.replace(/\.md$/,""),t.endsWith("/index")&&(t=t.replace(/\/index$/,"")),"index"!==t&&""!==t||(t="index"),t.endsWith("/_index")&&(t=t.replace(/\/_index$/,"")),t}posOffset(e){return this.source.posOffset(e)}description(){return this.description_}get Description(){return this.description()}StaticURL(e){return/^(https?:)?\/\//.test(e)?e:((e=(e=path18.normalize(e)).replace(/\\/g,"/")).startsWith("/")&&(e=e.slice(1)),`${this.meta.pageBaseUrl().replace(/\/+$/,"")}/${e}`)}params(){return this.meta.params()}get Params(){return this.params()}store(){return this.store_||(this.store_=new Scratch),this.store_}get Store(){return this.store()}scratch(){return this.store()}get Scratch(){return this.scratch()}pageBaseUrl(){return this.meta.pageBaseUrl()}pageWeight(){return this.meta.pageWeight()}pageDate(){return this.meta.pageDate()}publishDate(){return this.meta.publishDate()}async relatedKeywords(e){return this.meta.relatedKeywords(e)}shouldList(e){return this.meta.shouldList(e)}shouldListAny(){return this.meta.shouldListAny()}noLink(){return this.meta.noLink()}organization(){return this.meta.organization()}author(){return this.meta.author()}menu(){return this.meta.menu()}async current(){return await this.pagerManager.current()}setCurrent(e){this.pagerManager.setCurrent(e)}async paginator(){return await this.pagerManager.paginator()}async paginate(e){return this.pagerManager.paginate(e)}file(){return this.source.file}get Type(){return this.file().type()}name(){return this.source.file.baseFileName()}title(){return this.title_}get Title(){return this.title()}kind(){return this.kind_}isHome(){return this.kind()===getKindMain("home")}isPage(){return this.kind()===getKindMain("page")}isSection(){return this.kind()===getKindMain("section")}isAncestor(e){return e.path()!==this.path()&&e.paths().base().startsWith(this.paths().base())}eq(e){return this.pageIdentity().identifierBase()===e.pageIdentity().identifierBase()}layouts(){switch(this.kind_){case getKindMain("home"):return this.source.file.isBranchBundle()?this.layout.homeList():this.layout.home();case getKindMain("page"):return this.layout.page(this.source.file.section(),this.source.file.baseFileName());case getKindMain("section"):return this.layout.section(this.source.file.section());case getKindMain("taxonomy"):return this.layout.taxonomy();case getKindMain("term"):return this.layout.term();case getKindMain("404"):return this.layout.standalone404();case getKindMain("sitemap"):return this.layout.standaloneSitemap();default:return[]}}output(){return this.output_||(this.output_=new Output(this.source,this.kind())),this.output_.output(this)}get TargetPath(){return this.output().targetFilePath()}get Summary(){return this.output().summary()}truncated(){return!0}parent(){if(this.isHome())return null;let e=this.paths().containerDir();if(""===e)return null;for(;;){const t=this.pageMap?.treePages.longestPrefix(e,!0);if(!t)return null;const[r,i]=t;if(!i)return null;const[s,n]=i.getPage();if(!s)return null;if(this.isBundled())return n?s:null;if(!s.isPage())return n?s:null;e=dir(e)}}async Pages(){return await this.pages()}async pages(){const e=this.pageIdentity().pageLanguageIndex();switch(this.kind()){case PageKind.PAGE:case PageKind.SECTION:case PageKind.HOME:return await this.pageMap.getPagesInSection(e,new PageMapQueryPagesInSectionImpl(this.paths().base(),"page-section",!1,!1,e,e=>pagePredicates.shouldListLocal(e)&&(pagePredicates.kindPage(e)||pagePredicates.kindSection(e))));case PageKind.TERM:return await this.pageMap.getPagesWithTerm(e,new PageMapQueryPagesBelowPathImpl(this.paths().base(),"term"));case PageKind.TAXONOMY:return await this.pageMap.getPagesInSection(e,new PageMapQueryPagesInSectionImpl(this.paths().base(),"term",!0,!1,e,e=>pagePredicates.shouldListLocal(e)&&pagePredicates.kindTerm(e)));default:return Promise.resolve([])}}prevInSection(){return null}nextInSection(){return null}sections(e){return[]}async regularPages(){const e=this.pageIdentity().pageLanguageIndex();switch(this.kind()){case PageKind.PAGE:case PageKind.SECTION:case PageKind.HOME:case PageKind.TAXONOMY:return this.pageMap?await this.pageMap.getPagesInSection(e,new PageMapQueryPagesInSectionImpl(this.paths().base(),"",!1,!1,e,e=>pagePredicates.shouldListLocal(e)&&pagePredicates.kindPage(e))):[];case PageKind.TERM:return this.pageMap?await this.pageMap.getPagesWithTerm(e,new PageMapQueryPagesBelowPathImpl(this.paths().base(),"",e=>pagePredicates.shouldListLocal(e)&&pagePredicates.kindPage(e))):[];default:return[]}}regularPagesRecursive(){return[]}async terms(e,t){return this.pageMap?this.pageMap?.getTermsForPageInTaxonomy(e,this.paths().base(),t):null}async isTranslated(){return(await this.translations()).length>0}async translations(){const e=this.path()+"/"+this.pageIdentity().pageLanguage()+"/translations";if(!this.pageMap)return[];try{return await this.pageMap.getOrCreatePagesFromCacheSync(null,e,async e=>{const t=await this.allTranslations(),r=[];for(let e=0;e<t.length;e++){const i=t.at(e);i&&!i.eq(this)&&r.push(i)}return r})}catch(e){throw e}}async allTranslations(){const e=this.path()+"/translations-all";if(!this.pageMap)return[];try{return await this.pageMap.getOrCreatePagesFromCacheSync(null,e,async e=>{const t=[];var r;return this.pageMap.treePages.forEachInDimension(this.paths().base(),dimensionFlag.index(1),e=>{if(null!=e){const r=e.getPages();t.push(...r)}return!1}),r=t,pageBy(language).sort(r),t})}catch(e){throw e}}isBundled(){return this.source.file.isBundle()}},TaxonomyPageImpl=class extends PageImpl{singular;constructor(e,t,r,i,s,n="",a="taxonomy",o=null){super(e,t,r,i,n,a,o),this.singular=s}params(){const e=super.params();return e.Singular=this.singular,e}},TermPageImpl=class extends TaxonomyPageImpl{term;constructor(e,t,r,i,s,n,a="",o="term",l=null){super(e,t,r,i,s,a,o,l),this.term=n}params(){const e=super.params();return e.Term=this.term,e}}}}),init_pagemeta=__esm({"internal/domain/content/entity/pagemeta.ts"(){Meta=class{baseURL;list;parameters;weight;date;org;authorInfo;menuConfig;constructor(e,t="always",r={},i=999,s=new Date,n,a,o){this.baseURL=e,this.list=t,this.parameters=r,this.weight=i,this.date=s,this.org=n,this.authorInfo=a,this.menuConfig=o}description(){return""}params(){return this.parameters}pageBaseUrl(){return this.baseURL}pageWeight(){return this.weight}pageDate(){return this.date}publishDate(){return this.pageDate()}async relatedKeywords(e){return[]}shouldList(e){switch(this.list){case"always":default:return!0;case"never":return!1;case"local":return!e}}shouldListAny(){return this.shouldList(!0)||this.shouldList(!1)}noLink(){return!1}organization(){return this.org}author(){return this.authorInfo}menu(){return this.menuConfig}}}}),init_pagelayout=__esm({"internal/domain/content/entity/pagelayout.ts"(){Layout=class{home(){return["index.html","_default/index.html","_default/single.html"]}homeList(){return["index.html","_default/index.html","_default/list.html"]}section(e){return[`${e}/section.html`,`${e}/list.html`,"_default/section.html","_default/list.html","_default/index.html"]}page(e,t){const r=e?`${e}/${t}`:t,i=e?`${e}/single.html`:"single.html",s=[];return"index"!==r&&s.push(`${r}.html`),s.push(i),"index"!==t&&s.push(`_default/${t}.html`),s.push("_default/single.html"),s.push("index.html"),s.push("_default/index.html"),s}taxonomy(){return["taxonomy/taxonomy.html","taxonomy/list.html","_default/list.html","_default/taxonomy.html"]}term(){return["taxonomy/tag.html","term/term.html","taxonomy/list.html","_default/list.html","_default/term.html"]}standalone404(){return["404.html"]}standaloneSitemap(){return["sitemap.xml","_default/sitemap.xml"]}}}}),init_shortcode2=__esm({"internal/domain/content/entity/shortcode.ts"(){init_scratch(),ShortcodeWithPage=class{_params;_inner;_page;_parent;_name;_isNamedParams;_ordinal;_indentation;_innerDeindent=null;_posOffset;_pos=null;_scratch=null;constructor(e,t,r,i,s,n,a,o="",l=0){this._params=e,this._inner=t,this._page=r,this._parent=i,this._name=s,this._isNamedParams=n,this._ordinal=a,this._indentation=o,this._posOffset=l}get params(){return this._params}get Params(){return this._params}get IsNamedParams(){return this._isNamedParams}get inner(){return this._inner}get Inner(){return this._inner}get page(){return this._page}get Page(){return this._page}get parent(){return this._parent}get Parent(){return this._parent}get name(){return this._name}get isNamedParams(){return this._isNamedParams}get ordinal(){return this._ordinal}get Ordinal(){return this._ordinal}innerDeindent(){if(""===this._indentation)return this._inner;if(null===this._innerDeindent){const e=this._inner.split("\n");this._innerDeindent=e.map(e=>e.startsWith(this._indentation)?e.substring(this._indentation.length):e).join("\n")}return this._innerDeindent}get InnerDeindent(){return this.innerDeindent()}async position(){return this._pos||(this._pos=await this._page.posOffset(this._posOffset)),this._pos}scratch(){return this._scratch||(this._scratch=new Scratch),this._scratch}get(e){return this._params?Array.isArray(this._params)?"number"==typeof e?e>=this._params.length?"":this._params[e]:null:"object"==typeof this._params&&"string"==typeof e?this._params[e]||"":null:null}Get(e){return this.get(e)}}}}),init_type8=__esm({"internal/domain/template/type.ts"(){BASE_FILE_BASE="baseof",BASE_DEFAULT="_default",PARTIALS_PREFIX="partials/",new(TemplateError=class extends Error{constructor(e,t){super(e),this.code=t,this.name="TemplateError"}})("template not found","TEMPLATE_NOT_FOUND"),new TemplateError("template parse failed","PARSE_FAILED"),new TemplateError("template execute failed","EXECUTE_FAILED"),new TemplateError("invalid template","INVALID_TEMPLATE")}});import*as path19 from"path";var TemplateInfo2,init_baseof=__esm({"internal/domain/template/vo/baseof.ts"(){init_type8(),BaseOf=class{baseof=new Map;needsBaseof=new Map;getTemplateSearchOrder(e){const t=[];return t.push(`${BASE_DEFAULT}/baseof.html`),t}getBaseOf(e){return this.baseof.get(e)||null}getNeedsBaseOf(e){return this.needsBaseof.get(e)||null}addBaseOf(e,t){this.baseof.set(e,t)}addNeedsBaseOf(e,t){this.needsBaseof.set(e,t)}isBaseTemplatePath(e){return path19.basename(e).includes(BASE_FILE_BASE)}needsBaseOf(e,t){return!this.noBaseNeeded(e)&&this.needsBaseTemplate(t)}noBaseNeeded(e){return!!e.startsWith(PARTIALS_PREFIX)}needsBaseTemplate(e){let t=-1,r=!1;for(let i=0;i<e.length;)if(!r&&e.substring(i).startsWith("{{/*"))r=!0,i+=4;else if(!r&&e.substring(i).startsWith("{{- /*"))r=!0,i+=6;else if(r&&e.substring(i).startsWith("*/}}"))r=!1,i+=4;else if(r&&e.substring(i).startsWith("*/ -}}"))r=!1,i+=6;else{const s=e[i];if(!r){if(e.substring(i).startsWith("{{")){t=i;break}if(!/\s/.test(s))break}i++}return-1!==t&&/^{{-?\s*define/.test(e.substring(t))}getAllBaseOf(){return new Map(this.baseof)}getAllNeedsBaseOf(){return new Map(this.needsBaseof)}clear(){this.baseof.clear(),this.needsBaseof.clear()}getStats(){return{baseOfCount:this.baseof.size,needsBaseOfCount:this.needsBaseof.size}}}}});function removeLeadingBOM(e){for(let t=0;t<e.length;t++){const r=e[t];if(0===t&&"\ufeff"!==r)return e;if(t>0)return e.substring(t)}return e}function resolveTemplateType(e){return function(e){return e.includes("_shortcodes/")}(e)?1:e.includes("_partials/")?2:0}var BaseNamespace,RegularTemplateNamespace,PartialTemplateNamespace,ShortcodeTemplateNamespace,Executor,log31,ConcurrentCache,log32,Parser,init_info=__esm({"internal/domain/template/vo/info.ts"(){init_type8(),TemplateInfo2=class e{constructor(e,t,r){this.name=e,this.template=t,this.fi=r}identifierBase(){return this.name}errWithFileContext(e,t){const r=`${e}: ${t.message}`,i=new TemplateError(r,"TEMPLATE_FILE_ERROR");return Object.defineProperty(i,"fileName",{value:this.name,enumerable:!0}),Object.defineProperty(i,"fileContent",{value:this.template,enumerable:!0}),i}isZero(){return""===this.name}copy(){return new e(this.name,this.template,this.fi)}getCleanContent(){return removeLeadingBOM(this.template)}}}}),init_namespace=__esm({"internal/domain/template/vo/namespace.ts"(){init_type8(),init_log(),getDomainLogger("template",{component:"namespace"}),BaseNamespace=class{templates=new Map;mutex=new Set;addTemplate(e,t){this.withLock(()=>{this.templates.set(e,t)})}findTemplate(e){return this.withReadLock(()=>{if(this.templates.has(e))return this.templates.get(e)||null;if(!e.endsWith(".html")){const t=e+".html";if(this.templates.has(t))return this.templates.get(t)||null}for(const[t,r]of this.templates.entries())if(t.includes(e))return r;return null})}getTemplates(){return this.withReadLock(()=>new Map(this.templates))}hasTemplate(e){return this.withReadLock(()=>this.templates.has(e))}getTemplateNames(){return this.withReadLock(()=>Array.from(this.templates.keys()))}removeTemplate(e){return this.withLock(()=>this.templates.delete(e))}clear(){this.withLock(()=>{this.templates.clear()})}size(){return this.withReadLock(()=>this.templates.size)}getTemplatesByPattern(e){return this.withReadLock(()=>{const t=[];for(const[r,i]of this.templates)e.test(r)&&t.push(i);return t})}withLock(e){const t="write";for(;this.mutex.has(t););this.mutex.add(t);try{return e()}finally{this.mutex.delete(t)}}withReadLock(e){const t="read";this.mutex.add(t);try{return e()}finally{this.mutex.delete(t)}}},RegularTemplateNamespace=class extends BaseNamespace{lookup(e){const t=this.findTemplate(e);return t?t.template:null}findTemplateWithDependencies(e){return this.findTemplate(e)}getTemplatesNeedingBase(){return this.withReadLock(()=>Array.from(this.templates.values()).filter(e=>e.baseInfo))}},PartialTemplateNamespace=class extends BaseNamespace{lookup(e){const t=this.findTemplate(e);return t?t.template:null}addPartialTemplate(e,t){const r={...t,type:2};this.addTemplate(e,r)}},ShortcodeTemplateNamespace=class extends BaseNamespace{lookup(e){const t=this.findTemplate(e);return t?t.template:null}addShortcodeTemplate(e,t){const r={...t,type:1};this.addTemplate(e,r)}getShortcode(e){return this.lookup("_shortcodes/"+e)}hasShortcode(e){return this.hasTemplate(e)}getShortcodeNames(){return this.getTemplateNames()}}}}),init_executor=__esm({"internal/domain/template/entity/executor.ts"(){init_type8(),Executor=class{async execute(e,t){try{const[r,i]=await e.Execute(t);if(i)throw new TemplateError(`Template execution failed: ${i.message}`,"EXECUTION_FAILED");return r}catch(e){if(e instanceof TemplateError)throw e;const t=e instanceof Error?e.message:String(e);throw new TemplateError(`Template execution failed: ${t}`,"EXECUTION_FAILED")}}async executeWithTimeout(e,t,r){return new Promise(async(i,s)=>{const n=setTimeout(()=>{s(new TemplateError("Template execution timeout","EXECUTION_TIMEOUT"))},r);await this.execute(e,t).then(e=>{clearTimeout(n),i(e)}).catch(e=>{clearTimeout(n),s(e)})})}async executeSafely(e,t){try{return{result:await this.execute(e,t),error:null}}catch(e){if(e instanceof TemplateError)return{result:null,error:e};const t=e instanceof Error?e.message:String(e);return{result:null,error:new TemplateError(`Execution failed: ${t}`,"EXECUTION_ERROR")}}}async executeBatch(e){return(await Promise.allSettled(e.map(async({name:e,template:t,data:r})=>{try{return{name:e,result:await this.execute(t,r),error:null}}catch(t){return{name:e,result:null,error:t instanceof TemplateError?t:new TemplateError(`Batch execution failed: ${t.message}`,"BATCH_EXECUTION_FAILED")}}}))).map(e=>"fulfilled"===e.status?e.value:{name:"unknown",result:null,error:new TemplateError(`Batch execution failed: ${e.reason}`,"BATCH_EXECUTION_FAILED")})}async executeWithContext(e,t,r){if(r.signal?.aborted)throw new TemplateError("Template execution was cancelled","EXECUTION_CANCELLED");const i=new Promise((e,t)=>{r.signal&&r.signal.addEventListener("abort",()=>{t(new TemplateError("Template execution was cancelled","EXECUTION_CANCELLED"))})}),s=r.timeout?new Promise((e,t)=>{setTimeout(()=>{t(new TemplateError("Template execution timeout","EXECUTION_TIMEOUT"))},r.timeout)}):new Promise(()=>{});try{return await Promise.race([this.execute(e,t),i,s])}catch(e){if(e instanceof TemplateError)throw e;throw new TemplateError(`Context execution failed: ${e.message}`,"CONTEXT_EXECUTION_FAILED")}}}}}),init_cache2=__esm({"pkg/cahce/cache.ts"(){init_log(),log31=getDomainLogger("content",{component:"cache"}),new(ConcurrentCache=class{cache=new Map;pendingPromises=new Map;deletedKeys=new Set;constructor(){}get(e){return this.cache.get(e)}set(e,t){this.deletedKeys.has(e)||this.cache.set(e,t),this.pendingPromises.delete(e),this.deletedKeys.delete(e)}has(e){return this.cache.has(e)}isPending(e){return this.pendingPromises.has(e)}delete(e){return this.deletedKeys.add(e),this.pendingPromises.delete(e),this.cache.delete(e)}clear(){this.cache.clear(),this.pendingPromises.clear(),this.deletedKeys.clear()}size(){return this.cache.size}pendingCount(){return this.pendingPromises.size}async getOrCreate(e,t){const r=this.cache.get(e);if(void 0!==r)return r;const i=this.pendingPromises.get(e);return i?await i:this.createAndCache(e,t)}async createAndCache(e,t){const r=this.executeCreate(e,t);this.pendingPromises.set(e,r);try{const t=await r;return this.deletedKeys.has(e)?(this.deletedKeys.delete(e),this.pendingPromises.delete(e),t):(this.set(e,t),t)}catch(t){throw this.pendingPromises.delete(e),log31.error(`Failed to create value for key ${String(e)} : ${t}`),t}}async executeCreate(e,t){try{return await t(e)}catch(t){const r=t instanceof Error?t.message:String(t),i=new Error(`Cache creation failed for key ${String(e)}: ${r}`);throw t instanceof Error&&t.stack&&(i.stack=t.stack,i.originalError=t),i}}getStats(){return{size:this.cache.size,pendingCount:this.pendingPromises.size,keys:Array.from(this.cache.keys()),pendingKeys:Array.from(this.pendingPromises.keys())}}async preload(e){const t=e.filter(({key:e})=>!this.has(e)&&!this.isPending(e)).map(({key:e,create:t})=>this.getOrCreate(e,t));t.length>0&&await Promise.allSettled(t)}})}});import{New as New2}from"@mdfriday/text-template";import{NodeType}from"@mdfriday/text-template";var Lookup,log33,TemplateEngine,log34,engineDependentFunctions,PartialFunction,DefaultTemplateRegistry,init_parser=__esm({"internal/domain/template/entity/parser.ts"(){init_type8(),init_info(),init_log(),init_cache2(),log32=getDomainLogger("template",{component:"parser"}),Parser=class{prototypeText;prototypeTextClone;readyInit=!1;funcMap;parseOverlapCache;constructor(e=new Map){this.funcMap=e,this.prototypeText=New2(""),this.parseOverlapCache=new ConcurrentCache,this.funcMap.size>0&&this.prototypeText.Funcs(this.funcMap)}async markReady(){this.readyInit||(this.prototypeTextClone=this.prototypeText,this.readyInit=!0)}async parse(e){try{const t=New2(e.name);this.funcMap&&this.funcMap.size>0&&t.Funcs(this.funcMap);const[r,i]=t.Parse(e.template);if(i)throw new TemplateError(`Parse failed: ${i.message}`,"PARSE_FAILED");return{template:r,info:e,type:resolveTemplateType(e.name)}}catch(e){if(e instanceof TemplateError)throw e;const t=e instanceof Error?e.message:String(e);throw new TemplateError(`Parse failed: ${t}`,"PARSE_FAILED")}}async parseWithLock(e,t){try{this.prototypeTextClone||await this.markReady();const r=New2(e);this.funcMap&&this.funcMap.size>0&&r.Funcs(this.funcMap);const[i,s]=r.Parse(t);if(s)throw new TemplateError(`Parse with lock failed: ${s.message}`,"PARSE_LOCK_FAILED");return i}catch(e){if(e instanceof TemplateError)throw e;const t=e instanceof Error?e.message:String(e);throw new TemplateError(`Parse with lock failed: ${t}`,"PARSE_LOCK_FAILED")}}async parseOverlap(e,t,r){const i=`${e.name}::${t.name||"empty"}`;return this.parseOverlapCache.getOrCreate(i,async()=>{try{const i={template:await this.applyBaseTemplate(e,t,r),info:e,type:resolveTemplateType(e.name)};return t.isZero&&!t.name||(i.baseInfo=t),[i,!0,null]}catch(e){const t=e instanceof TemplateError?e:new TemplateError(`Parse overlap failed: ${e.message}`,"PARSE_OVERLAP_FAILED");return log32.error(`Failed to parse template overlap for key: ${i}: ${t.message}`),[null,!1,t]}})}async applyBaseTemplate(e,t,r){try{const i=New2(e.name);if(this.funcMap&&this.funcMap.size>0&&i.Funcs(this.funcMap),!t.isZero||t.name){const[e,r]=i.Parse(t.template);if(r)throw new TemplateError(`Base template parse failed: ${r.message}`,"BASE_PARSE_FAILED")}const[s,n]=i.Clone();if(n)throw new TemplateError(`Template clone failed: ${n.message}`,"CLONE_FAILED");const[a,o]=s.Parse(e.template);if(o)throw new TemplateError(`Overlay template parse failed: ${o.message}`,"OVERLAY_PARSE_FAILED");const l=await this.getDependencies(a,new Map,r);for(const[t,r]of l)if(t!==e.name)try{if(r.template.Tree){const[,e]=a.AddParseTree(t,r.template.Tree);if(e)throw log32.error(`AddParseTree failed: ${e.message} with name ${t}`),new TemplateError(`AddParseTree failed: ${e.message}`,"ADD_PARSE_TREE_FAILED")}}catch(r){throw log32.error(`Error adding dependency ${t} to template ${e.name}:`,r),new TemplateError(`Failed to add dependency ${t}: ${r.message}`,"DEPENDENCY_ADD_FAILED")}return a}catch(e){if(e instanceof TemplateError)throw e;const t=e instanceof Error?e.message:String(e);throw new TemplateError(`Apply base template failed: ${t}`,"APPLY_BASE_FAILED")}}async getDependencies(e,t,r){const i=new Map;if(t.has(e.Name()))return i;t.set(e.Name(),e);try{const s=new Set,n=e=>{if(!e)return;const t=e.Type();if(t===NodeType.NodeTemplate){const t=e.Name;t&&s.add(t)}else if(t===NodeType.NodeList){const t=e;if(t.Nodes)for(const e of t.Nodes)n(e)}if(t===NodeType.NodeAction){const t=e;t.Pipe&&n(t.Pipe)}else if(t===NodeType.NodePipe){const t=e;if(t.Cmds)for(const e of t.Cmds)n(e)}else if(t===NodeType.NodeCommand){const t=e;if(t.Args)for(const e of t.Args)n(e)}else if(t===NodeType.NodeIf||t===NodeType.NodeRange||t===NodeType.NodeWith){const t=e;t.Pipe&&n(t.Pipe),t.List&&n(t.List),t.ElseList&&n(t.ElseList)}};e.Tree&&e.Tree.Root&&n(e.Tree.Root);for(const e of s){const s=r(e);if(s&&(i.set(e,s),!t.has(s.template.Name()))){const e=await this.getDependencies(s.template,t,r);for(const[t,r]of e)i.has(t)||i.set(t,r)}}}catch(t){log32.error(`Error getting dependencies for template ${e.Name()}:`,t)}return i}setFuncMap(e){this.funcMap=new Map([...this.funcMap,...e]),this.funcMap.size>0&&this.prototypeText.Funcs(this.funcMap)}getFuncMap(){return new Map(this.funcMap)}async parseMultiple(e){const t=await Promise.allSettled(e.map(e=>this.parse(e))),r=[],i=[];for(const e of t)"fulfilled"===e.status?r.push(e.value):i.push(e.reason);if(i.length>0)throw new TemplateError(`Failed to parse ${i.length} templates: ${i.map(e=>e.message).join(", ")}`,"MULTIPLE_PARSE_FAILED");return r}clearCache(){this.parseOverlapCache.clear()}getCacheStats(){return this.parseOverlapCache.getStats()}}}}),init_lookup=__esm({"internal/domain/template/entity/lookup.ts"(){init_baseof(),Lookup=class{baseOf;funcsv;constructor(e,t){if(this.baseOf=e||new BaseOf,this.funcsv=new Map,t)for(const[e,r]of t)this.funcsv.set(e,r)}findNoDependence(e,t){try{const r=t.lookup(e);return r?[r,!0,null]:[null,!1,null]}catch(e){return[null,!1,e]}}findTemplate(e,t){try{const r=t.lookup(e);if(r)return[r,!0,null];const i=t.findTemplateWithDependencies(e);return i&&i.baseInfo?[i.template,!0,null]:[null,!1,null]}catch(e){return[null,!1,e]}}findPartial(e,t){try{const r=t.lookup(e);return r?[r,!0,null]:[null,!1,null]}catch(e){return[null,!1,e]}}findShortcode(e,t){try{const r=t.getShortcode(e);return r?[r,!0,null]:[null,!1,null]}catch(e){return[null,!1,e]}}findDependentInfo(e){const t=this.baseOf.getNeedsBaseOf(e);if(!t)return[null,null,!1];let r=null,i=!1;for(const t of this.baseOf.getTemplateSearchOrder(e))if(r=this.baseOf.getBaseOf(t),r){i=!0;break}return[t,r,i]}getFunc(e){return this.funcsv.get(e)}setFunc(e,t){this.funcsv.set(e,t)}setFuncMap(e){this.funcsv.clear();for(const[t,r]of e)this.funcsv.set(t,r)}getFuncMap(){return new Map(this.funcsv)}newTemplateLookup(e){return t=>e.findTemplate(t)}getBaseOf(){return this.baseOf}setBaseOf(e){this.baseOf=e}hasDependencies(e){const[t,r,i]=this.findDependentInfo(e);return i&&(null!==t||null!==r)}getAllFunctions(){return Array.from(this.funcsv.keys())}clearFunctions(){this.funcsv.clear()}getStats(){const e=this.baseOf.getStats();return{functionCount:this.funcsv.size,baseTemplateCount:e.baseOfCount,dependentTemplateCount:e.needsBaseOfCount}}}}}),init_template=__esm({"internal/domain/template/entity/template.ts"(){init_type8(),init_info(),init_info(),init_log(),init_paths(),log33=getDomainLogger("template",{component:"template-engine"}),TemplateEngine=class{executor;lookup;parser;templateNamespace;partialNamespace;shortcodeNamespace;fs;constructor(e,t,r,i,s,n,a){this.executor=e,this.lookup=t,this.parser=r,this.templateNamespace=i,this.partialNamespace=s,this.shortcodeNamespace=n,this.fs=a}async markReady(){try{await this.parser.markReady()}catch(e){throw new TemplateError(`Failed to mark template engine ready: ${e.message}`,"TEMPLATE_ENGINE_READY_FAILED")}}async getTemplate(e){const[t,r,i]=this.lookup.findTemplate(e,this.templateNamespace);if(i)return[null,!1,i];if(r&&t)return[t,!0,null];const[s,n,a]=this.lookup.findDependentInfo(e);if(a&&s)try{const[e,t,r]=await this.parser.parseOverlap(s,n||s,this.lookup.newTemplateLookup(this.templateNamespace));if(r)return[null,!1,r];if(t&&e)return[e.template,!0,null]}catch(e){return[null,!1,e]}return[null,!1,null]}async getPartial(e){let t=e.startsWith(PARTIALS_PREFIX)?e:`${PARTIALS_PREFIX}${e}`;return t=e.endsWith(".html")?t:`${t}.html`,this.lookup.findPartial(t,this.partialNamespace)}async getShortcode(e){return this.lookup.findShortcode(e,this.shortcodeNamespace)}async get(e){switch(resolveTemplateType(e)){case 1:return this.getShortcode(e);case 2:return this.getPartial(e);default:return this.getTemplate(e)}}async findFirst(e){if(!e||0===e.length)return[null,null,!1,null];for(const t of e)try{const[e,r,i]=await this.get(t);if(i)continue;if(r&&e)return[e,t,!0,null]}catch(e){log33.error("Error finding template:",e)}return[null,null,!1,null]}hasShortcode(e){return this.shortcodeNamespace.hasShortcode(e)}getShortcodeNames(){return this.shortcodeNamespace.getShortcodeNames()}getShortcodeCount(){return this.getShortcodeNames().length}async loadTemplates(){const e=async(e,t)=>{if(t.isDir())return;const r=e.startsWith(PATH_CONSTANTS.SYSTEM_PATH_SEPARATOR)?e.substring(1):e,i=PATH_CONSTANTS.normalizePath(r);try{await this.addTemplateFileInfo(i,t)}catch(e){log33.error("Error adding template:",new TemplateError(`Failed to add template ${i}: ${e.message}`,"LOAD_TEMPLATE_FAILED"))}};try{await this.fs.walk("",{walkFn:e},{})}catch(e){if(!e.message?.includes("ENOENT")&&!e.message?.includes("no such file"))throw e}}async addTemplateFileInfo(e,t){try{const r=await async function(e,t){let r=null;try{r=await t.open();const i=await r.stat(),s=new Uint8Array(i.size()),n=await r.read(s),a=removeLeadingBOM(new TextDecoder("utf-8").decode(n.buffer));return new TemplateInfo2(e,a,t)}catch(r){throw new TemplateInfo2(e,"",t).errWithFileContext("failed to load template",r)}finally{if(r)try{await r.close()}catch(e){console.warn(`Failed to close template file: ${e}`)}}}(e,t);await this.addTemplate(r.name,r)}catch(t){throw new TemplateError(`Failed to load template info for ${e}: ${t.message}`,"LOAD_TEMPLATE_INFO_FAILED")}}async addTemplate(e,t){try{if(this.lookup.getBaseOf().isBaseTemplatePath(e))return void this.lookup.getBaseOf().addBaseOf(e,t);if(this.lookup.getBaseOf().needsBaseOf(e,t.template))return void this.lookup.getBaseOf().addNeedsBaseOf(e,t);const r=resolveTemplateType(e),i=await this.parser.parse(t);switch(r){case 1:this.shortcodeNamespace.addShortcodeTemplate(e,i);break;case 2:this.partialNamespace.addPartialTemplate(e,i);break;default:this.templateNamespace.addTemplate(e,i)}}catch(t){throw new TemplateError(`Failed to add template ${e}: ${t.message}`,"ADD_TEMPLATE_FAILED")}}async execute(e,t){const[r,i,s]=await this.get(e);if(s)throw s;if(!i||!r)throw new TemplateError(`Template not found: ${e}`,"TEMPLATE_NOT_FOUND");return await this.executor.execute(r,t)}async executeRaw(e,t,r){const i=await this.parser.parseWithLock(e,t);if(!i)throw new TemplateError(`Raw Template parse error: ${e}`,"TEMPLATE_PARSE_ERROR");return await this.executor.execute(i,r)}async executeShortcode(e,t){const r=this.shortcodeNamespace.getShortcode(e);if(!r)throw new TemplateError(`Shortcode template '${e}' not found`,"SHORTCODE_NOT_FOUND");try{return await this.executor.execute(r,t)}catch(t){throw new TemplateError(`Error executing shortcode template '${e}': ${t.message}`,"SHORTCODE_EXECUTION_FAILED")}}async executeSafely(e,t){try{return{result:await this.execute(e,t),error:null}}catch(e){return e instanceof TemplateError?{result:null,error:e}:{result:null,error:new TemplateError(`Execute safely failed: ${e.message}`,"EXECUTE_SAFELY_FAILED")}}}async executeShortcodeSafely(e,t){try{return{result:await this.executeShortcode(e,t),error:null}}catch(e){return e instanceof TemplateError?{result:null,error:e}:{result:null,error:new TemplateError(`Execute shortcode safely failed: ${e.message}`,"EXECUTE_SHORTCODE_SAFELY_FAILED")}}}async hasTemplate(e){const[,t]=await this.get(e);return t}getTemplateNames(){return this.templateNamespace.getTemplateNames()}getPartialTemplateNames(){return this.partialNamespace.getTemplateNames()}getAllTemplateNames(){return[...this.templateNamespace.getTemplateNames(),...this.partialNamespace.getTemplateNames(),...this.shortcodeNamespace.getTemplateNames()]}getPartialNamespace(){return this.partialNamespace}getShortcodeNamespace(){return this.shortcodeNamespace}getTemplateNamespace(){return this.templateNamespace}clear(){this.templateNamespace.clear(),this.lookup.getBaseOf().clear()}getTemplatesByPattern(e){return this.templateNamespace.getTemplatesByPattern(e).map(e=>e.info.name)}}}});import*as crypto2 from"crypto";function newTemplateRegistry(){return new DefaultTemplateRegistry}var Factory2,Builder,init_registry=__esm({"internal/domain/template/vo/registry.ts"(){init_log(),init_lang(),log34=getDomainLogger("template",{component:"registry"}),engineDependentFunctions=[],PartialFunction=class{engine=null;globalPartialsCache=new Map;getFunctionName(){return"partial"}updateEngine(e){this.engine=e,this.globalPartialsCache.clear()}execute=async(e,t)=>{if(!this.engine)return log34.error(`Partial function called but engine not set: ${e}`),`\x3c!-- Partial function called but engine not ready: ${e} --\x3e`;try{const r=e.startsWith("partials/")?e:`partials/${e}`,i=r.includes("global");if(i&&this.globalPartialsCache.has(r))return this.globalPartialsCache.get(r);const s=await this.executePartial(r,t);return i&&this.globalPartialsCache.set(r,s),s}catch(t){return log34.error(`Partial execution failed for "${e}":`,t),`\x3c!-- Partial execution failed: ${e} - ${t.message} --\x3e`}};async executePartial(e,t){if(!this.engine)return`\x3c!-- Template engine not available: ${e} --\x3e`;try{const[r,i,s]=await this.engine.getPartial(e);if(s)return log34.error("Error getting partial template:",s),`\x3c!-- Error getting partial template: ${e} - ${s.message} --\x3e`;if(!i||!r)return log34.warn(`Template not found: ${e}`),`\x3c!-- Template not found: ${e} --\x3e`;const[n,a]=await r.Execute(t);return a?(log34.error("Template execution error:",a),`\x3c!-- Template execution error: ${e} - ${a.message} --\x3e`):n}catch(t){return log34.error("Sync partial execution failed:",t),`\x3c!-- Partial sync execution failed: ${e} - ${t.message} --\x3e`}}},DefaultTemplateRegistry=class{registerCoreFunctions(e){this.registerCryptoFunctions(e),this.registerStringFunctions(e),this.registerMathFunctions(e),this.registerTimeFunctions(e),this.registerCollectionFunctions(e),this.registerSafeFunctions(e),this.registerReflectFunctions(e),this.registerFmtFunctions(e),this.registerPathFunctions(e),this.registerTransformFunctions(e)}registerCryptoFunctions(e){e.set("md5",e=>e?crypto2.createHash("md5").update(e).digest("hex"):""),e.set("encryptAESGCM",(e,t)=>{if(!e||!t)return"";const r=crypto2.randomBytes(16),i=crypto2.randomBytes(12),s=crypto2.pbkdf2Sync(e,r,1e5,32,"sha256"),n=crypto2.createCipheriv("aes-256-gcm",s,i),a=Buffer.concat([n.update(t,"utf8"),n.final()]),o=n.getAuthTag();return Buffer.concat([r,i,o,a]).toString("base64")})}registerExtendedFunctions(e,t){this.registerURLFunctions(e,t),this.registerSiteFunctions(e,t),this.registerResourcesFunctions(e,t),this.registerHugoFunctions(e,t),this.registerLanguageFunctions(e,t)}registerAllFunctions(e,t){this.registerCoreFunctions(e),this.registerStringFunctions(e),this.registerMathFunctions(e),this.registerTimeFunctions(e),this.registerCollectionFunctions(e),this.registerEngineDependentFunctions(e),t&&(this.registerURLFunctions(e,t),this.registerExtendedFunctions(e,t))}registerEngineDependentFunctions(e){const t=new PartialFunction;engineDependentFunctions.push(t),e.set(t.getFunctionName(),t.execute)}registerURLFunctions(e,t){e.set("urls",()=>({Parse:e=>{try{return{Host:new URL(e).host}}catch{return{Host:""}}},JoinPath:(...e)=>e.filter(e=>""!==e).map(e=>e.replace(/^\/+|\/+$/g,"")).join("/"),URLize:e=>t.urlize(e),Abs:e=>t.absURL(e),Rel:e=>t.relURL(e),AbsLangURL:e=>t.absURL(e),RelLangURL:e=>t.relURL(e),Sanitize:e=>{try{return new URL(e).toString()}catch{return e.replace(/[<>"'%{}|\\^`]/g,"")}},PathEscape:e=>encodeURIComponent(e).replace(/%2F/g,"/").replace(/[!'()*]/g,e=>`%${e.charCodeAt(0).toString(16).toUpperCase()}`),QueryEscape:e=>encodeURIComponent(e),QueryUnescape:e=>{try{return decodeURIComponent(e)}catch{return e}},IsAbs:e=>{try{return""!==new URL(e).protocol}catch{return!1}},IsRelative:e=>{try{return new URL(e),!1}catch{return!0}}})),e.set("absURL",e=>t.absURL(e)),e.set("relURL",e=>t.relURL(e)),e.set("urlize",e=>t.urlize(e)),e.set("relref",(e,r)=>{if(/^https?:\/\//.test(r))return r;let i="";const s=r.indexOf("#");return-1!==s&&(i=r.slice(s),r=r.slice(0,s)),(r=r.replace(/^\/+|\/+$/g,"")).startsWith("./")||r.startsWith("../")||r.startsWith("/")?t.relURL(r+i):t.relURL("/"+r+i)}),e.set("ref",(e,r)=>{if(/^https?:\/\//.test(r))return r;let i="";const s=r.indexOf("#");return-1!==s&&(i=r.slice(s),r=r.slice(0,s)),(r=r.replace(/^\/+|\/+$/g,"")).startsWith("./")||r.startsWith("../")||r.startsWith("/")?t.absURL(r+i):t.absURL("/"+r+i)}),e.set("absLangURL",e=>t.absURL(e)),e.set("relLangURL",e=>t.relURL(e))}registerSiteFunctions(e,t){e.set("Site",()=>({Title:t.title(),BaseURL:t.baseURL(),Params:t.params(),Menus:t.menus(),IsMultiLingual:t.isMultiLanguage(),LanguageCode:t.defaultLanguage()}))}registerResourcesFunctions(e,t){e.set("resources",()=>({Get:async e=>await t.Get(e),GetRemote:async e=>await t.GetRemote(e),Minify:async e=>await t.Minify(e),Fingerprint:async e=>await t.Fingerprint(e),ExecuteAsTemplate:async(e,r,i)=>await t.ExecuteAsTemplate(e,r,i)}))}registerHugoFunctions(e,t){e.set("hugo",()=>({Version:t.version(),Environment:t.environment(),Generator:t.generator()}))}registerLanguageFunctions(e,t){e.set("lang",()=>({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)})),e.set("langName",e=>lang.getNameByCode(e)||e),e.set("langDirection",e=>lang.getDirection(e)||"ltr"),e.set("isLTR",e=>lang.isLTR(e)),e.set("isRTL",e=>lang.isRTL(e)),e.set("i18n",e=>t.translate(e))}registerStringFunctions(e){e.set("humanize",e=>e?(e=(e=e.replace(/([a-z])([A-Z])/g,"$1 $2")).replace(/[_-]+/g," "),/\.(md|html|htm|markdown|mdown|mkd|mkdn|txt)$/i.test(e)&&(e=e.replace(/\.[^/.]+$/,"")),(e=e.charAt(0).toUpperCase()+e.slice(1).toLowerCase()).trim()):""),e.set("upper",e=>e.toUpperCase()),e.set("lower",e=>e.toLowerCase()),e.set("title",e=>e.replace(/\w\S*/g,e=>e.charAt(0).toUpperCase()+e.substr(1).toLowerCase())),e.set("trim",e=>e.trim()),e.set("replace",(...e)=>{if(e.length<3)throw new Error("replace requires at least 3 arguments: string, old, new");const t=String(e[0]),r=String(e[1]),i=String(e[2]);if(e.length>=4){const s=Number(e[3]);if(isNaN(s))throw new Error("replace limit must be a number");let n=t,a=0,o=0;for(;a<s&&o<n.length;){const e=n.indexOf(r,o);if(-1===e)break;n=n.substring(0,e)+i+n.substring(e+r.length),o=e+i.length,a++}return n}return t.split(r).join(i)}),e.set("replaceRE",(...t)=>{if(t.length<3)throw new Error("replaceRE requires at least 3 arguments: pattern, replacement, string");const r=t[0],i=t[1],s=t[2],n=t.length>=4?t[3]:void 0;return e.get("strings")().ReplaceRE(r,i,s,n)}),e.set("split",(e,t)=>null==e?(log34.warn("split function: first argument is null or undefined"),[]):"string"!=typeof e?(log34.warn("split function: first argument must be a string, got:",typeof e,"value:",e),Array.isArray(e)?e:String(e).split(t)):e.split(t)),e.set("splitRegex",(e,t)=>{if(null==e)return log34.warn("splitRegex function: first argument is null or undefined"),[];if("string"!=typeof e){if(log34.warn("splitRegex function: first argument must be a string, got:",typeof e,"value:",e),Array.isArray(e))return e;const r=String(e);try{const e=new RegExp(t);return r.split(e)}catch(e){return log34.warn("splitRegex function: invalid regex pattern:",t,"error:",e),[r]}}try{const r=new RegExp(t);return e.split(r)}catch(r){return log34.warn("splitRegex function: invalid regex pattern:",t,"error:",r),[e]}}),e.set("delimit",(e,t)=>Array.isArray(e)?e.join(t):String(e)),e.set("in",(e,t)=>(Array.isArray(e)||"string"==typeof e&&"string"==typeof t)&&e.includes(t)),e.set("hasPrefix",(e,t)=>e.startsWith(t)),e.set("hasSuffix",(e,t)=>e.endsWith(t)),e.set("strings",()=>({ToLower:e=>String(e).toLowerCase(),ToUpper:e=>String(e).toUpperCase(),Title:e=>String(e).replace(/\w\S*/g,e=>e.charAt(0).toUpperCase()+e.substr(1).toLowerCase()),Trim:(e,t)=>String(e).split("").filter(e=>!t.includes(e)).join(""),TrimSpace:e=>String(e).trim(),TrimLeft:(e,t)=>{const r=String(t);let i=0;for(;i<r.length&&e.includes(r[i]);)i++;return r.slice(i)},TrimRight:(e,t)=>{const r=String(t);let i=r.length-1;for(;i>=0&&e.includes(r[i]);)i--;return r.slice(0,i+1)},TrimPrefix:(e,t)=>{const r=String(t);return r.startsWith(e)?r.slice(e.length):r},TrimSuffix:(e,t)=>{const r=String(t);return r.endsWith(e)?r.slice(0,-e.length):r},Contains:(e,t)=>String(e).includes(t),ContainsAny:(e,t)=>{const r=String(e);return t.split("").some(e=>r.includes(e))},HasPrefix:(e,t)=>String(e).startsWith(t),HasSuffix:(e,t)=>String(e).endsWith(t),Replace:(e,t,r,i)=>{const s=String(e);if(void 0===i)return s.split(t).join(r);let n=s,a=0,o=0;for(;a<i&&o<n.length;){const e=n.indexOf(t,o);if(-1===e)break;n=n.substring(0,e)+r+n.substring(e+t.length),o=e+r.length,a++}return n},ReplaceRE:(e,t,r,i)=>{const s=String(e),n=String(t),a=String(r);let o,l=-1;if(void 0!==i){const e=parseInt(String(i),10);if(isNaN(e))throw new Error("limit argument must be integer");l=e}try{o=new RegExp(s,"g")}catch(e){throw new Error(`invalid regular expression: ${s}`)}let c=0;return a.replace(o,e=>l>=0&&c>=l?e:(c++,n))},Split:(e,t)=>String(e).split(t),SliceString:(e,t,r)=>{const i=String(e);return void 0!==r?i.slice(t,r):i.slice(t)},Substr:(e,t,r)=>{const i=String(e);return t<0&&(t=i.length+t),t<0&&(t=0),t>=i.length?"":void 0===r?i.slice(t):r<=0?"":i.slice(t,t+r)},Count:(e,t)=>{const r=String(t);return e?(r.match(new RegExp(e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g"))||[]).length:r.length+1},CountWords:e=>{const t=String(e).trim();return t?t.split(/\s+/).length:0},CountRunes:e=>String(e).replace(/\s/g,"").length,RuneCount:e=>String(e).length,Repeat:(e,t)=>{if(e<0)throw new Error("strings: negative Repeat count");return String(t).repeat(e)},FirstUpper:e=>{const t=String(e);return t.charAt(0).toUpperCase()+t.slice(1)}})),e.set("substr",(e,...t)=>{const r=String(e),i=Array.from(r),s=i.length;let n,a;switch(t.length){case 0:throw new Error("too few arguments");case 1:const e=Number(t[0]);if(isNaN(e)||!Number.isInteger(e))throw new Error("start argument must be an integer");n=e,a=s;break;case 2:const r=Number(t[0]),i=Number(t[1]);if(isNaN(r)||!Number.isInteger(r))throw new Error("start argument must be an integer");if(isNaN(i)||!Number.isInteger(i))throw new Error("length argument must be an integer");n=r,a=i;break;default:throw new Error("too many arguments")}if(0===s)return"";if(n<0&&(n+=s),n<0&&(n=0),n>s-1)return"";let o=s;return 0===a?"":(a<0?o+=a:a>0&&(o=n+a),n>=o||o<0?"":(o>s&&(o=s),i.slice(n,o).join("")))}),e.set("truncate",(e,...t)=>{const r=Number(e);if(isNaN(r)||!Number.isInteger(r))throw new Error("truncate length must be an integer");let i,s=" …";switch(t.length){case 0:throw new Error("truncate requires a length and a string");case 1:i=t[0],s=" …";break;case 2:s=String(t[0]),i=t[1];break;default:throw new Error("too many arguments passed to truncate")}const n=String(i),a=/<[^>]+>/.test(n);return Array.from(n).length<=r?a?n:this.escapeHTML(n):a?this.truncateHTML(n,r,s):this.truncateText(n,r,s)})}escapeHTML(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;")}truncateText(e,t,r){const i=Array.from(e);if(i.length<=t)return this.escapeHTML(e);let s=0,n=0;for(let e=0;e<i.length&&n<t;e++){const t=i[e];n++,/\s/.test(t)&&(s=e),/[\u4e00-\u9fff\u3400-\u4dbf\u3040-\u309f\u30a0-\u30ff\uac00-\ud7af]/.test(t)&&(s=e)}let a=n>=t?s>0?s:t:i.length;const o=i.slice(0,a).join("");return this.escapeHTML(o)+r}truncateHTML(e,t,r){const i=/^<(\/)?([^ ]+?)(?:(\s*\/)| .*?)?>/,s=new Set(["br","col","link","base","img","param","area","hr","input"]),n=[];let a=0,o=0,l=0,c=0,h=0;const u=Array.from(e);for(;h<u.length;){const e=u[h];if("<"===e){const e=u.slice(h).join("").match(i);if(e){const t=e[0],r="/"===e[1],i=e[2].toLowerCase(),l="/"===e[3];h+=t.length,a=o,s.has(i)||l||n.push({name:i,pos:h-t.length,openTag:!r});continue}}if(l++,/\s/.test(e)?a=o:/[\u4e00-\u9fff\u3400-\u4dbf\u3040-\u309f\u30a0-\u30ff\uac00-\ud7af]/.test(e)?a=h:o=h+1,l>t){c=a>0?a:h;break}h++}if(l<=t)return e;let g=u.slice(0,c).join("")+r,d=null;for(let e=n.length-1;e>=0;e--){const t=n[e];t.pos>=c||null!==d?null!==d&&d.name===t.name&&(d=null):t.openTag?g+=`</${t.name}>`:d=t}return g}registerMathFunctions(e){e.set("add",(e,t)=>e+t),e.set("sub",(e,t)=>e-t),e.set("mul",(e,t)=>e*t),e.set("div",(e,t)=>0!==t?e/t:0),e.set("mod",(e,t)=>0!==t?e%t:0),e.set("math",()=>({Abs:e=>{const t=Number(e);if(isNaN(t))throw new Error("the math.Abs function requires a numeric argument");return Math.abs(t)},Add:(...e)=>{if(e.length<2)throw new Error("must provide at least two numbers");return e.reduce((e,t)=>{const r=Number(t);if(isNaN(r))throw new Error("Add operator can't be used with non-numeric values");return e+r},0)},Ceil:e=>{const t=Number(e);if(isNaN(t))throw new Error("Ceil operator can't be used with non-numeric value");return Math.ceil(t)},Div:(...e)=>{if(e.length<2)throw new Error("must provide at least two numbers");return e.reduce((e,t,r)=>{const i=Number(t);if(isNaN(i))throw new Error("Div operator can't be used with non-numeric values");if(0===r)return i;if(0===i)throw new Error("division by zero");return e/i})},Floor:e=>{const t=Number(e);if(isNaN(t))throw new Error("Floor operator can't be used with non-numeric value");return Math.floor(t)},Log:e=>{const t=Number(e);if(isNaN(t))throw new Error("Log operator can't be used with non-numeric value");return Math.log(t)},Max:(...e)=>{if(0===e.length)throw new Error("must provide at least one number");const t=e.flat().map(e=>{const t=Number(e);if(isNaN(t))throw new Error("Max operator can't be used with non-numeric values");return t});return Math.max(...t)},Min:(...e)=>{if(0===e.length)throw new Error("must provide at least one number");const t=e.flat().map(e=>{const t=Number(e);if(isNaN(t))throw new Error("Min operator can't be used with non-numeric values");return t});return Math.min(...t)},Mod:(e,t)=>{const r=Number(e),i=Number(t);if(isNaN(r)||isNaN(i))throw new Error("modulo operator can't be used with non-numeric value");if(0===i)throw new Error("the number can't be divided by zero at modulo operation");return r%i},ModBool:(e,t)=>{const r=Number(e),i=Number(t);if(isNaN(r)||isNaN(i))throw new Error("modulo operator can't be used with non-numeric value");if(0===i)throw new Error("the number can't be divided by zero at modulo operation");return r%i===0},Mul:(...e)=>{if(e.length<2)throw new Error("must provide at least two numbers");return e.reduce((e,t)=>{const r=Number(t);if(isNaN(r))throw new Error("Mul operator can't be used with non-numeric values");return e*r},1)},Pow:(e,t)=>{const r=Number(e),i=Number(t);if(isNaN(r)||isNaN(i))throw new Error("Pow operator can't be used with non-numeric value");return Math.pow(r,i)},Rand:()=>Math.random(),Round:e=>{const t=Number(e);if(isNaN(t))throw new Error("Round operator can't be used with non-numeric value");return Math.round(t)},Sqrt:e=>{const t=Number(e);if(isNaN(t))throw new Error("Sqrt operator can't be used with non-numeric value");return Math.sqrt(t)},Sub:(...e)=>{if(e.length<2)throw new Error("must provide at least two numbers");return e.reduce((e,t,r)=>{const i=Number(t);if(isNaN(i))throw new Error("Sub operator can't be used with non-numeric values");return 0===r?i:e-i})},Sum:(...e)=>{if(0===e.length)throw new Error("must provide at least one number");return e.flat().map(e=>{const t=Number(e);if(isNaN(t))throw new Error("Sum operator can't be used with non-numeric values");return t}).reduce((e,t)=>e+t,0)},Product:(...e)=>{if(0===e.length)throw new Error("must provide at least one number");return e.flat().map(e=>{const t=Number(e);if(isNaN(t))throw new Error("Product operator can't be used with non-numeric values");return t}).reduce((e,t)=>e*t,1)}}))}registerTimeFunctions(e){e.set("time",()=>({AsTime:e=>{if(!e)return null;if(e instanceof Date)return e;if("string"==typeof e){const t=new Date(e);return isNaN(t.getTime())?null:t}if("number"==typeof e){const t=new Date(e<1e10?1e3*e:e);return isNaN(t.getTime())?null:t}return null},Format:(e,t)=>{const r=t instanceof Date?t:new Date(t);if(isNaN(r.getTime()))return"";const i=r.getFullYear(),s=r.getMonth()+1,n=r.getDate(),a=r.getHours(),o=r.getMinutes(),l=r.getSeconds(),c=r.toLocaleString("en-US",{weekday:"short"}),h=r.toLocaleString("en-US",{month:"short"}),u=[{pattern:"2006",placeholder:"{{YEAR_FULL}}",value:i.toString()},{pattern:"January",placeholder:"{{MONTH_FULL}}",value:r.toLocaleString("en-US",{month:"long"})},{pattern:"Monday",placeholder:"{{WEEKDAY_FULL}}",value:r.toLocaleString("en-US",{weekday:"long"})},{pattern:"MST",placeholder:"{{TIMEZONE}}",value:r.toLocaleString("en-US",{timeZoneName:"short"})},{pattern:"Jan",placeholder:"{{MONTH_SHORT}}",value:h},{pattern:"Mon",placeholder:"{{WEEKDAY_SHORT}}",value:c},{pattern:"06",placeholder:"{{YEAR_SHORT}}",value:i.toString().slice(-2)},{pattern:"15",placeholder:"{{HOUR_24}}",value:a.toString().padStart(2,"0")},{pattern:"01",placeholder:"{{MONTH_ZERO}}",value:s.toString().padStart(2,"0")},{pattern:"02",placeholder:"{{DAY_ZERO}}",value:n.toString().padStart(2,"0")},{pattern:"04",placeholder:"{{MINUTE_ZERO}}",value:o.toString().padStart(2,"0")},{pattern:"05",placeholder:"{{SECOND_ZERO}}",value:l.toString().padStart(2,"0")},{pattern:"PM",placeholder:"{{AMPM_UPPER}}",value:a>=12?"PM":"AM"},{pattern:"pm",placeholder:"{{AMPM_LOWER}}",value:a>=12?"pm":"am"},{pattern:"3",placeholder:"{{HOUR_12}}",value:((a+11)%12+1).toString()},{pattern:"1",placeholder:"{{MONTH_NUM}}",value:s.toString()},{pattern:"2",placeholder:"{{DAY_NUM}}",value:n.toString()},{pattern:"4",placeholder:"{{MINUTE_NUM}}",value:o.toString()},{pattern:"5",placeholder:"{{SECOND_NUM}}",value:l.toString()}];let g=e;for(const{pattern:e,placeholder:t}of u){const r=e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");g=g.replace(new RegExp(r,"g"),t)}for(const{placeholder:e,value:t}of u)g=g.replace(new RegExp(e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g"),t);return g},Now:()=>new Date,Parse:(e,t)=>{try{const e=new Date(t);return isNaN(e.getTime())?null:e}catch{return null}},Unix:e=>{const t=e instanceof Date?e:new Date(e);return Math.floor(t.getTime()/1e3)},UnixNano:e=>1e6*(e instanceof Date?e:new Date(e)).getTime()})),e.set("now",()=>{const e=new Date;return{Format:t=>{const r=e.getFullYear(),i=e.getMonth()+1,s=e.getDate(),n=e.getHours(),a=e.getMinutes(),o=e.getSeconds(),l=[{pattern:"2006",value:r.toString()},{pattern:"06",value:r.toString().slice(-2)},{pattern:"01",value:i.toString().padStart(2,"0")},{pattern:"1",value:i.toString()},{pattern:"02",value:s.toString().padStart(2,"0")},{pattern:"2",value:s.toString()},{pattern:"15",value:n.toString().padStart(2,"0")},{pattern:"3",value:(n%12||12).toString()},{pattern:"04",value:a.toString().padStart(2,"0")},{pattern:"4",value:a.toString()},{pattern:"05",value:o.toString().padStart(2,"0")},{pattern:"5",value:o.toString()}];let c=t;for(const{pattern:e,value:t}of l){const r=new RegExp(`\\b${e}\\b`,"g");c=c.replace(r,t)}return"2006"===t?r.toString():"06"===t?r.toString().slice(-2):"01"===t?i.toString().padStart(2,"0"):"02"===t?s.toString().padStart(2,"0"):"15"===t?n.toString().padStart(2,"0"):"04"===t?a.toString().padStart(2,"0"):"05"===t?o.toString().padStart(2,"0"):c},getTime:()=>e.getTime(),toString:()=>e.toString(),toISOString:()=>e.toISOString()}}),e.set("dateFormat",(e,t)=>t.toLocaleDateString())}registerCollectionFunctions(e){e.set("len",e=>Array.isArray(e)||"string"==typeof e?e.length:e&&"object"==typeof e?Object.keys(e).length:0),e.set("first",(e,t)=>Array.isArray(e)?e.slice(0,1):Array.isArray(t)?t.slice(0,e):[]),e.set("last",(e,t)=>Array.isArray(e)?e.slice(-1):Array.isArray(t)?t.slice(-e):[]),e.set("merge",(...e)=>{const t={};for(const r of e)r&&"object"==typeof r&&!Array.isArray(r)&&Object.assign(t,r);return t}),e.set("index",(e,...t)=>{try{return this.doIndex(e,t)}catch(r){return log34.error(`Index of type ${typeof e} with args [${t.join(", ")}] failed:`,r),null}}),e.set("reverse",e=>Array.isArray(e)?[...e].reverse():e),e.set("append",(...e)=>{if(e.length<2)return e[0]||[];const t=Array.isArray(e[0])?[...e[0]]:[e[0]];for(let r=1;r<e.length;r++)Array.isArray(e[r])?t.push(...e[r]):t.push(e[r]);return t}),e.set("prepend",(e,...t)=>Array.isArray(e)?[...t,...e]:[...t,e]),e.set("seq",(...e)=>{if(e.length<1||e.length>3)throw new Error("invalid number of arguments to Seq");const t=e.map(e=>{const t=Number(e);if(isNaN(t))throw new Error("invalid arguments to Seq");return Math.floor(t)});let r,i=1,s=t[0];if(1===t.length){if(r=s,0===r)return[];r>0?s=1:(s=-1,i=-1)}else if(2===t.length)r=t[1],r<s&&(i=-1);else{if(i=t[1],r=t[2],0===i)throw new Error("'increment' must not be 0");if(s<r&&i<0)throw new Error("'increment' must be > 0");if(s>r&&i>0)throw new Error("'increment' must be < 0")}if(r<-1e5)throw new Error("size of result exceeds limit");const n=Math.floor((r-s)/i)+1;if(n<=0||n>2e3)throw new Error("size of result exceeds limit");const a=new Array(n);let o=s;for(let e=0;e<n&&(a[e]=o,o+=i,!(i<0&&o<r||i>0&&o>r));e++);return a}),e.set("sort",(e,...t)=>{if(null==e)throw new Error("sequence must be provided");let r;if(Array.isArray(e))r=[...e];else{if("object"!=typeof e||null===e)throw new Error("can't sort "+typeof e);r=Object.values(e)}if(0===r.length)return r;let i="",s=!0;for(let e=0;e<t.length;e++){const r=t[e];0===e?"string"==typeof r&&(i=r):1===e&&"string"==typeof r&&"desc"===r.toLowerCase()&&(s=!1)}const n=(e,t)=>{if(!t||"value"===t)return e;const r=t.split(".");let i=e;for(const e of r){if(null==i)return;if("object"!=typeof i)return;i=i[e]}return i};return r.sort((e,t)=>{let r=i?n(e,i):e,a=i?n(t,i):t;if(null==r)return null==a?0:s?-1:1;if(null==a)return s?1:-1;if("string"==typeof r&&"string"==typeof a){const e=r.localeCompare(a);return s?e:-e}if("number"==typeof r&&"number"==typeof a){const e=r-a;return s?e:-e}const o=String(r),l=String(a),c=o.localeCompare(l);return s?c:-c})}),e.set("where",(()=>(e,t,...r)=>{if(!e)return[];let i,s="==";if(1===r.length)i=r[0];else{if(2!==r.length)throw new Error("where function requires 2-4 arguments");s=r[0],i=r[1]}const n=[];if(Array.isArray(e))for(let r=0;r<e.length;r++){const a=e[r],o=this.getNestedValue(a,t);this.checkCondition(o,i,s)&&n.push(a)}else if("object"==typeof e)for(const[r,a]of Object.entries(e))if(Array.isArray(a)){const e=a.filter(e=>{const r=this.getNestedValue(e,t);return this.checkCondition(r,i,s)});e.length>0&&n.push({[r]:e})}return n})()),e.set("intersect",(e,t)=>Array.isArray(e)&&Array.isArray(t)?e.filter(e=>t.includes(e)):[]),e.set("querify",(...e)=>{let t=[];if(t=1===e.length&&Array.isArray(e[0])?e[0]:e,t.length%2!=0)throw new Error("querify requires an even number of arguments (key-value pairs)");const r=[];for(let e=0;e<t.length;e+=2){const i=String(t[e]),s=String(t[e+1]);r.push([i,s])}return r.sort((e,t)=>e[0].localeCompare(t[0])),r.map(([e,t])=>`${encodeURIComponent(e).replace(/%20/g,"+")}=${encodeURIComponent(t).replace(/%20/g,"+")}`).join("&")}),e.set("isset",(e,t)=>{if(null==e)return!1;if(Array.isArray(e)){const r=Number(t);return isNaN(r)||!Number.isInteger(r)?(console.warn(`isset unable to use key of type ${typeof t} as index`),!1):e.length>r&&r>=0}if("object"==typeof e)return t in e;if("string"==typeof e){const r=Number(t);return isNaN(r)||!Number.isInteger(r)?(console.warn(`isset unable to use key of type ${typeof t} as index`),!1):e.length>r&&r>=0}return console.warn(`calling isset with unsupported type "${typeof e}" (${e.constructor?.name||typeof e}) will always return false.`),!1})}doIndex(e,t){if(null==e)return null;if(0===t.length)return e;let r=e;for(const e of t){if(null==r)return null;if(Array.isArray(r))r=this.indexArray(r,e);else if("string"==typeof r)r=this.indexString(r,e);else{if("object"!=typeof r)throw new Error("can't index item of type "+typeof r);r=this.indexObject(r,e)}}return r}indexArray(e,t){const r=this.toInteger(t);if(null===r)throw new Error("cannot index slice/array with type "+typeof t);return r<0||r>=e.length?null:e[r]}indexString(e,t){const r=this.toInteger(t);if(null===r)throw new Error("cannot index string with type "+typeof t);return r<0||r>=e.length?null:e.charAt(r)}indexObject(e,t){const r=String(t);if(e.hasOwnProperty(r))return e[r];const i=Object.keys(e).find(e=>e.toLowerCase()===r.toLowerCase());if(i)return e[i];if(e instanceof Map){if(e.has(r))return e.get(r);for(const t of e.keys())if(String(t).toLowerCase()===r.toLowerCase())return e.get(t)}return null}toInteger(e){if("number"==typeof e)return Number.isInteger(e)?e:Math.floor(e);if("string"==typeof e){const t=parseInt(e,10);if(!isNaN(t))return t}return null}checkCondition(e,t,r){const i=r.toLowerCase().trim();if(null==e&&null==t)return["==","=","eq",""].includes(i);if(null==e||null==t)return["!=","<>","ne"].includes(i);if("in"===i)return(Array.isArray(t)||"string"==typeof t&&"string"==typeof e)&&t.includes(e);if("intersect"===i)return!(!Array.isArray(e)||!Array.isArray(t))&&e.some(e=>t.includes(e));const[s,n]=this.normalizeForComparison(e,t);switch(i){case"":case"=":case"==":case"eq":return s===n;case"!=":case"<>":case"ne":return s!==n;case"<":case"lt":return s<n;case"<=":case"le":return s<=n;case">":case"gt":return s>n;case">=":case"ge":return s>=n;default:return!1}}normalizeForComparison(e,t){if("number"==typeof e&&"number"==typeof t)return[e,t];if("number"==typeof e&&"string"==typeof t){const r=parseFloat(t);if(!isNaN(r))return[e,r]}if("string"==typeof e&&"number"==typeof t){const r=parseFloat(e);if(!isNaN(r))return[r,t]}return"string"==typeof e&&"string"==typeof t||"boolean"==typeof e&&"boolean"==typeof t?[e,t]:[String(e),String(t)]}registerSafeFunctions(e){e.set("return",(...e)=>0===e.length?"":1===e.length?e[0]:e),e.set("cond",(...e)=>{if(e.length<2)throw new Error("cond requires at least 2 arguments");const t=e[0],r=e[1],i=e.length>2?e[2]:"";let s=!1;return!0===t||1===t?s=!0:"string"==typeof t?s=t.length>0&&"false"!==t&&"0"!==t:"number"==typeof t?s=0!==t:Array.isArray(t)?s=t.length>0:t&&"object"==typeof t&&(s=Object.keys(t).length>0),s?r:i}),e.set("safeHTML",e=>e),e.set("safeCSS",e=>e),e.set("safeJS",e=>e),e.set("safeURL",e=>e),e.set("dict",(...e)=>{if(e.length%2!=0)throw new Error("dict requires an even number of arguments");const t={};for(let r=0;r<e.length;r+=2)t[String(e[r])]=e[r+1];return t}),e.set("slice",(...e)=>e),e.set("default",(e,t)=>null!=t&&""!==t&&0!==t?t:e),e.set("jsonify",(...e)=>{if(0===e.length)return"";let t,r={};if(1===e.length)t=e[0];else{if(2!==e.length)throw new Error("too many arguments to jsonify");{const i=e[0];t=e[1],i&&"object"==typeof i&&(r.prefix=i.prefix||"",r.indent=i.indent||"",r.noHTMLEscape=i.noHTMLEscape||!1)}}try{let e;return r.indent?(e=JSON.stringify(t,null,r.indent),r.prefix&&(e=e.split("\n").map(e=>r.prefix+e).join("\n"))):e=JSON.stringify(t),r.noHTMLEscape||(e=e.replace(/&/g,"\\u0026").replace(/</g,"\\u003c").replace(/>/g,"\\u003e")),e}catch(e){throw new Error(`failed to jsonify object: ${e.message}`)}})}registerFmtFunctions(e){e.set("printf",(e,...t)=>{let r=e,i=0;return r=r.replace(/%[vsdft%]/g,e=>{if("%%"===e)return"%";if(i>=t.length)return e;const r=t[i++];switch(e){case"%v":case"%s":default:return String(r);case"%d":return String(Math.floor(Number(r)||0));case"%f":return String(Number(r)||0);case"%t":return String(Boolean(r))}}),r}),e.set("print",(...e)=>e.map(e=>String(e)).join(" ")),e.set("println",(...e)=>e.map(e=>String(e)).join(" ")+"\n"),e.set("errorf",(e,...t)=>{let r=e;for(let e=0;e<t.length;e++)r=r.replace(/%[sd%]/,String(t[e]));return log34.error("Template Error:",r),""}),e.set("warnf",(e,...t)=>{let r=e;for(let e=0;e<t.length;e++)r=r.replace(/%[sd%]/,String(t[e]));return log34.warn("Template Warning:",r),""}),e.set("fmt",()=>({Print:(...e)=>e.map(e=>String(e)).join(" "),Printf:(e,...t)=>{let r=e;for(let e=0;e<t.length;e++)r=r.replace(/%[sd%]/,String(t[e]));return r},Println:(...e)=>e.map(e=>String(e)).join(" ")+"\n",Errorf:(e,...t)=>{let r=e;for(let e=0;e<t.length;e++)r=r.replace(/%[sd%]/,String(t[e]));return log34.error("Template Error:",r),""},Erroridf:(e,t,...r)=>{let i=t;for(let e=0;e<r.length;e++)i=i.replace(/%[sd%]/,String(r[e]));return log34.error("Template Error:",i),""},Warnf:(e,...t)=>{let r=e;for(let e=0;e<t.length;e++)r=r.replace(/%[sd%]/,String(t[e]));return log34.error("Template Warning:",r),""},Warnidf:(e,t,...r)=>{let i=t;for(let e=0;e<r.length;e++)i=i.replace(/%[sd%]/,String(r[e]));return log34.error("Template Warning:",i),""}}))}registerReflectFunctions(e){e.set("reflect",()=>({IsMap:e=>{if(null==e)return!1;if("object"!=typeof e||Array.isArray(e))return!1;if(e instanceof Map)return!0;if(e.constructor===Object)return!0;const t=Object.getPrototypeOf(e);return t===Object.prototype||null===t},IsSlice:e=>Array.isArray(e)}))}registerPathFunctions(e){e.set("path",()=>({Base:e=>{if(!e)return".";if(!(e=(e=e.replace(/\\/g,"/")).replace(/\/+$/,"")))return"/";const t=e.split("/");return t[t.length-1]||"/"},Clean:e=>{if(!e)return".";const t=(e=e.replace(/\\/g,"/")).startsWith("/"),r=e.split("/").filter(e=>e&&"."!==e),i=[];for(const e of r)".."===e?i.length>0&&".."!==i[i.length-1]?i.pop():t||i.push(".."):i.push(e);return e=i.join("/"),t&&(e="/"+e),e||(t?"/":".")},Dir:e=>{if(!e)return".";if(!(e=e.replace(/\/+$/,"")))return"/";const t=e.split("/");return t.pop(),t.join("/")||"."},Ext:e=>{const t=e.split("/").pop()||"",r=t.lastIndexOf(".");return-1===r||0===r?"":t.substring(r)},IsAbs:e=>e.startsWith("/"),Join:(...e)=>{if(0===e.length)return".";let t=e.filter(e=>e).map(e=>e.replace(/^\/+|\/+$/g,"")).join("/");return e[0]&&e[0].startsWith("/")&&(t="/"+t),t||"."},Split:e=>{if(!e)return[".",""];const t=e.lastIndexOf("/");return-1===t?["",e]:[e.substring(0,t),e.substring(t+1)]}}))}registerTransformFunctions(e){e.set("transform",()=>({Unmarshal:(...e)=>{if(e.length<1||e.length>2)throw new Error("unmarshal takes 1 or 2 arguments");let t,r,i={};if(1===e.length)t=e[0];else{const r=e[0];if(!r||"object"!=typeof r)throw new Error("first argument must be a map");i=r,t=e[1]}if(t&&"object"==typeof t&&"function"==typeof t.Content)try{const e=t.Content();return this.unmarshalContent(e,i)}catch(e){throw new Error(`failed to get content from resource: ${e.message}`)}if("string"==typeof t)r=t;else{if(!t||"function"!=typeof t.toString)throw new Error(`type ${typeof t} not supported`);r=t.toString()}return r&&""!==r.trim()?this.unmarshalContent(r,i):null},Plainify:e=>{const t=String(e);return this.stripHTML(t)}})),e.set("unmarshal",(...t)=>e.get("transform")().Unmarshal(...t)),e.set("plainify",e=>{const t=String(e);return this.stripHTML(t)})}stripHTML(e){if(!e.includes("<")&&!e.includes(">"))return e;let t=e.replace(/\n/g," ").replace(/<\/p>/gi,"\n").replace(/<br\s*\/?>/gi,"\n").replace(/<\/div>/gi,"\n").replace(/<\/h[1-6]>/gi,"\n").replace(/<\/li>/gi,"\n").replace(/<\/tr>/gi,"\n").replace(/<\/blockquote>/gi,"\n");t=t.replace(/<[^>]*>/g,"");const r=t.split("\n");return t=r.map(e=>e.trim().replace(/\s+/g," ")).filter(e=>e.length>0).join("\n").trim(),t=t.replace(/\n\s*\n/g,"\n"),t}unmarshalContent(e,t={}){const r=e.trim();if(!r)return null;let i=t.format;i||(i=this.detectFormat(r));try{switch(i.toLowerCase()){case"json":return JSON.parse(r);case"yaml":case"yml":return this.parseYAML(r);case"toml":return this.parseTOML(r);case"csv":return this.parseCSV(r);default:throw new Error(`format "${i}" not supported`)}}catch(e){throw new Error(`failed to unmarshal ${i}: ${e.message}`)}}detectFormat(e){const t=e.trim();if(t.startsWith("{")&&t.endsWith("}")||t.startsWith("[")&&t.endsWith("]"))try{return JSON.parse(t),"json"}catch{}return t.startsWith("---")||/^[a-zA-Z_][a-zA-Z0-9_]*\s*:\s*.+/m.test(t)?"yaml":/^\[.*\]$/m.test(t)||/^[a-zA-Z_][a-zA-Z0-9_]*\s*=\s*.+/m.test(t)?"toml":/^[^,\n]*,[^,\n]*/.test(t)?"csv":"json"}parseYAML(e){const t=e.split("\n"),r={};for(const e of t){const t=e.trim();if(!t||t.startsWith("#")||"---"===t)continue;const i=t.indexOf(":");if(i>0){const e=t.substring(0,i).trim();let s=t.substring(i+1).trim();(s.startsWith('"')&&s.endsWith('"')||s.startsWith("'")&&s.endsWith("'"))&&(s=s.slice(1,-1)),"true"===s?r[e]=!0:"false"===s?r[e]=!1:/^\d+$/.test(s)?r[e]=parseInt(s,10):/^\d*\.\d+$/.test(s)?r[e]=parseFloat(s):r[e]=s}}return r}parseTOML(e){const t=e.split("\n"),r={};let i="";for(const e of t){const t=e.trim();if(!t||t.startsWith("#"))continue;if(t.startsWith("[")&&t.endsWith("]")){i=t.slice(1,-1),r[i]||(r[i]={});continue}const s=t.indexOf("=");if(s>0){const e=t.substring(0,s).trim();let n,a=t.substring(s+1).trim();(a.startsWith('"')&&a.endsWith('"')||a.startsWith("'")&&a.endsWith("'"))&&(a=a.slice(1,-1)),n="true"===a||"false"!==a&&(/^\d+$/.test(a)?parseInt(a,10):/^\d*\.\d+$/.test(a)?parseFloat(a):a),i?r[i][e]=n:r[e]=n}}return r}parseCSV(e){const t=e.trim().split("\n");if(0===t.length)return[];const r=this.parseCSVLine(t[0]),i=[];for(let e=1;e<t.length;e++){const s=this.parseCSVLine(t[e]),n={};for(let e=0;e<r.length;e++){const t=r[e],i=e<s.length?s[e]:"";/^\d+$/.test(i)?n[t]=parseInt(i,10):/^\d*\.\d+$/.test(i)?n[t]=parseFloat(i):n[t]="true"===i||"false"!==i&&i}i.push(n)}return i}parseCSVLine(e){const t=[];let r="",i=!1;for(let s=0;s<e.length;s++){const n=e[s];'"'===n?i&&'"'===e[s+1]?(r+='"',s++):i=!i:","!==n||i?r+=n:(t.push(r.trim()),r="")}return t.push(r.trim()),t}getNestedValue(e,t){if(!e||!t)return;const r=t.replace(/^\\.+/,"").split(".");let i=e;for(let e=0;e<r.length;e++){const t=r[e];if(null==i)return;if("object"==typeof i){if(i.hasOwnProperty(t)){i=i[t];continue}const e=Object.keys(i).find(e=>e.toLowerCase()===t.toLowerCase());if(e){i=i[e];continue}const r=t.toLowerCase();if("function"==typeof i[r])try{i=i[r]();continue}catch(e){return}return}return}return i}}}});var log35,PageBuilder,Taxonomy2,init_template2=__esm({"internal/domain/template/factory/template.ts"(){init_type8(),init_template(),init_executor(),init_parser(),init_lookup(),init_namespace(),init_baseof(),init_registry(),Factory2=class{async create(e){return this.createWithConfig(e,{})}async createWithConfig(e,t){try{const r=(new Builder).withFs(e).withNamespaces(new RegularTemplateNamespace,new PartialTemplateNamespace,new ShortcodeTemplateNamespace);t.services?r.withServices(t.services):t.funcMap?r.withFuncMap(t.funcMap):r.withFuncMap(function(){const e=new Map;return newTemplateRegistry().registerCoreFunctions(e),e}());const i=await r.buildLookup().buildParser().buildExecutor().build();return await i.markReady(),i}catch(e){const t=e instanceof Error?e.message:String(e);throw new TemplateError(`Failed to create template engine: ${t}`,"FACTORY_CREATE_FAILED")}}async createWithServices(e,t){return this.createWithConfig(e,{services:t})}},Builder=class{funcMap=new Map;services;fs;templateNamespace;partialNamespace;shortcodeNamespace;lookup;parser;executor;withFs(e){return this.fs=e,this}withNamespaces(e,t,r){return this.templateNamespace=e,this.partialNamespace=t,this.shortcodeNamespace=r,this}withFuncMap(e){return this.funcMap=new Map([...this.funcMap,...e]),this}withServices(e){return this.services=e,this.funcMap=function(e){const t=new Map;return newTemplateRegistry().registerAllFunctions(t,e),t}(e),this}buildLookup(){const e=new BaseOf;return this.lookup=function(e,t){return new Lookup(e,t)}(e,this.funcMap),this}buildParser(){return this.parser=function(e=new Map){return new Parser(e)}(this.funcMap),this}buildExecutor(){return this.executor=new Executor,this}async build(){if(!this.fs)throw new TemplateError("File system is required","BUILDER_FS_REQUIRED");if(!this.templateNamespace)throw new TemplateError("Template namespace is required","BUILDER_TEMPLATE_NAMESPACE_REQUIRED");if(!this.partialNamespace)throw new TemplateError("Partial namespace is required","BUILDER_PARTIAL_NAMESPACE_REQUIRED");if(!this.shortcodeNamespace)throw new TemplateError("Shortcode namespace is required","BUILDER_SHORTCODE_NAMESPACE_REQUIRED");if(!this.lookup)throw new TemplateError("Lookup is required","BUILDER_LOOKUP_REQUIRED");if(!this.parser)throw new TemplateError("Parser is required","BUILDER_PARSER_REQUIRED");if(!this.executor)throw new TemplateError("Executor is required","BUILDER_EXECUTOR_REQUIRED");const e=(t=this.executor,r=this.lookup,i=this.parser,s=this.templateNamespace,n=this.partialNamespace,a=this.shortcodeNamespace,o=this.fs,new TemplateEngine(t,r,i,s,n,a,o));var t,r,i,s,n,a,o;!function(e){for(const t of engineDependentFunctions)try{t.updateEngine(e)}catch(e){log34.error(`❌ Failed to update function ${t.getFunctionName()}:`,e)}}(e);try{await e.loadTemplates()}catch(e){const t=e instanceof Error?e.message:String(e);throw new TemplateError(`Failed to load templates: ${t}`,"BUILDER_LOAD_TEMPLATES_FAILED")}return e}}}}),init_template3=__esm({"internal/domain/template/index.ts"(){init_type8(),init_type8(),init_baseof(),init_info(),init_namespace(),init_executor(),init_parser(),init_lookup(),init_template(),init_template2()}}),init_pagebuilder=__esm({"internal/domain/content/entity/pagebuilder.ts"(){init_pagecontent(),init_frontmatter(),init_kind(),init_section(),init_standalone(),init_log(),init_page(),init_pagemeta(),init_pagelayout(),init_paginator(),init_shortcode2(),init_template3(),log35=getDomainLogger("content",{component:"pagebuilder"}),PageBuilder=class{urlSvc;langSvc;taxonomySvc;templateSvc;pageMapper;taxonomy;term;section;standalone;converter;contentHub;source;sourceByte;kind;singular;term_;langIdx;fm;fmParser;c;renderableDocument=null;constructor(e,t,r,i,s,n,a,o,l,c,h){this.urlSvc=e,this.langSvc=t,this.taxonomySvc=r,this.templateSvc=i,this.pageMapper=null,this.taxonomy=n,this.term=a,this.section=o,this.standalone=l,this.converter=c,this.contentHub=h,this.source=null,this.sourceByte=new Uint8Array,this.kind="",this.singular="",this.term_="",this.langIdx=-1,this.fm=null,this.fmParser=null,this.c=null}withSource(e){const t=Object.assign(Object.create(Object.getPrototypeOf(this)),this);return t.reset(),t.source=e,t}withLangIdx(e){return this.langIdx=e,this}reset(){this.c=null,this.kind="",this.langIdx=-1}async build(){if(!this.source)throw new Error("source for page builder is nil");const e=await this.source.contentSource();this.sourceByte=e,await this.parse(e);const t=await this.buildInternal();return await this.render(t),t}async kindBuild(){if(!this.source)throw new Error("source for page builder is nil");return await this.parseKind(),-1===this.langIdx?await this.parseLanguageByDefault():await this.parseLanguageByIdx(this.langIdx),this.fm={path:"",lang:"",kind:"",title:"",description:"",weight:999,terms:{},params:{}},this.c=newContent(new Uint8Array),await this.buildInternal()}async buildInternal(){switch(this.kind){case getKindMain("home"):return await this.buildHome();case getKindMain("section"):return await this.buildSection();case getKindMain("page"):return await this.buildPage();case getKindMain("taxonomy"):return await this.buildTaxonomy();case getKindMain("term"):return await this.buildTerm();case getKindMain("404"):return await this.build404();case getKindMain("sitemap"):return await this.buildSitemap();default:throw new Error(`unknown kind "${this.kind}"`)}}async buildPage(){const e=await this.newPage(this.source,this.c);return await this.applyFrontMatter(e),e.pageMap=this.pageMapper,await this.buildOutput(e),await this.adaptPagination(e),e}async buildPageWithKind(e){const t=await this.newPage(this.source,this.c);if(await this.applyFrontMatter(t),t.pageMap=this.pageMapper,t.kind_=e,e===getKindMain("sitemap")||e===getKindMain("404")){const e=t.meta;e&&(e.list="never")}return await this.buildOutput(t),t}async applyFrontMatter(e){if(this.fm){e.title_=this.fm.title,e.description_=this.fm.description;const t=e.meta;t&&(t.weight=this.fm.weight,t.parameters=this.fm.params||{},this.fm.date&&(t.date=this.fm.date),void 0!==this.fm.organization&&(t.org=this.fm.organization),void 0!==this.fm.author&&(t.authorInfo=this.fm.author),void 0!==this.fm.menu&&(t.menuConfig=this.fm.menu))}}async buildHome(){const e=await this.buildPageWithKind(getKindMain("home"));return await this.buildPagination(e),e}async buildSection(){const e=await this.buildPageWithKind(getKindMain("section"));return await this.buildPagination(e),e}async build404(){const e=await this.buildPageWithKind(getKindMain("404"));return await this.adaptPagination(e),e}async buildSitemap(){const e=await this.buildPageWithKind(getKindMain("sitemap"));return await this.adaptPagination(e),e}async buildTaxonomy(){const e=this.taxonomy.getTaxonomy(this.source.file.paths().path()),t=e?e.singular():"",r=await this.newTaxonomy(this.source,this.c,t);return r.pageMap=this.pageMapper,await this.buildOutput(r),await this.buildPagination(r),r}async buildTerm(){const e=this.source.file.paths(),t=this.taxonomy.getTaxonomy(e.path()),r=t?t.singular():"",i=e.unnormalized().baseNameNoIdentifier(),s=await this.newTerm(this.source,this.c,r,i);return s.pageMap=this.pageMapper,await this.buildOutput(s),await this.buildPagination(s),s}async render(e){if(this.c?.lazyRendered)return void(this.c.lazyRender=async()=>{const t=await(this.renderableDocument?.render({maxSummaryLength:300,wordsPerMinute:200,shortcodeRenderer:this.createShortcodeRenderer(e)}));this.c?.updateWithContentResult(t)});log35.info(`Lazy rendering not enabled, rendering immediately for page: ${e.path()}`);const t=await(this.renderableDocument?.render({maxSummaryLength:300,wordsPerMinute:200,shortcodeRenderer:this.createShortcodeRenderer(e)}));this.c?.updateWithContentResult(t)}async parse(e){this.renderableDocument=await this.converter.prepareRender(e),this.c=newContent(e),this.c.toc=this.renderableDocument.toc(),this.fmParser=new FrontMatterParserImpl(this.renderableDocument.frontMatter(),this.langSvc,this.taxonomySvc),await this.parseFrontMatter(),await this.parseLanguage(),await this.parseKind(),await this.parseTerms()}async parseTerms(){this.fm&&this.fm.terms&&(this.term.terms=this.fm.terms)}async parseKind(){const e=this.source.file.paths();let t="";if(this.fm&&(t=this.fm.kind||""),""===t)switch(t=getKindMain("page"),e.baseNoLeadingSlash()){case PAGE_HOME_BASE:case"":t=getKindMain("home");break;case STANDALONE_PAGE_404_BASE:t=getKindMain("404");break;case STANDALONE_PAGE_SITEMAP_BASE:t=getKindMain("sitemap");break;default:if(this.source.file.isBranchBundle()){t=getKindMain("section");const r=this.taxonomy.getTaxonomy(e.path());this.taxonomy.isZero(r)||(t=this.taxonomy.isTaxonomyPath(e.path())?getKindMain("taxonomy"):getKindMain("term"))}}this.kind=t}async parseLanguageByDefault(){const e=this.langSvc.defaultLanguage(),t=await this.langSvc.getLanguageIndex(e);this.source.identity.lang=e,this.source.identity.langIdx=t}async parseLanguageByIdx(e){const t=this.langSvc.getLanguageByIndex(e);this.source.identity.lang=t,this.source.identity.langIdx=e}async parseLanguage(){const[e,t]=this.langSvc.getSourceLang(this.source.file.fileInfo().root());if(t){const t=this.langSvc.getLanguageIndex(e);return this.source.identity.lang=e,void(this.source.identity.langIdx=t)}await this.parseLanguageByDefault()}async parseFrontMatter(){this.fmParser?this.fm=await this.fmParser.parse(this.urlSvc.baseUrl()):this.fm={path:"",lang:"",kind:"",title:"",description:"",weight:999,terms:{},params:{}}}createShortcodeRenderer(e){return async t=>{if(!this.templateSvc)return log35.warn(`Template service not available for shortcode: ${t.name}`),"";try{return t.name?await this.doRenderShortcode(t,null,0,e):(log35.warn("Shortcode missing name"),"")}catch(e){return log35.error(`Error rendering shortcode "${t.name}":`,e),""}}}async doRenderShortcode(e,t,r,i){if(e.inline)return log35.warn("Inline shortcodes are not supported yet."),"";let s=new ShortcodeWithPage(e.params||{},"",i,t,e.name,"object"==typeof e.params&&!Array.isArray(e.params),e.ordinal||0,e.indentation||"",e.pos||0);if(e.inner&&e.inner.length>0){let n="";for(const t of e.inner)if("string"==typeof t)n+=t;else{if("object"!=typeof t||!("name"in t))return log35.error(`Illegal state on shortcode rendering of "${e.name}". Illegal type in inner data: ${typeof t}`),"";n+=await this.doRenderShortcode(t,s,r+1,i)}if(e.doMarkup)try{const r=await this.renderShortcodeMarkdown(i,n);s=new ShortcodeWithPage(e.params||{},r,i,t,e.name,"object"==typeof e.params&&!Array.isArray(e.params),e.ordinal||0,e.indentation||"",e.pos||0)}catch(e){throw new Error(`Failed to process inner content: ${e}`)}else s=new ShortcodeWithPage(e.params||{},n,i,t,e.name,"object"==typeof e.params&&!Array.isArray(e.params),e.ordinal||0,e.indentation||"",e.pos||0)}try{let t=await(this.templateSvc?.execute(e.name,s));if(!e.inner?.length&&e.indentation){const r=t?.split("\n");t=r?.map((t,r)=>0===r?t:e.indentation+t).join("\n")}return t||""}catch(t){if(t instanceof TemplateError&&"SHORTCODE_NOT_FOUND"===t.code)return e.rawContent;throw new Error(`Failed to process shortcode: ${t instanceof Error?t.message:String(t)}`)}}async renderShortcodeMarkdown(e,t){try{const r={document:e,documentID:e.path(),documentName:e.name(),filename:e.pageFile().filename()},i={ctx:{},src:(new TextEncoder).encode(t),renderTOC:!1,getRenderer:()=>null},s=await this.converter.convert(r,i);let n=(new TextDecoder).decode(s.bytes());return n.includes("\n")||(n=n.replace(/^<p>(.*)<\/p>\n$/,"$1")),n}catch(e){return log35.error("Error rendering shortcode markdown:",e),""}}async buildPagination(e){const t=new PaginatorManagerImpl({pageSize:()=>10,globalRegularPages:async()=>this.contentHub?await this.contentHub.globalRegularPages():[]},e);e.pagerManager=t}async adaptPagination(e){const t={current:()=>new PaginatorImpl([],0,10,e.path()).pagers()[0],setCurrent:t=>{throw new Error(`pagination not supported for this page: ${e.path()}`)},paginator:async()=>{throw new Error(`pagination not supported for this page: ${e.path()}`)},paginate:async t=>{throw new Error(`pagination not supported for this page: ${e.path()}`)}};e.pagerManager=t}async buildOutput(e){}async newPage(e,t){const r=new Meta(this.urlSvc.baseUrl(),"always",{},999,e.file.fileInfo().modTime()),i=new Layout;return new PageImpl(e,t,r,i,"",getKindMain("page"),this.pageMapper)}async newTaxonomy(e,t,r){const i=new Meta(this.urlSvc.baseUrl(),"always",{},999,e.file.fileInfo().modTime()),s=new Layout;return new TaxonomyPageImpl(e,t,i,s,r,r,getKindMain("taxonomy"),this.pageMapper)}async newTerm(e,t,r,i){const s=new Meta(this.urlSvc.baseUrl(),"always",{},999,e.file.fileInfo().modTime()),n=new Layout;return new TermPageImpl(e,t,s,n,r,i,i,getKindMain("term"),this.pageMapper)}}}});import*as path20 from"path";import*as filepath from"path";var log36,Term,init_taxonomy3=__esm({"internal/domain/content/entity/taxonomy.ts"(){init_pagetrees(),init_fileinfo2(),init_pagesource(),Taxonomy2=class{views;fsSvc;constructor(e,t){this.views=e,this.fsSvc=t}async assemble(e,t,r){for(const i of this.views){const s=this.pluralTreeKey(i.plural()),n=(e.get(s),newPageSource(newFileInfo2(this.fsSvc.newFileMetaInfo(s+"/_index.md")))),a=await t.withSource(n).withLangIdx(r).kindBuild();e.insertIntoValuesDimension(s,newPageTreesNode2(a))}}isTaxonomyPath(e){const t=this.getTaxonomy(e);return!!t&&e===path20.join(this.pluralTreeKey(t.plural()),"_index.md")}pluralTreeKey(e){return function(...e){let t="";return e.length>0&&(t=e[0],e.length>1&&(t=path20.join(...e))),t=t.replace(/^[\.\/ \s]+|[\.\/ \s]+$/g,""),t=filepath.posix.normalize(t.toLowerCase().replace(/[^\w\-_\/]/g,"")),""===t||"/"===t?"":("/"!==t[0]&&(t="/"+t),t)}(e)}getTaxonomy(e){for(const t of this.views)if(e.startsWith(this.pluralTreeKey(t.plural())))return t;return null}isZero(e){return!e||""===e.singular()}}}});function toStringSlicePreserveString(e){return e?Array.isArray(e)?e.map(e=>String(e)):"string"==typeof e?[e]:[String(e)]:null}function toInt(e){if("number"==typeof e)return Math.floor(e);if("string"==typeof e){const t=parseInt(e,10);if(isNaN(t))throw new Error(`cannot convert "${e}" to int`);return t}throw new Error(`cannot convert ${typeof e} to int`)}var SitePager,log38,Page2,init_term=__esm({"internal/domain/content/entity/term.ts"(){init_pagetrees(),init_fileinfo2(),init_pagesource(),init_frontmatter(),init_doctree(),init_log(),log36=getDomainLogger("content",{component:"term"}),Term=class{terms;fsSvc;constructor(e){this.terms={},this.fsSvc=e}async assemble(e,t,r,i){const s=new NodeShiftTreeWalker({tree:e,lockType:2,handle:async(s,n,a)=>{const[o,l]=n.getPage();if(!l)return[!1,null];for(const n of r.taxonomy.views){const a=toStringSlicePreserveString(getParam(o.params(),n.plural(),!1));if(!a)continue;const l=getParamToLower(o.params(),n.plural()+"_weight");let c=0;if(null==l||""===l)c=0;else try{c=toInt(l)}catch(e){log36.warn(`Unable to convert taxonomy weight ${l} to int for "${o.paths().path()}"`)}for(let l=0;l<a.length;l++){const h=a[l];if(""===h)continue;const u="/"+n.plural()+"/"+h;try{const a=newFileInfo2(this.fsSvc.newFileMetaInfo(u+"/_index.md")),g=a.paths(),d=newPageSource(a),p=await r.withSource(d).withLangIdx(i).kindBuild();e.insertIntoValuesDimension(g.base(),newPageTreesNode2(p));const m=e.get(g.base());if(m){const[e,t]=m.getPage();if(!t)return[!1,null];const r=e;r.term=h,r.singular=n.singular()}let f=s;""===f&&(f="/");const y=g.base()+f,[w,S]=m.getPage();if(!S)return[!1,null];t.insert(y,new WeightedTermTreeNode(newPageTreesNode2(o),{page:w,ordinal:l,weight:c,Weight:()=>c,Ordinal:()=>l}))}catch(e){return[!1,e]}}}return[!1,null]}});try{return await s.walk(),null}catch(e){return e}}}}}),init_content3=__esm({"internal/domain/content/index.ts"(){init_type4(),init_hub(),init_kind(),init_identity(),init_fileinfo2(),init_sort(),init_frontmatter(),init_classifier(),init_content2(),init_converter(),init_pagebuilder(),init_pagetrees(),init_pagemap(),init_taxonomy3(),init_term(),init_section(),init_standalone(),init_translator()}}),init_pager=__esm({"internal/domain/site/entity/pager.ts"(){init_log(),getDomainLogger("site",{component:"pager"}),SitePager=class e{page;pager;constructor(e,t){this.page=e,this.pager=t}pageNumber(){return this.pager.pageNumber()}totalPages(){return this.pager.totalPages()}url(){return this.pager.url()}pages(){return this.pager.pages()}allPages(){return this.pager.allPages()}pagers(){return this.pager.pagers()}first(){return this.pager.first()}last(){return this.pager.last()}hasPrev(){return this.pager.hasPrev()}prev(){return this.pager.prev()}hasNext(){return this.pager.hasNext()}next(){return this.pager.next()}get PageNumber(){return this.pageNumber()}get TotalPages(){return this.totalPages()}get URL(){let e=this.url();return e.startsWith("/")&&(e=e.slice(1)),this.page.Site.getURL().relURL(e)}get HasPrev(){return this.hasPrev()}get HasNext(){return this.hasNext()}get First(){const t=this.first();return t?new e(this.page,t):null}get Last(){const t=this.last();return t?new e(this.page,t):null}get Prev(){const t=this.prev();return t?new e(this.page,t):null}get Next(){const t=this.next();return t?new e(this.page,t):null}get Pagers(){return this.pagers().map(t=>new e(this.page,t))}get Pages(){const e=this.pages();return this.page.sitePages(e)}get AllPages(){const e=this.pager.allPages();return this.page.sitePages(e)}}}});import path21 from"path";var BaseURL,URL2,log39,WeightedPage,WeightedPages,Taxonomy3,OrderedTaxonomyEntry,OrderedTaxonomy,TaxonomyList,TaxonomiesBuilder,init_page2=__esm({"internal/domain/site/entity/page.ts"(){init_log(),init_pager(),log38=getDomainLogger("site",{component:"page"}),Page2=class e{tmplSvc;langSvc;publisher;contentPage;pageOutput=null;site;resources=[];_paginator=null;_processedContent=null;_precomputedData={backlinks:null,tableOfContents:null,summary:null};constructor(e,t,r,i,s){this.tmplSvc=e,this.langSvc=t,this.publisher=r,this.contentPage=i,this.site=s}async precomputeTemplateData(){try{await Promise.all([this.precomputeBacklinks(),this.precomputeTableOfContents(),this.precomputeSummary()])}catch(e){log38.warn(`Failed to precompute data for ${this.paths().path()}: ${e}`)}}async precomputeBacklinks(){try{this._precomputedData.backlinks=await this.Backlinks()}catch(e){log38.debug(`Failed to precompute backlinks: ${e}`)}}async precomputeTableOfContents(){try{this._precomputedData.tableOfContents=this.TableOfContents}catch(e){log38.debug(`Failed to precompute TOC: ${e}`)}}async precomputeSummary(){try{this._precomputedData.summary=await this.Summary()}catch(e){log38.debug(`Failed to precompute summary: ${e}`)}}async processResources(e){this.resources=e}async render(){try{await this.renderResources(),await this.renderPage()}catch(e){log38.error(`Failed to render page ${this.paths().path()}: ${e}`)}}getPageOutput(){return this.pageOutput||(this.pageOutput=this.output()),this.pageOutput}async renderPage(){const e=this.layouts(),{preparer:t,found:r}=await this.tmplSvc.lookupLayout(e);if(!r)return void log38.warn(`Failed to find layout: ${e.join(",")} for page ${this.paths().path()}`);const i=[];let s=this.getPageOutput().targetPrefix();s=this.site.getLanguage().getCurrentLanguage()===s&&s===this.langSvc.defaultLanguage()?"":this.site.getLanguage().getCurrentLanguage(),i.push(path21.join(s,this.getPageOutput().targetFilePath())),await this.renderAndWritePage(t,i);const n=await this.current();if(n){let e=n.next();for(;e;){this.setCurrent(e);const r=[path21.join(s,e.url(),this.getPageOutput().targetFileBase())];await this.renderAndWritePage(t,r),e=e.next()}}}async renderAndWritePage(e,t){try{const r=await this.tmplSvc.executeWithContext(e,this);await this.publisher.publishSource(r,...t)}catch(e){throw this.errorf(e,"failed to publish page")}}async renderResources(){for(const e of this.resources){const t=[];let r=this.getPageOutput().targetPrefix();r=this.site.getLanguage().getCurrentLanguage()===r&&r===this.langSvc.defaultLanguage()?"":this.site.getLanguage().getCurrentLanguage();let i=e.path();t.push(path21.join(r,i));let s=null;try{const r=()=>e.pageFile().open();if(s=await r(),!s)throw new Error("Failed to open resource stream");let i;i="function"==typeof s.read?new ReadableStream({async start(e){try{const t=new Uint8Array(8192);for(;;){const r=await s.read(t);if(0===r.bytesRead)break;e.enqueue(t.slice(0,r.bytesRead))}e.close()}catch(t){e.error(t)}}}):new ReadableStream({start(e){e.close()}}),await this.publisher.publishFiles(i,...t)}catch(e){throw this.errorf(e,"failed to publish page resources")}finally{if(s)try{await s.close()}catch(e){log38.warn(`Failed to close resource stream: ${e}`)}}}}errorf(e,t,...r){const i=[this.pageIdentity().pageLanguage(),this.paths().path(),...r],s=`[%s] page "%s": ${t}: %s`,n=this.sprintf(s,...i,e.message||e);return new Error(n)}sprintf(e,...t){let r=0;return e.replace(/%s/g,()=>t[r++]||"")}clone(){const t=new e(this.tmplSvc,this.langSvc,this.publisher,this.contentPage,this.site);return t.resources=[...this.resources],t.pageOutput=this.pageOutput,t}pageIdentity(){return this.contentPage.pageIdentity()}pageFile(){return this.contentPage.pageFile()}staleVersions(){return this.contentPage.staleVersions()}section(){return this.contentPage.section()}paths(){return this.contentPage.paths()}path(){return this.contentPage.path()}slug(){return this.contentPage.slug()}file(){return this.contentPage.file()}name(){return this.contentPage.name()}title(){return this.contentPage.title()}kind(){return this.contentPage.kind()}scratch(){return this.contentPage.scratch()}get Scratch(){return this.contentPage.scratch()}IsAncestor(e){return this.contentPage.isAncestor(e.contentPage)}get Title(){return this.title()}get Section(){return this.contentPage.section()}get LinkTitle(){return this.title()}get IsSection(){return this.contentPage.isSection()}get IsPage(){return this.contentPage.isPage()}get Content(){return this.getPageOutput().content()}async WikilinkContent(){if(null!==this._processedContent)return this._processedContent;const e=await this.getPageOutput().content();return e?(this._processedContent=await this.site.ProcessWikilinks(this.slug(),e),this._processedContent):e}async Summary(){if(null!==this._precomputedData.summary)return this._precomputedData.summary;const e=await this.contentPage.output().summary();return this._precomputedData.summary=e,e}async ReadingTime(){return await this.getPageOutput().readingTime()}async WordCount(){return await this.getPageOutput().wordCount()}async Backlinks(){if(null!==this._precomputedData.backlinks)return this._precomputedData.backlinks;const e=this.site.GetBacklinks(this.slug()),t=[],r=await this.site.RegularPages();for(const i of e){const e=r.find(e=>e.slug()===i);e&&t.push(e)}return this._precomputedData.backlinks=t,t}OutgoingLinks(){const e=this.site.getPageGraph();return e?e.getOutgoingLinks(this.slug()):[]}get Description(){return this.description()}get Date(){return this.pageDate()}get LocalDate(){return this.pageDate().toLocaleDateString()}get RelPermalink(){let e;if(this.pageIdentity().pageLanguage()===this.langSvc.defaultLanguage())e=this.getPageOutput().targetFilePath();else{const t=this.getPageOutput().targetPrefix(),r=this.getPageOutput().targetFilePath();e=this.pathJoin(t,r)}return e.startsWith("/")&&(e=e.slice(1)),this.site.getURL().relURL(e)}get GitInfo(){return{}}get File(){return{BaseFileName:this.contentPage.file().baseFileName(),OriginalBaseName:this.contentPage.file().originalBaseFileName(),Dir:this.contentPage.file().dir()}}isHome(){return this.contentPage.isHome()}get IsHome(){return this.isHome()}isPage(){return this.contentPage.isPage()}isSection(){return this.contentPage.isSection()}isAncestor(e){return this.contentPage.isAncestor(e)}eq(e){return this.contentPage.eq(e)}isBundled(){return this.contentPage.isBundled()}layouts(){return this.contentPage.layouts()}output(){return this.contentPage.output()}pageOutputs(){return[this.contentPage.output()]}truncated(){return this.contentPage.truncated()}get Truncated(){return this.contentPage.truncated()}parent(){return this.contentPage.parent()}pages(){return this.contentPage.pages()}isStale(){return this.contentPage.pageIdentity().isStale()}clearStale(){this.contentPage.pageIdentity().clearStale()}prevInSection(){return this.contentPage.prevInSection()}nextInSection(){return this.contentPage.nextInSection()}sections(e){return this.contentPage.sections(e)}regularPages(){return this.contentPage.regularPages()}regularPagesRecursive(){return this.contentPage.regularPagesRecursive()}terms(e,t){return this.contentPage.terms(e,t)}isTranslated(){return this.contentPage.isTranslated()}translations(){return this.contentPage.translations()}rawContent(){return this.contentPage.rawContent()}description(){return this.contentPage.description?this.contentPage.description():""}params(){return this.contentPage.params?this.contentPage.params():{}}pageBaseUrl(){return this.contentPage.pageBaseUrl()?this.contentPage.pageBaseUrl():""}pageWeight(){return this.contentPage.pageWeight?this.contentPage.pageWeight():0}pageDate(){return this.contentPage.pageDate?this.contentPage.pageDate():new Date}publishDate(){return this.contentPage.publishDate?this.contentPage.publishDate():new Date}get PublishDate(){return this.publishDate()}async relatedKeywords(e){return this.contentPage.relatedKeywords?await this.contentPage.relatedKeywords(e):[]}shouldList(e){return!this.contentPage.shouldList||this.contentPage.shouldList(e)}shouldListAny(){return!this.contentPage.shouldListAny||this.contentPage.shouldListAny()}noLink(){return!!this.contentPage.noLink&&this.contentPage.noLink()}organization(){return this.contentPage.organization?this.contentPage.organization():void 0}author(){return this.contentPage.author?this.contentPage.author():void 0}menu(){return this.contentPage.menu?this.contentPage.menu():void 0}current(){return this.contentPage.current()}setCurrent(e){this.contentPage.setCurrent(e)}posOffset(e){return this.contentPage.posOffset(e)}paginator(){return this.contentPage.paginator()}async paginate(e){return this.contentPage.paginate(e)}get Plain(){return this.rawContent()}get TableOfContents(){if(null!==this._precomputedData.tableOfContents)return this._precomputedData.tableOfContents;const e=this.getPageOutput().tableOfContents();return this._precomputedData.tableOfContents=e,e}get Params(){return this.params()}get Site(){return this.site}get Sites(){return{First:this.site,Default:this.site}}get Lastmod(){return this.contentPage.pageDate?this.contentPage.pageDate():null}get Sitemap(){return{ChangeFreq:"weekly",Priority:.5,Filename:"sitemap.xml"}}get IsTranslated(){return this.isTranslated()}async Paginator(){return this._paginator||await this.setupCurrentPaginator(),this._paginator}async Paginate(e){try{const t=e.map(e=>e.contentPage),r=await this.contentPage.paginate(t);return r&&(this._paginator=new SitePager(this,r)),this._paginator}catch(e){return log38.error("Error during pagination:",e),null}}async setupCurrentPaginator(){try{const e=await this.contentPage.paginator();this._paginator=e?new SitePager(this,e):null}catch(e){log38.error("Error initializing Paginator:",e),this._paginator=null}}get Language(){return{Lang:this.pageIdentity().pageLanguage(),LanguageName:this.langSvc.getLanguageName(this.pageIdentity().pageLanguage()),Title:this.title(),Weight:this.pageWeight()}}get Permalink(){return this.RelPermalink}sitePages(e){const t=[];for(const r of e){const e=this.sitePage(r);e&&t.push(e)}return t}sitePage(t){try{return null===t?(log38.warn(`Invalid content page provided: ${t}`),null):new e(this.tmplSvc,this.langSvc,this.publisher,t,this.site)}catch(e){return log38.error(`Error creating site page: ${e}`),null}}pathJoin(...e){return e.filter(e=>e&&e.length>0).map(e=>e.replace(/^\/+|\/+$/g,"")).filter(e=>e.length>0).join("/")}joinURL(e,t){return e?t?(e.endsWith("/")&&(e=e.slice(0,-1)),t.startsWith("/")||(t="/"+t),e+t):e:t}async Translations(){const e=await this.translations();return Array.isArray(e)?e.map(e=>this.sitePage(e)).filter(e=>null!==e):[]}async GetTerms(e){const t=await this.terms(this.site.getLanguage().currentLanguageIndex(),e);return Array.isArray(t)?t.map(e=>this.sitePage(e)).filter(e=>null!==e):[]}async Pages(){return await this.getSitePages()}get Page(){return this.contentPage}get Kind(){return this.kind()}get Type(){if("home"===this.kind())return"page";if("page"===this.kind()){const e=this.section();if(e&&e.length>0)return e}return"page"}get Parent(){return this.sitePage(this.contentPage.parent())}async getSitePages(){const e=await this.contentPage.pages();return!e||Array.isArray(e)&&0===e.length?[]:this.sitePages(e)}}}}),init_baseurl=__esm({"internal/domain/site/valueobject/baseurl.ts"(){BaseURL=class e{url;withPath;withPathNoTrailingSlash;withoutPath;basePath;basePathNoTrailingSlash;isRelative;constructor(e,t=!1){if(this.url=e,this.isRelative=t,this.withPath=e.toString(),this.withPathNoTrailingSlash=this.withPath.replace(/\/$/,""),t)this.withoutPath="/";else{const t=new URL(e.toString());t.pathname="",this.withoutPath=t.toString().replace(/\/$/,"")}this.basePath=e.pathname,this.basePathNoTrailingSlash=this.basePath.replace(/\/$/,"")}static fromString(t){try{t&&"/"!==t||(t="/");const r=t.trim();if(r.startsWith("/")&&!r.startsWith("//")){const t=new URL(r,"http://localhost");return t.pathname.endsWith("/")||(t.pathname+="/"),new e(t,!0)}if(r.startsWith("//")){const t=new URL("https:"+r);return t.pathname.endsWith("/")||(t.pathname+="/"),new e(t)}if(r.includes("://")){const t=new URL(r);if(!["http:","https:"].includes(t.protocol))throw new Error(`Unsupported protocol: ${t.protocol}. Only http and https are supported.`);return t.pathname.endsWith("/")||(t.pathname+="/"),new e(t)}if(r.includes(":")&&!r.includes("/")){const e=r.indexOf(":"),t=r.substring(0,e+1);throw new Error(`Unsupported protocol: ${t}. Only http and https are supported.`)}const i=new URL("https://"+r);return i.pathname.endsWith("/")||(i.pathname+="/"),new e(i)}catch(e){throw new Error(`Invalid URL: ${e?.message||"Unknown error"}`)}}getRoot(e){return this.isRelative?this.basePath:e.startsWith("/")?this.withoutPath:this.withPath}toString(){return this.isRelative?this.basePath:this.withPath}path(){return this.url.pathname}port(){return this.url.port?parseInt(this.url.port):0}hostURL(){return this.isRelative?"/":this.toString().replace(this.path(),"")}protocol(){return this.url.protocol}host(){return this.url.host}hostname(){return this.url.hostname}getURL(){return new URL(this.url.toString())}withProtocol(t){if(this.isRelative)throw new Error("Cannot change protocol of relative URL");const r=this.getURL();let i=t;const s=i.endsWith("://"),n=i.endsWith(":");if(s?i=i.slice(0,-3):n&&(i=i.slice(0,-1)),n&&!r.pathname)throw new Error(`cannot determine BaseURL for protocol ${t}`);return r.protocol=i,e.fromString(r.toString())}withPort(t){if(this.isRelative)throw new Error("Cannot set port on relative URL");const r=this.getURL();return r.port=t.toString(),e.fromString(r.toString())}isRelativeURL(){return this.isRelative}isAbsoluteURL(){return!this.isRelative}}}}),init_text=__esm({"pkg/text/index.ts"(){}}),init_url=__esm({"internal/domain/site/entity/url.ts"(){init_baseurl(),init_paths2(),init_text(),URL2=class e{base;canonical;baseURL=null;constructor(e,t=!1){this.base=e,this.canonical=t,this.setup()}setup(){try{this.baseURL=BaseURL.fromString(this.base)}catch(e){throw new Error(e?.message||"Failed to setup URL")}}isAbsURL(e){return e.startsWith("http://")||e.startsWith("https://")?[!0,null]:[/^[a-zA-Z][a-zA-Z\d+\-.]*:/.test(e),null]}startWithBaseUrlRoot(e){return!!this.baseURL&&e.startsWith(this.baseURL.getRoot(e))}isProtocolRelPath(e){return e.startsWith("//")}trimBaseUrlRoot(e){if(!this.baseURL)return e;const t=this.baseURL.getRoot(e);return e.endsWith(t)?e.slice(0,-t.length):e}addContextRoot(e){if(!this.baseURL)return e;let t=e;return this.canonical||(r=this.baseURL.getRoot(e),i=e,t=!r||i.startsWith(r)?i:function(...e){return e.filter(Boolean).join("/").replace(/\/+/g,"/").replace(/\/$/,"")}(r,i)),t;var r,i}handleRootSuffix(e,t){return this.baseURL?(""===e&&this.baseURL.getRoot(e).endsWith("/")&&(t+="/"),t):t}handlePrefix(e){return e.startsWith("/")||(e="/"+e),e}relURL(e){if(!e)return this.baseURL?this.baseURL.basePath:"";const[t,r]=this.isAbsURL(e);if(r)return e;if(t||this.isProtocolRelPath(e))return e;if(!this.baseURL)return e;let i=e;if(e.startsWith("/"))return this.baseURL.isRelativeURL()?e:this.baseURL.withoutPath+e;if(i=this.baseURL.isRelativeURL()?(this.baseURL.basePath.endsWith("/")?this.baseURL.basePath:this.baseURL.basePath+"/")+e:(this.baseURL.withPath.endsWith("/")?this.baseURL.withPath:this.baseURL.withPath+"/")+e,i.includes("://")){const e=i.indexOf("://"),t=i.substring(0,e+3),r=i.substring(e+3);i=t+r.replace(/\/+/g,"/")}else i=i.replace(/\/+/g,"/");return i}absURL(e,t=!1,r=""){const[i,s]=this.isAbsURL(e);if(s)return e;if(i||this.isProtocolRelPath(e))return e;if(!this.baseURL)return e;const n=this.baseURL.getRoot(e);if(t&&r){let t=!1,i=e;if(e.startsWith("/")&&(i=e.slice(1)),t=i===r||i.startsWith(r+"/"),!t){const t=""===e||e.endsWith("/");e=this.joinPaths(r,e),t&&(e+="/")}}return function(e,t){const r=`${e.replace(/\/$/,"")}/${t.replace(/^\//,"")}`;try{return new URL(r)}catch{return new URL("http://"+r)}}(n,e).toString()}urlize(e){return this.urlEscape(this.makePathSanitized(e))}makePathSanitized(e){return this.makePath(e).toLowerCase()}urlEscape(t){try{if(/^[a-zA-Z][a-zA-Z\d+\-.]*:/.test(t))return new e(t).toString();const r=t.match(/^([^?#]*)(\?[^#]*)?(#.*)?$/);if(!r)return encodeURI(t);const[,i="",s="",n=""]=r;return encodeURI(i)+(s||"")+(n||"")}catch{return encodeURI(t)}}makePath(e){let t=function(e){return e.replace(/[\s\t\n\r]+/g,"-").replace(/[^\w\-_]/g,"").replace(/-+/g,"-").replace(/^-|-$/g,"")}(e);return t=t.normalize("NFD").replace(/[\u0300-\u036f]/g,""),t}basePathNoSlash(){return this.baseURL?this.baseURL.basePathNoTrailingSlash:""}joinPaths(...e){return e.filter(Boolean).join("/").replace(/\/+/g,"/").replace(/\/$/,"")}}}}),taxonomies_builder_exports={};__export(taxonomies_builder_exports,{OrderedTaxonomy:()=>OrderedTaxonomy,OrderedTaxonomyEntry:()=>OrderedTaxonomyEntry,TaxonomiesBuilder:()=>TaxonomiesBuilder,Taxonomy:()=>Taxonomy3,TaxonomyList:()=>TaxonomyList,WeightedPage:()=>WeightedPage,WeightedPages:()=>WeightedPages});var Menu2,Menus,init_taxonomies_builder=__esm({"internal/domain/site/entity/taxonomies-builder.ts"(){init_log(),log39=getDomainLogger("site",{component:"taxonomies-builder"}),WeightedPage=class{page;ordinalWeightPage;constructor(e,t){this.page=e,this.ordinalWeightPage=t}get Page(){return this.page}weight(){return this.ordinalWeightPage.weight()}ordinal(){return this.ordinalWeightPage.ordinal()}owner(){return this.ordinalWeightPage.owner()}get Permalink(){return this.page.Permalink}get RelPermalink(){return this.page.RelPermalink}get Title(){return this.page.Title}},WeightedPages=class extends Array{page(){return 0===this.length?(log39.error("Page called on empty WeightedPages"),null):this[0]}get Page(){return this.page()}pages(){return Array.from(this)}sortByWeight(){this.stableSort((e,t)=>e.weight()-t.weight())}count(){return this.length}get Count(){return this.count()}stableSort(e){const t=this.map((e,t)=>({item:e,index:t}));t.sort((t,r)=>{const i=e(t.item,r.item);return 0!==i?i:t.index-r.index}),this.splice(0,this.length,...t.map(e=>e.item))}},Taxonomy3=class{terms=new Map;get(e){return this.terms.get(e)}set(e,t){this.terms.set(e,t)}has(e){return this.terms.has(e)}keys(){return Array.from(this.terms.keys())}values(){return Array.from(this.terms.values())}get Values(){return this.terms}entries(){return Array.from(this.terms.entries())}size(){return this.terms.size}byCount(){const e=this.taxonomyArray();return e.sort((e,t)=>{const r=e.weightedPages.length,i=t.weightedPages.length;return r===i?e.name.localeCompare(t.name):i-r}),new OrderedTaxonomy(e)}taxonomyArray(){const e=[];for(const[t,r]of this.terms.entries())e.push(new OrderedTaxonomyEntry(t,r));return e}},OrderedTaxonomyEntry=class{name;weightedPages;constructor(e,t){this.name=e,this.weightedPages=t}count(){return this.weightedPages.count()}term(){return this.name}},OrderedTaxonomy=class extends Array{constructor(e){super(),e&&this.push(...e)}getOneOPage(){return 0===this.length?null:this[0].weightedPages.page()}},TaxonomyList=class{taxonomies=new Map;get(e){return this.taxonomies.get(e)}set(e,t){this.taxonomies.set(e,t)}has(e){return this.taxonomies.has(e)}keys(){return Array.from(this.taxonomies.keys())}values(){return Array.from(this.taxonomies.values())}get Values(){return this.taxonomies}entries(){return Array.from(this.taxonomies.entries())}size(){return this.taxonomies.size}},TaxonomiesBuilder=class{contentService;constructor(e){this.contentService=e}async buildTaxonomiesForLanguage(e,t){const r=new TaxonomyList;try{return await this.contentService.walkTaxonomies(e,async(e,i,s)=>{r.has(e)||r.set(e,new Taxonomy3);const n=r.get(e);n.has(i)||n.set(i,new WeightedPages);const a=await t.siteWeightedPage(s);n.get(i).push(a)}),r}catch(e){throw log39.error(`Failed to create taxonomies: ${e}`),e}}}}});function newEmptyMenus(){return new Menus({})}var init_menu=__esm({"internal/domain/site/valueobject/menu.ts"(){init_log(),getDomainLogger("site",{component:"menu"}),Menu2=class e{_title;_url;_children;_weight;_identifier;constructor(e){this._title=e.title,this._url=e.url,this._children=e.children||[],this._weight=e.weight||0,this._identifier=e.identifier||this._url}title(){return this._title}get Title(){return this.title()}url(){return this._url}get URL(){return this.url()}children(){return[...this._children]}get Children(){return this.children()}weight(){return this._weight}identifier(){return this._identifier}hasChildren(){return this._children.length>0}get HasChildren(){return this.hasChildren()}addChild(t){const r=[...this._children,t];return new e({title:this._title,url:this._url,children:r,weight:this._weight,identifier:this._identifier})}toJSON(){return{title:this._title,url:this._url,weight:this._weight,children:this._children.map(e=>e.toJSON())}}withChildren(t){return new e({title:this._title,url:this._url,children:t,weight:this._weight,identifier:this._identifier})}},Menus=class{_nav;_footer;constructor(e={}){this._nav=e.nav?this.sortMenus([...e.nav]):[],this._footer=e.footer?this.sortMenus([...e.footer]):[]}nav(){return[...this._nav]}get Nav(){return this.nav()}footer(){return[...this._footer]}get Footer(){return this.footer()}sortMenus(e){return e.sort((e,t)=>{if(e.weight()!==t.weight())return 0===t.weight()?-1:0===e.weight()?1:e.weight()-t.weight();const r=e.title().localeCompare(t.title());return 0!==r?r:e.identifier().localeCompare(t.identifier())})}toJSON(){return{nav:this._nav.map(e=>e.toJSON()),footer:this._footer.map(e=>e.toJSON())}}}}});import{slug as slugAnchor}from"github-slugger";function splitAnchor2(e){let[t,r]=e.split("#",2);return t.endsWith(".pdf")?[t,void 0===r?"":`#${r}`]:(r=void 0===r?"":"#"+slugAnchor(r),[t,r])}function simplifySlug(e){const t=stripSlashes2((endsWith2(r=e,"index")&&(r=r.slice(0,-5)),r),!0);var r;return 0===t.length?"/":t}function pathToRoot(e){let t=e.split("/").filter(e=>""!==e).slice(0,-1).map(e=>"..").join("/");return 0===t.length&&(t="."),t}function joinSegments(...e){if(0===e.length)return"";let t=e.filter(e=>""!==e&&"/"!==e).map(e=>stripSlashes2(e)).join("/");return e[0].startsWith("/")&&(t="/"+t),e[e.length-1].endsWith("/")&&(t+="/"),t}function transformLink(e,t,r){let i=function(e){let[t,r]=splitAnchor2(decodeURI(e));const i=isFolderPath(t);let s=t.split("/").filter(e=>e.length>0),n=s.filter(isRelativeSegment).join("/");const a=simplifySlug(function(e){let t=(r=e=stripSlashes2(e),r.match(/\.[A-Za-z0-9]+$/)?.[0]);var r;const i=e.replace(new RegExp(t+"$"),"");[".md",".html",void 0].includes(t)&&(t="");let s=function(e){return e.split("/").map(e=>e.replace(/\s/g,"-").replace(/&/g,"-and-").replace(/%/g,"-percent").replace(/\?/g,"").replace(/#/g,"")).join("/").replace(/\/$/,"")}(i);return endsWith2(s,"_index")&&(s=s.replace(/_index$/,"index")),s+t}(s.filter(e=>!isRelativeSegment(e)&&""!==e).join("/"))),o=i?"/":"";return""===(l=joinSegments(stripSlashes2(n),stripSlashes2(a)))&&(l="."),l.startsWith(".")||(l=joinSegments(".",l)),l+o+r;var l}(t);if("relative"===r.strategy)return i;{const t=isFolderPath(i)?"/":"",s=stripSlashes2(i.slice(1));let[n,a]=splitAnchor2(s);if("shortest"===r.strategy){const t=r.allSlugs.filter(e=>{const t=e.split("/").at(-1);return n.toLowerCase()===t?.toLowerCase()});if(1===t.length)return function(e,t){return joinSegments(pathToRoot(e),simplifySlug(t))}(e,t[0])+a}return joinSegments(pathToRoot(e),s)+t}}function isFolderPath(e){return e.endsWith("/")||endsWith2(e,"index")||endsWith2(e,"index.md")||endsWith2(e,"index.html")}function endsWith2(e,t){return e===t||e.endsWith("/"+t)}function isRelativeSegment(e){return/^\.{0,2}$/.test(e)}function stripSlashes2(e,t){return e.startsWith("/")&&(e=e.substring(1)),!t&&e.endsWith("/")&&(e=e.slice(0,-1)),e}var log41,PageGraph,log42,defaultOptions,HtmlLinkProcessor,init_path3=__esm({"internal/domain/site/valueobject/path.ts"(){}}),init_pagegraph=__esm({"internal/domain/site/entity/pagegraph.ts"(){init_path3(),init_log(),log41=getDomainLogger("site",{component:"PageGraph"}),PageGraph=class{allSlugs;outgoingLinks=new Map;constructor(e){this.allSlugs=[...e],log41.info(`PageGraph initialized with ${e.length} items (pages + resources)`)}registerOutgoingLinks(e,t){const r=simplifySlug(e);this.outgoingLinks.set(r,t)}getBacklinks(e){const t=simplifySlug(e),r=[];for(const[e,i]of this.outgoingLinks.entries())i.includes(t)&&r.push(e);return r}getAllSlugs(){return[...this.allSlugs]}hasSlug(e){return this.allSlugs.includes(e)}resolveLink(e,t,r){return transformLink(e,t,{strategy:r,allSlugs:this.allSlugs})}getOutgoingLinks(e){const t=simplifySlug(e);return this.outgoingLinks.get(t)||[]}getAllOutgoingLinks(){return new Map(this.outgoingLinks)}getStats(){return{totalPages:this.allSlugs.length,slugs:[...this.allSlugs]}}}}});import{unified}from"unified";import rehypeParse from"rehype-parse";import rehypeStringify from"rehype-stringify";import{visit}from"unist-util-visit";import isAbsoluteUrl from"is-absolute-url";import path22 from"path";var log43,pageFilter,init_html_link_processor=__esm({"internal/domain/site/service/html-link-processor.ts"(){init_path3(),init_log(),log42=getDomainLogger("site",{component:"HtmlLinkProcessor"}),defaultOptions={markdownLinkResolution:"shortest",prettyLinks:!0,openLinksInNewTab:!1,lazyLoad:!1,externalLinkIcon:!0},HtmlLinkProcessor=class{constructor(e,t={}){this.graph=e,this.options={...defaultOptions,...t}}options;async processLinks(e,t){if(!t||"string"!=typeof t)return log42.error("[HtmlLinkProcessor] Invalid HTML input: "+typeof t),{html:t||"",outgoingLinks:[]};const r=this.options,i=simplifySlug(e),s=new Set,n=unified().use(rehypeParse,{fragment:!0}).use(()=>t=>{visit(t,"element",t=>{if("a"===t.tagName&&t.properties){const n=t.properties.dataWikilink||t.properties.dataSlug,a="string"==typeof t.properties.href;if(!a&&!n)return;let o;o=!a&&n?t.properties.dataWikilink||t.properties.dataSlug:t.properties.href;const l=t.properties.className??[],c=isAbsoluteUrl(o,{httpOnly:!1});l.includes("external")||l.includes("internal")||l.push(c?"external":"internal"),c&&r.externalLinkIcon&&t.children.push({type:"element",tagName:"svg",properties:{"aria-hidden":"true",class:"external-icon",style:"max-width:0.8em;max-height:0.8em",viewBox:"0 0 512 512"},children:[{type:"element",tagName:"path",properties:{d:"M320 0H288V64h32 82.7L201.4 265.4 178.7 288 224 333.3l22.6-22.6L448 109.3V192v32h64V192 32 0H480 320zM32 32H0V64 480v32H32 456h32V480 352 320H424v32 96H64V96h96 32V32H160 32z"},children:[]}]}),1===t.children.length&&"text"===t.children[0].type&&t.children[0].value!==o&&l.push("alias"),t.properties.className=l,c&&r.openLinksInNewTab&&(t.properties.target="_blank");const h=!(isAbsoluteUrl(o,{httpOnly:!1})||o.startsWith("#"));if(h){const n=transformLink(e,o,{strategy:r.markdownLinkResolution,allSlugs:this.graph.getAllSlugs()}),a=new URL(n,"https://base.com/"+stripSlashes2(i,!0)).pathname;let[l,c]=splitAnchor2(a);l.endsWith("/")&&(l+="index");const h=decodeURIComponent(stripSlashes2(l,!0)),u=simplifySlug(h);s.add(u);let g=n;if(g.startsWith("./")&&(g=g.slice(2)),g.startsWith("../")){const t=(g.match(/\.\.\//g)||[]).length,r=e.split("/").filter(e=>e).slice(0,-1),i=g.replace(/\.\.\//g,""),s=r.slice(0,r.length-t);i&&s.push(i),g=s.join("/")}g=r.baseURL?`${r.baseURL}/${g}`:`/${g}`;const[d,p]=splitAnchor2(g);let m=d;m.endsWith(".html")||m.endsWith("/")||(m+=".html"),g=m+p,o=t.properties.href=g,t.properties["data-slug"]=h}r.prettyLinks&&h&&1===t.children.length&&"text"===t.children[0].type&&!t.children[0].value.startsWith("#")&&(t.children[0].value=path22.basename(t.children[0].value))}if(["img","video","audio","iframe"].includes(t.tagName)&&t.properties&&"string"==typeof t.properties.src&&(r.lazyLoad&&(t.properties.loading="lazy"),!isAbsoluteUrl(t.properties.src,{httpOnly:!1}))){let i=t.properties.src;i=t.properties.src=transformLink(e,i,{strategy:r.markdownLinkResolution,allSlugs:this.graph.getAllSlugs()}),t.properties.src=i}})}).use(rehypeStringify),a=await n.process(t);return{html:String(a),outgoingLinks:Array.from(s)}}}}});function shouldProcessPage(e,t){return pageFilter.shouldProcess(e,t)}var log44,Site,Publisher,MultiWriter,init_page_filter=__esm({"pkg/page-filter/index.ts"(){init_log(),log43=getDomainLogger("pkg",{component:"page-filter"}),pageFilter=new class{filterSet=null;currentLanguage=null;setFilter(e){this.filterSet=new Set;for(const t of e){const e=`${t.language}:${t.pagePath}`;this.filterSet.add(e)}log43.debug(`Page filter set: ${e.length} tasks`)}setCurrentLanguage(e){this.currentLanguage=e}clearFilter(){this.filterSet=null,this.currentLanguage=null,log43.debug("Page filter cleared")}shouldProcess(e,t){if(!this.filterSet)return!0;const r=`${e}:${t}`;return this.filterSet.has(r)}getFilterSize(){return this.filterSet?.size??0}}}}),init_site=__esm({"internal/domain/site/entity/site.ts"(){init_page2(),init_url(),init_log(),init_taxonomies_builder(),init_menu(),init_pagegraph(),init_html_link_processor(),init_page_filter(),log44=getDomainLogger("site",{component:"site"}),Site=class{configSvc;contentSvc;translationSvc;languageSvc;sitemap;staticCopySvc;publisher;template=null;author;organization;compiler;url;ref=null;language;navigation=null;title;home=null;pageGraph=null;backlinksCache=null;get Title(){return this.title}get Description(){return this.home?.description()||""}get Compiler(){return this.compiler}get IsGoogleAnalyticsEnabled(){return this.configSvc.isGoogleAnalyticsEnabled()}get GoogleAnalyticsID(){return this.configSvc.googleAnalyticsID()}get IsGoogleAnalyticsRespectDoNotTrack(){return this.configSvc.isGoogleAnalyticsRespectDoNotTrack()}get IsDisqusEnabled(){return this.configSvc.isDisqusEnabled()}get DisqusShortname(){return this.configSvc.disqusShortname()}get IsXRespectDoNotTrack(){return this.configSvc.isXRespectDoNotTrack()}get IsXDisableInlineCSS(){return this.configSvc.isXDisableInlineCSS()}get ConfiguredSocialPlatforms(){return this.configSvc.getConfiguredSocialPlatforms()}GetSocialLink(e){return this.configSvc.getSocialLink(e)}GetSocialTitle(e){return this.configSvc.getSocialTitle(e)}async Pages(){const e=this.languageSvc.getLanguageIndex(this.language.getCurrentLanguage()),t=await this.contentSvc.globalPages(e);return this.sitePages(t)}async RegularPages(){const e=await this.contentSvc.globalRegularPages();return this.sitePages(e)}constructor(e,t,r,i,s,n,a,o,l,c,h,u,g,d,p){this.configSvc=e,this.contentSvc=t,this.translationSvc=r,this.languageSvc=i,this.sitemap=s,this.staticCopySvc=n,this.publisher=a,this.author=o,this.organization=l,this.compiler=c,this.url=h,this.ref=u,this.language=g,this.navigation=d,this.title=p}async build(e){try{this.template=e,await this.setup(),await this.copyStaticFiles();const t=this.languageSvc.languageKeys();for(const e of t)this.language.setCurrentLanguage(e),await this.generateNavigations(),await this.render()}catch(e){const t=e instanceof Error?e.message:String(e);throw log44.error(`❌ Site build failed: ${t}`),e}}async renderAllLanguages(){const e=this.languageSvc.languageKeys();for(const t of e)this.language.setCurrentLanguage(t),await this.generateNavigations(),await this.render()}async buildWithProgress(e,t){try{this.template=e,await this.setup(),await this.copyStaticFiles();const r=this.languageSvc.languageKeys();for(const e of r)this.language.setCurrentLanguage(e),await this.generateNavigations(),await this.renderWithProgress(t)}catch(e){const t=e instanceof Error?e.message:String(e);throw log44.error(`❌ Site build failed: ${t}`),e}}async setup(){try{await this.buildPageGraph()}catch(e){const t=e instanceof Error?e.message:String(e);throw log44.error(`❌ Setup failed: ${t}`),e}}async render(){try{await this.renderPages()}catch(e){throw e}}async renderWithProgress(e){try{await this.renderPagesWithProgress(e)}catch(e){throw e}}async renderPages(){const e=this.language.getCurrentLanguage(),t=this.languageSvc.getLanguageIndex(e),r=[];await this.contentSvc.walkPages(t,async e=>{const t=await this.sitePage(e);r.push(t);const i=await this.contentSvc.getPageSources(e);await t.processResources(i),e.isHome()&&(this.home=t)}),log44.info(`📊 Processing wikilinks for ${r.length} pages...`);for(const e of r)try{await e.WikilinkContent()}catch(t){const r=t instanceof Error?t.message:String(t);log44.warn(`⚠️ Failed to process wikilinks for ${e.slug()}: ${r}`)}log44.info("✅ Wikilink processing complete");const i=r.filter(t=>{const r=t.file().paths().base();return!!shouldProcessPage(e,r)&&t.isStale()}),s=i.filter(e=>e.isHome()),n=i.filter(e=>!e.isHome());log44.info(`📄 Rendering ${s.length} home page(s) first...`);for(const e of s)await e.render(),e.clearStale();log44.info(`✅ Home page(s) rendered, now rendering ${n.length} other pages in parallel...`);for(let e=0;e<n.length;e+=10){const t=n.slice(e,e+10);await Promise.all(t.map(async e=>{try{await e.render(),e.clearStale()}catch(t){const r=t instanceof Error?t.message:String(t);log44.error(`❌ Failed to render page ${e.slug()}: ${r}`)}}))}}async renderPagesWithProgress(e){const t=this.language.getCurrentLanguage(),r=this.languageSvc.getLanguageIndex(t),i=[];await this.contentSvc.walkPages(r,async e=>{const t=await this.sitePage(e);i.push(t);const r=await this.contentSvc.getPageSources(e);await t.processResources(r),e.isHome()&&(this.home=t)}),log44.info(`📊 Processing wikilinks for ${i.length} pages...`);for(const e of i)try{await e.WikilinkContent()}catch(t){const r=t instanceof Error?t.message:String(t);log44.warn(`⚠️ Failed to process wikilinks for ${e.slug()}: ${r}`)}log44.info("✅ Wikilink processing complete");const s=i.filter(e=>{const r=e.file().paths().base();return!!shouldProcessPage(t,r)&&e.isStale()}),n=s.filter(e=>e.isHome()),a=s.filter(e=>!e.isHome()),o=i.length;let l=0;log44.info(`📄 Rendering ${n.length} home page(s) first...`);for(const t of n)await t.render(),l++,e?.({currentPage:l,totalPages:o});log44.info(`✅ Home page(s) rendered, now rendering ${a.length} other pages in parallel...`);for(let t=0;t<a.length;t+=10){const r=a.slice(t,t+10);await Promise.all(r.map(async e=>{try{await e.render()}catch(t){const r=t instanceof Error?t.message:String(t);log44.error(`❌ Failed to render page ${e.slug()}: ${r}`)}})),l+=r.length,e?.({currentPage:l,totalPages:o})}log44.info("✅ All pages rendered successfully")}async pageOutput(e){return e.output()}clearSiteCache(){}translate(e){return this.translationSvc.translate(this.language.getCurrentLanguage(),e)}get Home(){return this.home}get Params(){return this.configSvc.configParams()}get Taxonomies(){return this.navigation&&this.navigation.getTaxonomies(this.language.getCurrentLanguage())||new TaxonomyList}get Menus(){return this.navigation?this.navigation.getMenus(this.language.getCurrentLanguage()):new Menus}getTitle(){return this.title}setTitle(e){this.title=e}getConfigService(){return this.configSvc}getContentService(){return this.contentSvc}getLanguageService(){return this.languageSvc}baseURL(){return this.url.base}get BaseURL(){return this.baseURL()}getURL(){return this.url}getRef(){return this.ref?this.ref:{}}getLanguage(){return this.language}get Language(){return this.getLanguage()}get LanguageCode(){return this.language.lang()}get Languages(){return this.language.languages()}getNavigation(){return this.navigation?this.navigation:{}}getPublisher(){return this.publisher}getTemplate(){return this.template}get Author(){return this.author.author(this.home?.author())}get Organization(){return this.organization.organization(this.home?.organization())}getCompiler(){return this.compiler}getSitemap(){return this.sitemap}isMultipleLanguage(){return this.language.isMultipleLanguage()}get IsMultilingual(){return this.isMultipleLanguage()}getCurrentLanguage(){return this.language.lang()}languagePrefix(){return this.language.languagePrefix()}async sitePage(e){return new Page2(this.template,this.languageSvc,this.publisher,e,this)}sitePages(e){const t=[];for(let r=0;r<e.length;r++){const i=e[r];try{const e=this.sitePageSync(i);t.push(e)}catch(e){log44.error(`❌ [Site.sitePages] Failed to convert page ${r}:`,e)}}return t}sitePageSync(e){return new Page2(this.template,this.languageSvc,this.publisher,e,this)}async generateNavigations(){const e=this.language.getCurrentLanguage(),t=this.languageSvc.getLanguageIndex(e);this.navigation&&(await this.navigation.generateMenusForLanguage(e,t),await this.navigation.generateTaxonomiesForLanguage(e,t,this))}GetPage(...e){if(e.length>1)throw new Error(`too many arguments to .Site.GetPage: ${e}. Use lookups on the form {{ .Site.GetPage "/posts/mypage-md" }}`);let t=e[0];t=t.replace(/\\/g,"/"),t.startsWith("/")||(t="/"+t);try{const e=this.languageSvc.getLanguageIndex(this.language.getCurrentLanguage()),r=this.contentSvc.getPageFromPathSync(e,t);return r?this.sitePageSync(r):(log44.warn(`⚠️ GetPage: No page found for key "${t}"`),null)}catch(e){return log44.error(`❌ Error getting page "${t}": ${e}`),null}}async copyStaticFiles(){try{await this.staticCopySvc.copyStaticFiles(this.staticCopySvc.staticFs(),this.staticCopySvc.publishFs())}catch(e){throw log44.error("❌ Static file copy failed:",e),e}}async siteWeightedPage(e){const t=await this.sitePage(e.page()),{WeightedPage:r}=await Promise.resolve().then(()=>(init_taxonomies_builder(),taxonomies_builder_exports));return new r(t,e)}async buildPageGraph(){if(!this.pageGraph)try{const e=[],t=this.languageSvc.languageKeys();for(const r of t){const t=this.languageSvc.getLanguageIndex(r);await this.contentSvc.walkPages(t,async t=>{e.push(t)})}const r=e.map(e=>e.slug());log44.info(`📄 Collected ${r.length} page slugs`);const i=await this.collectResourceSlugs(e);log44.info(`🖼️ Collected ${i.length} resource slugs`);const s=[...r,...i];this.pageGraph=new PageGraph(s),log44.info(`✅ PageGraph built: ${r.length} pages + ${i.length} resources = ${s.length} total`),this.buildBacklinksCache(e)}catch(e){const t=e instanceof Error?e.message:String(e);throw log44.error(`❌ Failed to build PageGraph: ${t}`),e}}async collectResourceSlugs(e){const t=[],r=new Set;try{for(const i of e)try{const e=await this.contentSvc.getPageSources(i);for(const i of e){const e=i.slug();r.has(e)||(r.add(e),t.push(e))}}catch(e){const t=e instanceof Error?e.message:String(e);log44.error(`⚠️ Failed to get resources for page ${i.slug()}: ${t}`)}}catch(e){const t=e instanceof Error?e.message:String(e);log44.warn(`⚠️ Failed to collect resource slugs: ${t}`)}return t}async ProcessWikilinks(e,t){if(!this.pageGraph)return log44.warn("⚠️ PageGraph not built yet, returning original HTML"),t;try{let i="";if(this.url&&this.url.base){if(i=this.url.base.replace(/\/$/,""),i.startsWith("/"));else if(i)try{i=new URL2(i).pathname.replace(/\/$/,"")}catch(e){log44.warn(`Failed to parse baseURL as URL: ${i}, treating as path`)}"/"===i&&(i="")}const s=(r=this.pageGraph,new HtmlLinkProcessor(r,{markdownLinkResolution:"shortest",prettyLinks:!0,openLinksInNewTab:!1,lazyLoad:!0,externalLinkIcon:!0,baseURL:i})),n=await s.processLinks(e,t);return this.pageGraph.registerOutgoingLinks(e,n.outgoingLinks),n.html}catch(r){const i=r instanceof Error?r.message:String(r);return log44.error(`❌ Failed to process wikilinks for ${e}: ${i}`),t}var r}getPageGraph(){return this.pageGraph}GetBacklinks(e){if(this.backlinksCache&&this.backlinksCache.has(e))return this.backlinksCache.get(e);if(!this.pageGraph)return log44.warn(`⚠️ PageGraph not built yet, cannot get backlinks for ${e}`),[];const t=this.pageGraph.getBacklinks(e);return this.backlinksCache&&this.backlinksCache.set(e,t),t}async buildBacklinksCache(e){this.pageGraph?this.backlinksCache=new Map:log44.warn("⚠️ PageGraph not built, skipping backlinks cache")}async GetContentIndex(){if(!this.pageGraph)return log44.warn("⚠️ PageGraph not built yet, cannot generate content index"),new Map;const e=new Map,t=await this.RegularPages();for(const r of t){const t=r.slug(),i=this.pageGraph.getOutgoingLinks(t),s=(r.Plain||"").substring(0,1e3);e.set(t,{slug:t,title:r.Title||r.File.OriginalBaseName,links:i,tags:r.Params?.tags||[],content:s})}return e}}}});import path23 from"path";async function openFileForWriting(e,t){const r=path23.normalize(t);try{return await e.create(r)}catch(t){if(!function(e){return e&&("ENOENT"===e.code||"FILE_NOT_FOUND"===e.code||e.message?.includes("not found")||e.message?.includes("no such file"))}(t))throw t;const i=path23.dirname(r);return await e.mkdirAll(i,511),await e.create(r)}}var log46,Ref,CollatorWrapper,Language2,Author2,Organization2,Compiler,log49,Navigation,log50,MenuBuilder,log51,NavigationFactory,init_publisher=__esm({"internal/domain/site/entity/publisher.ts"(){init_log(),getDomainLogger("site",{component:"publisher"}),Publisher=class{fs;constructor(e){this.fs=e}async publishSource(e,...t){const r=await this.openFilesForWriting(...t);try{const t="string"==typeof e?(new TextEncoder).encode(e):e;await this.copyToWriter(r,t)}finally{await r.close()}}async publishFiles(e,...t){const r=await this.openFilesForWriting(...t);try{await this.copyStreamToWriter(r,e)}finally{await r.close()}}async openFilesForWriting(...e){const t=[];for(const r of e){const e=await openFileForWriting(this.fs,r);t.push(e)}return new MultiWriter(t)}async copyToWriter(e,t){await e.write(t)}async copyStreamToWriter(e,t){const r=t.getReader();try{for(;;){const{done:t,value:i}=await r.read();if(t)break;await e.write(i)}}finally{r.releaseLock()}}},MultiWriter=class{files;constructor(e){this.files=e}async write(e){const t=this.files.map(t=>t.write(e));await Promise.all(t)}async close(){const e=this.files.map(e=>e.close());await Promise.all(e)}}}}),init_ref=__esm({"internal/domain/site/entity/ref.ts"(){init_log(),log46=getDomainLogger("site",{component:"ref"}),Ref=class{site;contentSvc;notFoundURL;constructor(e,t,r="#ZgotmplZ"){this.site=e,this.contentSvc=t,this.notFoundURL=r}async relRefFrom(e,t){return this.relRef(e,t)}async relRef(e,t){try{const r=this.decodeRefArgs(e);return r.path?this.refLink(r.path,t,!0,r.outputFormat):""}catch(e){throw new Error(`Invalid arguments to Ref: ${e}`)}}decodeRefArgs(e){return{path:e.path||"",outputFormat:e.outputFormat||""}}async refLink(e,t,r,i){const s=t;if(!s||"function"!=typeof s.unwrapPage)throw new Error("source is not a PageWrapper");const n=s.unwrapPage();let a;const o=e.replace(/\\/g,"/");try{a=new globalThis.URL(o,"http://example.com")}catch(e){return log46.error(`Failed to parse ref URL: ${e}`),this.notFoundURL}let l=null,c="";if(""!==a.pathname)try{l=await this.contentSvc.getPageRef(n,a.pathname,this.site.home.page);let e=null;if(l||this.isPositioner(t)&&(e=t.position()),!l)return this.logNotFound(a.pathname,"page not found",n,e),this.notFoundURL;const i=await this.site.sitePage(l);c=r?i.relPermalink():i.permalink()}catch(t){return log46.error(`[${n.pageIdentity().pageLanguage()}] REF_NOT_FOUND: Ref "${e}": ${t}`),this.notFoundURL}return a.hash&&(c=c+"#"+a.hash),c}isPositioner(e){return e&&"function"==typeof e.position}logNotFound(e,t,r,i){const s=r.pageIdentity().pageLanguage();i&&i.isValid()?log46.error(`[${s}] REF_NOT_FOUND: Ref "${e}": ${i.toString()}: ${t}`):r?log46.error(`[${s}] REF_NOT_FOUND: Ref "${e}" from page "${r.path()}": ${t}`):log46.error(`[${s}] REF_NOT_FOUND: Ref "${e}": ${t}`)}}}}),init_language3=__esm({"internal/domain/site/entity/language.ts"(){init_log(),getDomainLogger("site",{component:"language"}),CollatorWrapper=class{collator;constructor(e){this.collator=e}compare(e,t){return this.collator.compare(e,t)}},Language2=class e{langSvc;currentLocation;currentLanguage;collator=null;constructor(e){this.langSvc=e,this.currentLocation="UTC",this.currentLanguage=""}currentLanguageIndex(){try{return this.langSvc.getLanguageIndex(this.currentLanguage)}catch(e){throw new Error(`language "${this.currentLanguage}" not found`)}}async setup(){this.currentLocation="UTC"}languages(){const t=[];for(const r of this.langSvc.languageKeys()){const i=new e(this.langSvc);i.currentLocation=this.currentLocation,i.currentLanguage=r,i.collator=this.collator,t.push(i)}return t}getCollator(){if(!this.collator)try{const e=new Intl.Collator(this.currentLanguage||"en");this.collator=new CollatorWrapper({compare:(t,r)=>e.compare(t,r)})}catch(e){const t=new Intl.Collator("en");this.collator=new CollatorWrapper({compare:(e,r)=>t.compare(e,r)})}return this.collator}location(){return this.currentLocation}isMultipleLanguage(){return this.langSvc.languageKeys().length>1}languagePrefix(){return this.currentLanguage===this.langSvc.defaultLanguage()?"":this.currentLanguage}lang(){return this.currentLanguage}get Lang(){return this.lang()}languageName(){return this.langSvc.getLanguageName(this.currentLanguage)}get LanguageName(){return this.languageName()}defaultLanguageName(){return this.langSvc.getLanguageName(this.langSvc.defaultLanguage())}languageCode(){return this.currentLanguage}get LanguageCode(){return this.languageCode()}get LanguageDirection(){return"ltr"}languageDirection(){return"ltr"}setCurrentLanguage(e){this.currentLanguage=e}getCurrentLanguage(){return this.currentLanguage}setCurrentLocation(e){this.currentLocation=e}}}}),init_author=__esm({"internal/domain/site/valueobject/author.ts"(){Author2=class{_name;_email;_homeAuthor;constructor(e,t){this._name=e,this._email=t}name(){return this._name}email(){return this._email}author(e){return this._homeAuthor=e,this}get Name(){return this._homeAuthor?.name||this.name()}get Description(){return this._homeAuthor?.description||""}get Avatar(){return this._homeAuthor?.avatar||""}get Twitter(){return this._homeAuthor?.social?.twitter||""}get Socials(){const e=[];if(!this._homeAuthor?.social)return e;for(const[t,r]of Object.entries(this._homeAuthor.social))r&&e.push({ID:t,Link:r});return e}}}}),init_organization=__esm({"internal/domain/site/valueobject/organization.ts"(){init_log(),getDomainLogger("site",{component:"organization"}),Organization2=class{_name;_description;_website;_logo;_email;_address;_vision;_homeOrganization;constructor(){this._name="MDFriday",this._description="Turn markdown to website, in minutes.",this._website="https://mdfriday.com",this._logo="https://gohugo.net/mdfriday.svg",this._email="support@mdfriday.com",this._address="Cang long Street, Wuhan, China",this._vision="Make site generation easy and accessible for everyone."}name(){return this._name}description(){return this._description}website(){return this._website}organization(e){return this._homeOrganization=e,this}get Name(){return this._homeOrganization?.name||this.name()}get Description(){return this._homeOrganization?.description||this.description()}get Website(){return this._homeOrganization?.website||this.website()}get Vision(){return this._homeOrganization?.vision||this._vision}get Logo(){return this._homeOrganization?.logo||this._logo}get Address(){return this._homeOrganization?.contact?.address||this._address}get Email(){return this._homeOrganization?.contact?.email||this._email}get Social(){return this._homeOrganization?.social}SocialById(e){return this._homeOrganization?.social?.[e]||""}get Socials(){const e=[];if(!this._homeOrganization?.social)return e;for(const[t,r]of Object.entries(this._homeOrganization.social))r&&e.push({ID:t,Link:r});return e}}}}),init_version=__esm({"internal/domain/site/valueobject/version.ts"(){Compiler=class{ver;constructor(e){this.ver=e}version(){return this.ver}environment(){return"production"}}}}),init_navigation=__esm({"internal/domain/site/entity/navigation.ts"(){init_log(),init_menu(),log49=getDomainLogger("site",{component:"navigation"}),Navigation=class{taxonomies;taxonomiesBuilder=null;taxonomiesCache=new Map;menus;menuBuilder=null;menuCache=new Map;constructor(e){this.taxonomies=new Map,this.menus=new Map;for(const t of e.languageKeys())this.menus.set(t,newEmptyMenus()),this.menuCache.set(t,!1)}setMenuBuilder(e){this.menuBuilder=e}setTaxonomiesBuilder(e){this.taxonomiesBuilder=e}async generateMenusForLanguage(e,t){if(this.menuBuilder){if(!0!==this.menuCache.get(e))try{const r=await this.menuBuilder.buildMenusForLanguage(t);this.menus.set(e,r),this.menuCache.set(e,!0)}catch(t){log49.error(`Failed to generate menus for language ${e}: ${t}`)}}else log49.error("Menu builder not set, cannot generate menus")}async generateTaxonomiesForLanguage(e,t,r){if(this.taxonomiesBuilder){if(!0!==this.taxonomiesCache.get(e))try{const i=await this.taxonomiesBuilder.buildTaxonomiesForLanguage(t,r);this.taxonomies.set(e,i),this.taxonomiesCache.set(e,!0)}catch(t){log49.error(`Failed to generate taxonomies for language ${e}: ${t}`)}}else log49.error("Taxonomies builder not set, cannot generate taxonomies")}getMenus(e){let t=this.menus.get(e);return void 0===t&&(t=newEmptyMenus()),t}getTaxonomies(e){return this.taxonomies.get(e)}}}}),init_menu_builder=__esm({"internal/domain/site/entity/menu-builder.ts"(){init_log(),init_menu(),log50=getDomainLogger("site",{component:"menu-builder"}),MenuBuilder=class{contentService;site;constructor(e,t){this.contentService=e,this.site=t}async buildMenusForLanguage(e){const t=new Map;return await this.contentService.walkPages(e,async e=>{await this.processPage(e,t)}),this.convertToMenus(t)}async processPage(e,t){try{const r=e.menu();if(!r)return;const i=await this.generatePageUrl(e);for(const[s,n]of Object.entries(r))await this.processMenuSection(s,n,i,e,t)}catch(e){log50.error(`Error processing page for menu: ${e}`)}}async processMenuSection(e,t,r,i,s){if(!(!1===t||Array.isArray(t)&&0===t.length))if(Array.isArray(t))await this.processMenuItems(e,t,r,i,s);else if(t&&"object"==typeof t){let n=0;for(const[a,o]of Object.entries(t))if(!(!1===o||Array.isArray(o)&&0===o.length)&&Array.isArray(o)){const t=`${e}.${a}`;if(await this.processMenuItems(t,o,r,i,s),"footer"===e){const e=`${t}::__subsection__`;s.has(e)||s.set(e,{title:a,url:"",children:new Map,weight:1e3,level:0,menuName:t,order:n})}n++}}}async processMenuItems(e,t,r,i,s){for(let n=0;n<t.length;n++){const a=t[n];if(!a||"object"!=typeof a)continue;if(!a.title||"string"!=typeof a.title)continue;let o=a.url||"";o=""===o?r:await this.processMenuItemUrl(o);const l="number"==typeof a.weight?a.weight:1e3,c=`${e}::${a.title}`;let h=s.get(c);h?l<h.weight&&(h.weight=l,h.url=o):(h={title:a.title,url:o,children:new Map,weight:l,level:0,menuName:e||void 0,order:n},s.set(c,h)),Array.isArray(a.children)&&await this.processChildrenItems(c,a.children,r,i,s,h)}}async processChildrenItems(e,t,r,i,s,n){for(let a=0;a<t.length;a++){const o=t[a];if(!o||"object"!=typeof o)continue;if(!o.title||"string"!=typeof o.title)continue;let l=o.url||"";l=""===l?r:await this.processMenuItemUrl(l);const c="number"==typeof o.weight?o.weight:1e3,h=`${e}::${o.title}`,u={title:o.title,url:l,children:new Map,weight:c,level:n.level+1,menuName:n.menuName||void 0,order:a};s.set(h,u),n.children.set(h,u),Array.isArray(o.children)&&await this.processChildrenItems(h,o.children,r,i,s,u)}}async generatePageUrl(e){try{return(await this.site.sitePage(e)).RelPermalink}catch(t){return log50.error(`Error generating page URL for ${e.path()}: ${t}`),this.fallbackUrlFromPath(e.path())}}async processMenuItemUrl(e){try{return this.site.getURL().relURL(e)}catch(t){return log50.error(`Error processing menu item URL ${e}: ${t}`),e}}fallbackUrlFromPath(e){let t=e.replace(/\.md$/,"");return t.startsWith("/")||(t="/"+t),t.endsWith("/")||t.includes(".")||(t+="/"),t}convertToMenus(e){const t=new Map;for(const[r,i]of e.entries())if(!r.includes("::__subsection__")&&0===i.level){const e=i.menuName||"main";t.has(e)||t.set(e,[]),t.get(e).push(i)}const r=this.buildMenuItems(t.get("nav")||[],e),i=[],s=new Map,n=new Map;for(const[r,i]of t.entries())if(r.startsWith("footer.")){const t=r.substring(7),a=this.buildMenuItems(i,e,!1);s.set(t,a);const o=`${r}::__subsection__`,l=e.get(o);l&&n.set(t,l.order)}const a=Array.from(s.entries()).sort((e,t)=>(n.get(e[0])||0)-(n.get(t[0])||0));for(let e=0;e<a.length;e++){const[t,r]=a[e];if(r.length>0){const s=new Menu2({title:this.capitalizeFirstLetter(t),url:"",children:r,weight:e+1,identifier:`footer-${t}`});i.push(s)}}const o={};return r.length>0&&(o.nav=r),i.length>0&&(o.footer=i),new Menus(o)}capitalizeFirstLetter(e){return e.charAt(0).toUpperCase()+e.slice(1)}buildMenuItems(e,t,r=!0){const i=[];for(const s of e){const e=Array.from(s.children.values()),n=e.length>0?this.buildMenuItems(e,t,r):[],a=new Menu2({title:s.title,url:s.url,children:n,weight:s.weight,identifier:s.url});i.push(a)}return r?i.sort((e,t)=>e.weight()!==t.weight()?e.weight()-t.weight():e.title().localeCompare(t.title())):i.sort((t,r)=>{const i=e.find(e=>e.title===t.title()),s=e.find(e=>e.title===r.title());return(i?.order||0)-(s?.order||0)})}}}}),init_navigation_factory=__esm({"internal/domain/site/factory/navigation-factory.ts"(){init_navigation(),init_menu_builder(),init_taxonomies_builder(),init_log(),log51=getDomainLogger("site",{component:"navigation-factory"}),NavigationFactory=class{langService;contentService;site;constructor(e,t,r){this.langService=e,this.contentService=t,this.site=r}createNavigation(){try{const t=(e=this.langService,new Navigation(e)),r=new MenuBuilder(this.contentService,this.site);t.setMenuBuilder(r);const i=new TaxonomiesBuilder(this.contentService);return t.setTaxonomiesBuilder(i),t}catch(e){throw log51.error(`Failed to create Navigation entity: ${e}`),e}var e}}}});var log53,ResourceHash,PublishOnce,ResourceImpl,init_site2=__esm({"internal/domain/site/factory/site.ts"(){init_site(),init_publisher(),init_url(),init_ref(),init_language3(),init_author(),init_organization(),init_version(),init_navigation_factory(),init_log(),getDomainLogger("site",{component:"factory"})}}),init_type9=__esm({"internal/domain/resources/type.ts"(){}});import{createHash as createHash3}from"crypto";import{PassThrough}from"stream";import{pipeline}from"stream/promises";import{Readable}from"stream";var MinifierClient,MinifyTransformation,init_resource=__esm({"internal/domain/resources/entity/resource.ts"(){init_resources2(),init_paths(),init_log(),log53=getDomainLogger("resources",{component:"publisher"}),ResourceHash=class{value="";size=0;resource=null;async setup(e){if(this.value)return;this.resource=e;const t=await e.readSeekCloser(),r=createHash3("sha256");let i=0;const s=[];t.on("data",e=>{r.update(e),i+=e.length,s.push(e)}),await new Promise((e,s)=>{t.on("end",()=>{this.value=r.digest("hex"),this.size=i,e()}),t.on("error",s)}),await t.close()}},PublishOnce=class{hasPublished=!1;publishPromise=null;async do(e){if(!this.hasPublished)return this.publishPromise||(this.publishPromise=e().then(()=>{this.hasPublished=!0})),this.publishPromise}},ResourceImpl=class e{h;openReadSeekCloser;_mediaType;paths;_data;publisher;publishOnce;constructor(e,t,r,i={},s){this.h=new ResourceHash,this.openReadSeekCloser=e,this._mediaType=t,this.paths=r,this._data=i,this.publisher=s,this.publishOnce=new PublishOnce}name(){return this.paths.pathFile()}nameNormalized(){return this.paths.targetPath().replace(/\\/g,"/")}mediaType(){return this._mediaType}resourceType(){return this._mediaType.mainType}relPermalink(){return this.publish(),this.paths.targetLink()}permalink(){return this.publish(),this.paths.targetPath()}async publish(){const e=this.targetPath();this.publisher?await this.publishOnce.do(async()=>{let t=null,r=null;try{t=await this.publisher.openPublishFileForWriting(this.paths.targetPath()),r=await this.readSeekCloser(),await this.copyStreamToFile(r,t)}catch(t){throw log53.errorf("❌ [Resource.publish] Error publishing %s: %s",e,t),t}finally{if(r)try{await r.close()}catch(t){log53.errorf("❌ [Resource.publish] Failed to close ReadSeekCloser %s: %s",e,t)}if(t)try{await t.file.close()}catch(t){log53.errorf("❌ [Resource.publish] Failed to close public writer %s: %s",e,t)}}}):log53.error("⚠️ [Resource.publish] No publisher for: %s",e)}async copyStreamToFile(e,t){const r=this.targetPath();try{await pipeline(e,t)}catch(e){throw log53.errorf("❌ [copyStreamToFile] Error during pipeline for %s: %s",r,e),e}}targetPath(){return this.paths.targetPath()}data(){return this._data}async readSeekCloser(){const e=await this.openReadSeekCloser();if(e&&"function"==typeof e.read){const t=e.read();if(t){const r=new Readable;let i;for(r.push(t);null!==(i=e.read());)i&&r.push(i);return r.push(null),Object.assign(r,{seek:async(e,t)=>0,close:async()=>Promise.resolve()})}}return e}async content(e){const t=await this.readSeekCloser();return new Promise((e,r)=>{let i="";t.on("data",e=>{i+=e.toString()}),t.on("end",()=>{e(i)}),t.on("error",r)})}async hash(){return await this.h.setup(this),this.h.value}async size(){return await this.h.setup(this),this.h.size}cloneTo(e){const t=this.clone();return t.paths=t.paths.fromTargetPath(e),t}clone(){const t=new e(this.openReadSeekCloser,this._mediaType,this.paths,{...this._data},this.publisher);return t.h=this.h,t}key(){return this.paths.targetLink()}get RelPermalink(){return this.relPermalink()}get Permalink(){return this.permalink()}get Name(){return this.name()}get MediaType(){return this.mediaType()}get ResourceType(){return this.resourceType()}get TargetPath(){return this.targetPath()}get Data(){return this.data()}get Content(){return this.content()}get Hash(){return()=>this.hash()}get Size(){return()=>this.size()}meta(){return new ResourceMetadataImpl(this.paths.targetPath(),this._mediaType.type,this._data)}mergeData(e){if(e&&0!==Object.keys(e).length)for(const[t,r]of Object.entries(e))t in this._data||(this._data[t]=r)}async transform(...e){let t=this;for(let r=0;r<e.length;r++){const i=e[r];try{const e=await t.readSeekCloser(),r=new PassThrough;let s="";const n=[],a={source:{from:e,inPath:t.targetPath(),inMediaType:t.mediaType()},target:{to:r},data:{...t.data()},addOutPathIdentifier:e=>{const r=t.targetPath(),i=PathDomain.parseBasic(r);let s=i.dir;s=s.replace(/\/+$/,"");let n="";s&&(n=s+"/"),n+=i.nameWithoutExt+e+i.ext,a.data.targetPath=n},updateBuffer:()=>{},updateSource:()=>{},close:()=>{e.close()}};r.on("data",e=>{n.push(e)});const o=new Promise((e,t)=>{r.on("end",()=>{s=Buffer.concat(n).toString(),e()}),r.on("error",e=>{t(e)})});await i.transform(a),await o;const l=a.data.targetPath||t.targetPath(),c=this.createTransformedResource(s,l,t.mediaType(),a.data);t=c,a.close()}catch(e){throw e}}return t}createTransformedResource(t,r,i,s){const n=this.paths.fromTargetPath(r);return new e(async()=>{const e=new PassThrough;return e.end(t),Object.assign(e,{seek:async(e,t)=>0,close:async()=>Promise.resolve()})},i,n,s,this.publisher)}}}});import{minify as terserMinify}from"terser";var IntegrityClient,FingerprintTransformation,init_minifier=__esm({"internal/domain/resources/entity/minifier.ts"(){init_resources2(),MinifierClient=class{minifiers=new Map;minifyOutput;constructor(e=!1){this.minifyOutput=e,this.setupMinifiers()}setupMinifiers(){this.minifiers.set("text/css",this.minifyCSS.bind(this)),this.minifiers.set("text/javascript",this.minifyJS.bind(this)),this.minifiers.set("application/javascript",this.minifyJS.bind(this)),this.minifiers.set("application/json",this.minifyJSON.bind(this)),this.minifiers.set("text/html",this.minifyHTML.bind(this)),this.minifiers.set("image/svg+xml",this.minifySVG.bind(this)),this.minifiers.set("application/xml",this.minifyXML.bind(this)),this.minifiers.set("text/xml",this.minifyXML.bind(this))}async minify(e){const t=new MinifyTransformation(this);return e.transform(t)}getMinifier(e){return this.minifiers.get(e)||null}async minifyCSS(e){return e}async minifyJS(e){try{return(await terserMinify(e,{compress:{drop_console:!1,drop_debugger:!0,passes:2},mangle:{toplevel:!1},format:{comments:!1}})).code||e}catch(t){return e}}async minifyJSON(e){try{return JSON.stringify(JSON.parse(e))}catch{return e}}async minifyHTML(e){return e}async minifySVG(e){return e}async minifyXML(e){return e}},MinifyTransformation=class{constructor(e){this.minifierClient=e}key(){return ResourceTransformationKey.newResourceTransformationKey("minify")}async transform(e){e.addOutPathIdentifier(".min");const t=e.source.inMediaType.type,r=this.minifierClient.getMinifier(t);if(!r)return void e.source.from.pipe(e.target.to);let i="";e.source.from.on("data",e=>{i+=e.toString()}),await new Promise((t,s)=>{e.source.from.on("end",async()=>{try{const s=await r(i);e.target.to.write(s),e.target.to.end(),t()}catch(e){s(e)}}),e.source.from.on("error",s)})}}}});import{createHash as createHash4}from"crypto";var ExecuteAsTemplateTransform,TemplateClient,log54,Publisher2,FileWritable,init_integrity=__esm({"internal/domain/resources/entity/integrity.ts"(){init_resources2(),IntegrityClient=class{async fingerprint(e,t="sha256"){const r=new FingerprintTransformation(t);return e.transform(r)}generateIntegrity(e){return`sha256-${createHash4("sha256").update(e,"utf8").digest("base64")}`}generateSHA384(e){return`sha384-${createHash4("sha384").update(e,"utf8").digest("base64")}`}generateSHA512(e){return`sha512-${createHash4("sha512").update(e,"utf8").digest("base64")}`}verifyIntegrity(e,t){const[r,i]=t.split("-",2);let s;switch(r){case"sha256":s=createHash4("sha256").update(e,"utf8").digest("base64");break;case"sha384":s=createHash4("sha384").update(e,"utf8").digest("base64");break;case"sha512":s=createHash4("sha512").update(e,"utf8").digest("base64");break;default:return!1}return s===i}},FingerprintTransformation=class{constructor(e){this.algo=e}key(){return ResourceTransformationKey.newResourceTransformationKey("fingerprint",this.algo)}async transform(e){const t=this.newHash(this.algo);let r="";const i=[];e.source.from.on("data",e=>{t.update(e),i.push(e),r+=e.toString()}),await new Promise((r,s)=>{e.source.from.on("end",()=>{try{const s=t.digest(),n=s.toString("hex");e.data.Integrity=this.integrity(this.algo,s);const a=n.substring(0,12);e.addOutPathIdentifier("."+a);for(const t of i)e.target.to.write(t);e.target.to.end(),r()}catch(e){s(e)}}),e.source.from.on("error",s)})}newHash(e){switch(e){case"md5":return createHash4("md5");case"sha256":return createHash4("sha256");case"sha384":return createHash4("sha384");case"sha512":return createHash4("sha512");default:throw new Error(`Unsupported hash algorithm: "${e}", use either md5, sha256, sha384 or sha512`)}}integrity(e,t){return`${e}-${t.toString("base64")}`}}}}),init_template4=__esm({"internal/domain/resources/entity/template.ts"(){init_resources2(),ExecuteAsTemplateTransform=class{templateExecutor;_targetPath;data;constructor(e,t,r){this.templateExecutor=e,this._targetPath=t,this.data=r}key(){return ResourceTransformationKey.newResourceTransformationKey("execute-as-template",this._targetPath)}async transform(e){try{e.data.targetPath=this._targetPath;let t="";if("function"==typeof e.source.from.read){let r;const i=[];for(;null!==(r=e.source.from.read());)r&&i.push(r);if(i.length>0)t=Buffer.concat(i).toString();else if(e.source.from._readableState&&e.source.from._readableState.buffer){const r=e.source.from._readableState.buffer,i=[];for(const e of r)e&&e.chunk&&i.push(e.chunk);i.length>0&&(t=Buffer.concat(i).toString())}}if(!t)return new Promise((t,r)=>{const i=[];e.source.from.on("data",e=>{i.push(e)}),e.source.from.on("end",async()=>{try{const s=Buffer.concat(i).toString();await this.executeTemplate(s,e,t,r)}catch(t){r(new Error(`failed to parse Resource "${e.source.inPath}" as Template: ${t}`))}}),e.source.from.on("error",e=>{r(e)}),"function"==typeof e.source.from.resume&&e.source.from.resume()});await this.executeTemplateSync(t,e)}catch(t){throw new Error(`failed to parse Resource "${e.source.inPath}" as Template: ${t}`)}}async executeTemplateSync(e,t){const r=await this.templateExecutor.executeTemplate(t.source.inPath,e,this.data);t.target.to.write(r),t.target.to.end()}async executeTemplate(e,t,r,i){try{await this.executeTemplateSync(e,t),r()}catch(e){i(e instanceof Error?e:new Error(String(e)))}}},TemplateClient=class{templateExecutor;constructor(e){this.templateExecutor=e}async executeAsTemplate(e,t,r){try{if(!e)throw new Error("Resource is null or undefined");if("function"!=typeof e.transform)throw new Error("Resource does not implement Transformer interface. Resource type: "+typeof e);const i=new ExecuteAsTemplateTransform(this.templateExecutor,t.replace(/\\/g,"/").replace(/^\/+/,""),r);return await e.transform(i)}catch(e){throw e}}}}});import*as path24 from"path";import{Writable as Writable2}from"stream";var log55,HttpClient4,init_publisher2=__esm({"internal/domain/resources/entity/publisher.ts"(){init_log(),log54=getDomainLogger("resources",{component:"publisher"}),Publisher2=class{pubFs;urlSvc;constructor(e,t){this.pubFs=e,this.urlSvc=t}async openPublishFileForWriting(e){const t=e.replace(/^\/+/,"");try{const e=await this.pubFs.create(t);return new FileWritable(e)}catch(e){if("ENOENT"===e.code||e.message.includes("ENOENT")){const e=path24.dirname(t);await this.pubFs.mkdirAll(e,511);const r=await this.pubFs.create(t),i=r.close.bind(r);return r.close=async()=>{try{await i()}catch(e){throw log54.errorf("❌ [Publisher.File.close] Error closing publish file (retry) %s, $s",t,e),e}},new FileWritable(r)}throw e}}async openFilesForWriting(...e){if(0===e.length)throw new Error("No filenames provided");const t=e[0];return await this.openFileForWriting(t)}async openFileForWriting(e){const t=path24.normalize(e);try{return await this.pubFs.create(t)}catch(e){if(!this.isFileNotFoundError(e))throw e;const r=path24.dirname(t);return await this.pubFs.mkdirAll(r,511),await this.pubFs.create(t)}}isFileNotFoundError(e){return e&&("ENOENT"===e.code||e.message?.includes("no such file or directory")||e.message?.includes("not found"))}},FileWritable=class extends Writable2{file;constructor(e){super(),this.file=e}_write(e,t,r){this.file.write(e).then(()=>r()).catch(r)}_final(e){this.file.sync?.().then(()=>this.file.close()).then(()=>e()).catch(e)}}}});import*as http2 from"http";import*as https2 from"https";var log56,Resources,init_http2=__esm({"internal/domain/resources/entity/http.ts"(){init_log(),log55=getDomainLogger("resources",{component:"http-client"}),HttpClient4=class{defaultTimeout=3e4;defaultHeaders={"User-Agent":"MDFriday-Resources/1.0.0"};async fromRemote(e,t){return new Promise(r=>{try{const i=new URL(e),s="https:"===i.protocol,n=s?https2:http2,a={...this.defaultHeaders,...t?.headers},o={hostname:i.hostname,port:i.port||(s?443:80),path:i.pathname+i.search,method:"GET",headers:a,timeout:t?.timeout||this.defaultTimeout},l=n.request(o,i=>{if(i.statusCode&&i.statusCode>=300&&i.statusCode<400&&i.headers.location)return log55.infof("🔄 [HttpClient.fromRemote] Redirecting from %s to %s",e,i.headers.location),void this.fromRemote(i.headers.location,t).then(r);if(!i.statusCode||i.statusCode<200||i.statusCode>=300)return log55.errorf("❌ [HttpClient.fromRemote] HTTP error %d when fetching %s: %s",i.statusCode||0,e,i.statusMessage||"Unknown error"),void r(null);const s=[];i.on("data",e=>{s.push(e)}),i.on("end",()=>{try{const t=Buffer.concat(s).toString("utf8");log55.infof("✅ [HttpClient.fromRemote] Successfully fetched %d bytes from %s",t.length,e),r(t)}catch(t){log55.errorf("❌ [HttpClient.fromRemote] Error converting response to string from %s: %s",e,t),r(null)}}),i.on("error",t=>{log55.errorf("❌ [HttpClient.fromRemote] Response error when fetching %s: %s",e,t.message),r(null)})});l.on("error",t=>{log55.errorf("❌ [HttpClient.fromRemote] Request error when fetching %s: %s",e,t.message),r(null)}),l.on("timeout",()=>{l.destroy(),log55.errorf("❌ [HttpClient.fromRemote] Request timeout when fetching %s",e),r(null)}),l.end()}catch(t){log55.errorf("❌ [HttpClient.fromRemote] Error fetching content from %s: %s",e,t),r(null)}})}}}});import*as path25 from"path";import{createHash as createHash5}from"crypto";import{Readable as Readable2}from"stream";var ResourcePaths,init_resources=__esm({"internal/domain/resources/entity/resources.ts"(){init_resource(),init_resources2(),init_minifier(),init_integrity(),init_template4(),init_publisher2(),init_http2(),init_type6(),init_log(),log56=getDomainLogger("resources",{component:"resources"}),Resources=class{cache=new Map;workspace;fsSvc;urlSvc;templateSvc;publisher;minifierClient;integrityClient;templateClient=null;httpClient;constructor(e){this.workspace=e,this.fsSvc=e,this.urlSvc=e,this.templateSvc=e,this.publisher=new Publisher2(e.publishFs(),e),this.minifierClient=new MinifierClient,this.integrityClient=new IntegrityClient,this.templateClient=new TemplateClient(this.templateSvc),this.httpClient=new HttpClient4}setTemplateSvc(e){this.templateSvc=e,this.templateClient=new TemplateClient(e)}async getResource(e){const t=path25.posix.normalize(e),r=`${t}__get`;if(this.cache.has(r))return this.cache.get(r)||null;try{const e=this.workspace.assetsFs();if(!await e.stat(t))return null;const i=async()=>{const r=await e.open(t);return await this.createReadSeekCloser(r)},s=await this.buildResource(t,i);return s&&this.cache.set(r,s),s}catch(e){return log56.errorf("❌ [Resources.getResource] Error getting resource %s, %s",t,e),null}}async getResourceWithOpener(e,t){const r=path25.posix.normalize(e),i=`${r}__get_with_opener`;if(this.cache.has(i))return this.cache.get(i)||null;try{const e=await this.buildResource(r,t);return e&&this.cache.set(i,e),e}catch(e){return log56.errorf("❌ [Resources.getResourceWithOpener] Error getting resource with opener %s, %s",r,e),null}}async executeAsTemplate(e,t,r){if(!this.templateClient)throw new Error("Template client not available. Please set template client first.");const i=e.key()+"-template-"+t,s=this.cacheKey(i);if(this.cache.has(s))return this.cache.get(s);try{const i=await this.templateClient.executeAsTemplate(e,t,r);return i?this.cache.set(s,i):log56.warnf("⚠️ [Resources.executeAsTemplate] Template execution returned null for resource %s",e.key()),i}catch(t){throw log56.errorf("❌ [Resources.executeAsTemplate] Error executing template %s, %s",e.key(),t),t}}async minify(e){if(!this.minifierClient)throw new Error("Minifier client not available. Please set minifier client first.");const t=e.key()+"-minify",r=this.cacheKey(t);if(this.cache.has(r))return this.cache.get(r);try{const t=await this.minifierClient.minify(e);return t?this.cache.set(r,t):log56.warnf("⚠️ [Resources.minify] Minification returned null for resource %s",e.key()),t}catch(t){throw log56.errorf("❌ [Resources.minify] Error minifying resource %s, %s",e.key(),t),t}}async fingerprint(e){const t=e.key()+"-fingerprint",r=this.cacheKey(t);if(this.cache.has(r))return this.cache.get(r);try{const t=await this.integrityClient.fingerprint(e);return t?this.cache.set(r,t):log56.warnf("⚠️ [Resources.fingerprint] Fingerprint operation returned null for resource %s",e.key()),t}catch(t){throw log56.errorf("❌ [Resources.fingerprint] Error fingerprinting resource %s, %s",e.key(),t),t}}async getRemote(e){const t=`${e}__remote`;if(this.cache.has(t))return this.cache.get(t)||null;try{const r=await this.httpClient.fromRemote(e);if(!r)return null;const i=async()=>this.newReadSeekerNoOpCloserFromString(r),s=await this.buildResource(e,i);return s&&this.cache.set(t,s),s}catch(t){return log56.errorf("❌ [Resources.fromRemote] Error getting remote resource %s, %s",e,t),null}}cacheKey(e){return createHash5("sha256").update(e).digest("hex").substring(0,16)}getMinifierClient(){return this.minifierClient}getIntegrityClient(){return this.integrityClient}setTemplateClient(e){this.templateClient=e}async buildResource(e,t){try{const r=path25.extname(e),i=this.getMediaTypeFromExtension(r),s=ResourcePaths.newResourcePaths(e,this.workspace);return new ResourceImpl(t,i,s,{},this.publisher)}catch(t){return log56.errorf("❌ [Resources.buildResource] Error building resource for %s, %s",e,t),null}}getMediaTypeFromExtension(e){const t={".js":{type:"text/javascript",mainType:"text",subType:"javascript"},".css":{type:"text/css",mainType:"text",subType:"css"},".html":{type:"text/html",mainType:"text",subType:"html"},".json":{type:"application/json",mainType:"application",subType:"json"},".svg":{type:"image/svg+xml",mainType:"image",subType:"svg+xml"},".xml":{type:"application/xml",mainType:"application",subType:"xml"},".txt":{type:"text/plain",mainType:"text",subType:"plain"}},r=e?t[e]||t[".txt"]:t[".html"],i=e?e.substring(1):"html",s=e||".html";return new MediaType({type:r.type,mainType:r.mainType,subType:r.subType,delimiter:".",firstSuffix:{suffix:i,fullSuffix:s},mimeSuffix:"",suffixesCSV:i})}async createReadSeekCloser(e){try{const t=[];let r=0;try{for(;;){const i=new Uint8Array(8192),s=await e.read(i);if(0===s.bytesRead)break;r+=s.bytesRead,t.push(i.slice(0,s.bytesRead))}}finally{await e.close()}let i="";if(t.length>0){const e=new Uint8Array(r);let s=0;for(const r of t)e.set(r,s),s+=r.length;i=(new TextDecoder).decode(e)}return this.newReadSeekerNoOpCloserFromString(i)}catch(t){try{await e.close()}catch(t){log56.warnf("❌ [Resources.createReadSeekCloser] Error closing file after read error %s, %s",e.path,t)}return this.newReadSeekerNoOpCloserFromString("")}}newReadSeekerNoOpCloserFromString(e){const t=new Readable2({read(){}});return t.push(e),t.push(null),Object.assign(t,{seek:async(e,t)=>0,close:async()=>Promise.resolve()})}}}});import*as path26 from"path";var ResourceTransformationKey,init_resourcepaths=__esm({"internal/domain/resources/valueobject/resourcepaths.ts"(){ResourcePaths=class e{dir;baseDirTarget;baseDirLink;targetBasePaths;file;baseUrl="";constructor(e="",t="",r="",i="",s=[],n=""){this.dir=e,this.file=t,this.baseDirTarget=r,this.baseDirLink=i,this.targetBasePaths=s,this.baseUrl=n}static newResourcePaths(t,r){const i=t.replace(/\\/g,"/"),s=path26.posix.parse(i);let n=s.dir;return"/"===n&&(n=""),new e(n,s.base,r.baseUrl(),r.baseUrl(),[],r.baseUrl())}join(...e){let t="";for(let r=0;r<e.length;r++){const i=e[r];if(i)if(""===t)t=i;else{const e=!t.endsWith("/")&&!i.startsWith("/"),r=t.endsWith("/")&&i.startsWith("/");t+=r?i.substring(1):e?"/"+i:i}}return t.startsWith("/")&&(t=t.substring(1)),t.endsWith("/")&&t.length>1&&(t=t.substring(0,t.length-1)),t}targetLink(){let e=this.join(this.baseDirLink,this.dir,this.file);return e.startsWith("http://")||e.startsWith("https://")||e.startsWith("/")||(e="/"+e),e}targetPath(){return this.join(this.dir,this.file)}fromTargetPath(t){const r=t.replace(/\\/g,"/"),i=path26.posix.parse(r);let s=i.dir;return"/"===s&&(s=""),new e(s,i.base,this.baseUrl,this.baseUrl,this.targetBasePaths,this.baseUrl)}pathDir(){return this.dir}pathBaseDirTarget(){return this.baseDirTarget}pathBaseDirLink(){return this.baseDirLink}pathTargetBasePaths(){return this.targetBasePaths}pathFile(){return this.file}}}});import{createHash as createHash6}from"crypto";var ResourceMetadataImpl,log57,configCache,modulesCache,fsCache,contentCache,resourcesCache,siteCache,createDomainInstances,tasks,init_transformation=__esm({"internal/domain/resources/valueobject/transformation.ts"(){ResourceTransformationKey=class e{constructor(e,t=[]){this.name=e,this.elements=t}static newResourceTransformationKey(t,...r){return new e(t,r)}value(){if(0===this.elements.length)return this.name;const e=this.hashElements(...this.elements);return`${this.name}_${e}`}hashElements(...e){const t=e.map(e=>String(e)).join("|");return createHash6("sha256").update(t).digest("hex").substring(0,16)}}}}),init_resourcemetadata=__esm({"internal/domain/resources/valueobject/resourcemetadata.ts"(){ResourceMetadataImpl=class e{constructor(e,t,r){this.target=e,this.mediaType=t,this.metaData=r}marshal(){return JSON.stringify({Target:this.target,MediaType:this.mediaType,Data:this.metaData})}static unmarshal(t){const r=JSON.parse(t);return new e(r.Target,r.MediaType,r.Data||{})}}}}),init_resource2=__esm({"internal/domain/resources/factory/resource.ts"(){init_resources()}}),init_resources2=__esm({"internal/domain/resources/index.ts"(){init_type9(),init_resources(),init_resource(),init_minifier(),init_integrity(),init_template4(),init_resourcepaths(),init_transformation(),init_resourcemetadata(),init_resource2()}}),ssg_exports={};__export(ssg_exports,{collectAllPageTasks:()=>collectAllPageTasks,generateStaticSite:()=>generateStaticSite,generateStaticSiteWithProgress:()=>generateStaticSiteWithProgress,processSSG:()=>processSSG,processSSGWithProgress:()=>processSSGWithProgress,serveSSG:()=>serveSSG});import path27 from"path";function setDomainInstances(e,t,r,i,s,n,a){siteCache=e,contentCache=t,fsCache=r,configCache=i,modulesCache=s,resourcesCache=n}async function loadConfiguration(e,t){const r=new OsFs,i=path27.join(e,"config.json");return await loadConfigWithParams(r,i,e,t)}async function createFileSystem(e,t){const r={path:e.getDir().getWorkingDir(),publish:e.getDir().getPublishDir(),osFs:e.fs()};return await createFs(r,t)}async function createContentEngine(e,t,r,i){const s={baseUrl:()=>t.getRoot().baseUrl(),markdown:()=>i,useInternalRenderer:()=>t.getMarkdown().useInternalRenderer(),isWikilinkEnabled:()=>t.getMarkdown().isWikilinkEnabled(),isTagEnabled:()=>t.getMarkdown().isTagEnabled(),isCalloutEnabled:()=>t.getMarkdown().isCalloutEnabled(),isLatexEnabled:()=>t.getMarkdown().isLatexEnabled(),isMermaidEnabled:()=>t.getMarkdown().isMermaidEnabled(),newFileMetaInfo:t=>e.newFileMetaInfo(t),newFileMetaInfoWithContent:t=>e.newFileMetaInfoWithContent(t),contentFs:()=>e.contentFs(),walkContent:(t,r,i,s)=>e.walkContent(t,r,i,s),walkI18n:(t,r,i)=>e.walkI18n(t,r,i),isLanguageValid:e=>t.getLanguage().isLanguageValid(e),getSourceLang:e=>r.getSourceLang(e),getLanguageIndex:e=>t.getLanguage().getLanguageIndex(e),getLanguageByIndex:e=>t.getLanguage().getLanguageByIndex(e),defaultLanguage:()=>t.getLanguage().defaultLanguage(),languageIndexes:()=>t.getLanguage().languageIndexes(),views:()=>t.getTaxonomy().getViews().map(e=>{const t=e.singular,r=e.plural;return{singular:()=>t||"",plural:()=>r||""}})};return await createContent(s)}function createResourcesEngine(e,t){return new Resources({assetsFs:()=>t.assetsFs(),publishFs:()=>t.publishFs(),baseUrl:()=>e.getProvider().getString("baseURL")||"http://localhost",executeTemplate:async(e,t,r)=>{throw new Error("Template execution not initialized. Please call resources.setTemplateSvc() first.")}})}async function createTemplateEngineFromFs(e,t,r,i){const s=function(e,t,r){const i=e.getProvider().getString("baseURL")||"http://localhost";return{relURL:e=>t.getURL().relURL(e),absURL:e=>t.getURL().absURL(e,t.isMultipleLanguage(),t.languagePrefix()),urlize:e=>t.getURL().urlize(e),translate:e=>t.translate(e),relRefFrom:async(e,t)=>[e.path||"",null],title:()=>e.getProvider().getString("title")||"My Site",baseURL:()=>i,params:()=>e.getProvider().getParams("params"),menus:()=>({}),isMultiLanguage:()=>e.getLanguage().languageKeys().length>1,version:()=>"0.1.0",environment:()=>"development",generator:()=>"AuPro Static Site Generator",defaultLanguage:()=>e.getLanguage().defaultLanguage(),languageKeys:()=>e.getLanguage().languageKeys(),Get:async function(e){try{return await r.getResource(e)}catch(t){return log57.warn(`Resource not found: ${e}`,t),Promise.resolve(null)}},GetRemote:async function(e){return await r.getRemote(e)},Minify:async function(e){return await r.minify(e)},Fingerprint:async function(e){return await r.fingerprint(e)},ExecuteAsTemplate:async function(e,t,i){return await r.executeAsTemplate(i,e,t)}}}(t,r,i),n={walk:e.walkLayouts.bind(e)};return await async function(e,t){return(new Factory2).createWithServices(e,t)}(n,s)}async function createTemplateAdapter(e,t){return{async lookupLayout(t){const[r,i,s,n]=await e.findFirst(t);return n?{preparer:null,found:!1}:s&&r&&i?{preparer:{name:()=>i,execute:async e=>{const[t,i]=await r.Execute(e);if(i)throw log57.errorf("template exec error: %s",i),i;return t}},found:!0}:{preparer:null,found:!1}},async executeWithContext(e,t){if(!e)return"<html><body>Default template - no preparer</body></html>";try{return await e.execute(t)}catch(e){return log57.error(`❌ Template execution error: ${e}`),`<html><body>Template execution error: ${e}</body></html>`}}}}function createSiteForSSG(e,t,r){return function(e){const t=new Publisher(e.publishFs()),r=new URL2(e.baseUrl(),!0),i=new Language2(e),s=new Author2("MDFriday","support@mdfriday.com"),n=new Organization2,a=new Compiler("0.1.0"),o=new Site(e,e,e,e,e,e,t,s,n,a,r,null,i,null,e.siteTitle()),l=function(e,t,r){return new NavigationFactory(e,t,r)}(e,e,o);return o.navigation=l.createNavigation(),o.ref=new Ref({home:{page:null},sitePage:async e=>{const t=await o.sitePage(e);return{relPermalink:()=>t.path?t.path():"",permalink:()=>t.path?t.path():""}}},e,"/404.html"),o}({configParams:()=>e.getProvider().getParams("params"),siteTitle:()=>e.getProvider().getString("title")||"My Site",menus:()=>({}),isGoogleAnalyticsEnabled:()=>e.getService().isGoogleAnalyticsEnabled(),googleAnalyticsID:()=>e.getService().googleAnalyticsID(),isGoogleAnalyticsRespectDoNotTrack:()=>e.getService().isGoogleAnalyticsRespectDoNotTrack(),isDisqusEnabled:()=>e.getService().isDisqusEnabled(),disqusShortname:()=>e.getService().disqusShortname(),isXRespectDoNotTrack:()=>e.getService().isXRespectDoNotTrack(),isXDisableInlineCSS:()=>e.getService().isXDisableInlineCSS(),getConfiguredSocialPlatforms:()=>e.getSocial().getConfiguredPlatforms(),getSocialLink:t=>{const r=e.getSocial().getSocialLink(t);return r?r.url:""},getSocialTitle:t=>{const r=e.getSocial().getSocialLink(t);return r?r.title:""},globalPages:async e=>await r.globalPages(e),globalRegularPages:async()=>await r.globalRegularPages(),walkPages:async(e,t)=>{await r.walkPages(e,t)},getPageSources:async e=>r.getPageSources(e),walkTaxonomies:async(e,t)=>{await r.walkTaxonomies(e,t)},searchPage:async(e,t)=>[],getPageFromPath:async(e,t)=>{try{const i=r.getPageFromPath(e,t);return i||log57.error(`⚠️ Application.getPageFromPath: content domain returned null for path: "${t}"`),i}catch(e){return log57.error("❌ Application.getPageFromPath error delegating to content domain:",e),null}},getPageFromPathSync:(e,t)=>{try{const i=r.getPageFromPath(e,t);return i||log57.warn(`⚠️ Application.getPageFromPathSync: content domain returned null for path: ${t}`),i}catch(e){return log57.error("❌ Application.getPageFromPathSync error delegating to content domain:",e),null}},getPageRef:async(e,t,r)=>null,translate:(e,t)=>r.translate(e,t),defaultLanguage:()=>e.getLanguage().defaultLanguage(),languageKeys:()=>e.getLanguage().languageKeys(),getLanguageIndex:t=>e.getLanguage().getLanguageIndex(t),getLanguageName:t=>e.getLanguage().getLanguageName(t),changeFreq:()=>"weekly",priority:()=>.5,generateSitemap:async()=>({urls:[]}),publishFs:()=>t.publishFs(),staticFs:()=>t.staticFs(),copyStaticFiles:(e,r)=>t.copyStatic([e],r),workingDir:()=>e.getProvider().getString("workingDir")||process.cwd(),getResource:async e=>null,getResourceWithOpener:async(e,t)=>({name:()=>e,readSeekCloser:t,targetPath:()=>e}),baseUrl:()=>e.getProvider().getString("baseURL")||"http://localhost"})}async function generateStaticSite(e,t,r){try{let i=performance.now();const s=await loadConfiguration(e,t);let n=performance.now();log57.info(`✅ Configuration loaded in ${(n-i).toFixed(2)} ms`);const a=r;i=performance.now();const o=await async function(e){const t={osFs:()=>e.fs(),projDir:()=>e.getDir().getWorkingDir(),moduleDir:()=>e.getDir().getThemesDir(),moduleCacheDir:()=>e.getDir().getThemesCacheDir(),importPaths:()=>e.getModule().importPaths(),defaultLanguageKey:()=>e.getLanguage().defaultLanguage(),otherLanguageKeys:()=>e.getLanguage().otherLanguageKeys(),getRelDir:(t,r)=>e.getLanguage().getRelDir(t,r)};return await async function(e){try{const t=e.httpClient?.(),r=newHttpClient(e.osFs(),void 0,void 0,t),i=newZipExtractor(e.osFs()),s=newModuleCache(e.osFs(),e.moduleCacheDir()),n=newModules(e,r,i,s);return await n.load(),n}catch(e){const t=e instanceof Error?e.message:String(e);throw log5.error(`Failed to create modules: ${t}`),new ModuleError(`Failed to create modules: ${t}`,"FACTORY_FAILED")}}(t)}(s);n=performance.now(),log57.info(`✅ Modules created in ${(n-i).toFixed(2)} ms`),i=performance.now();const l=await createFileSystem(s,o);n=performance.now(),log57.info(`✅ Filesystem created in ${(n-i).toFixed(2)} ms`);const c=await createContentEngine(l,s,o,a),h=createSiteForSSG(s,l,c),u=createResourcesEngine(s,l),g=await createTemplateEngineFromFs(l,s,h,u);u.setTemplateSvc({executeTemplate:async(e,t,r)=>await g.executeRaw(e,t,r)}),c.setTemplateSvc({execute:async(e,t)=>await g.executeShortcode(e,t)}),i=performance.now(),await c.collectPages(),n=performance.now(),log57.info(`✅ Pages collected in ${(n-i).toFixed(2)} ms`);const d=await createTemplateAdapter(g);i=performance.now(),await h.build(d),n=performance.now(),setDomainInstances(h,c,l,s,o,u),log57.info(`✅ Site built in ${(n-i).toFixed(2)} ms`)}catch(e){const t=e instanceof Error?e.message:String(e);throw log57.error(`❌ Static site generation failed: ${t}`),new Error(`Failed to generate static site: ${t}`)}}async function processSSG(e,t,r){try{const i=process.cwd();process.chdir(e);try{await generateStaticSite(e,t,r)}finally{process.chdir(i)}}catch(e){const t=e instanceof Error?e.message:String(e);throw log57.error(`❌ SSG processing failed: ${t}`),new Error(`Failed to process SSG: ${t}`)}}async function generateStaticSiteWithProgress(e,t,r,i,s){try{i?.({stage:"config",message:"Loading configuration...",percentage:5});const n=await loadConfiguration(e,t),a=r;i?.({stage:"modules",message:"Creating and downloading modules...",percentage:10});const o=await createModuleWithProgress(n,i,s);i?.({stage:"filesystem",message:"Creating filesystem...",percentage:30});const l=await createFileSystem(n,o);i?.({stage:"content",message:"Creating content engine...",percentage:40});const c=await createContentEngine(l,n,o,a);i?.({stage:"site",message:"Creating site...",percentage:50});const h=createSiteForSSG(n,l,c),u=createResourcesEngine(n,l);i?.({stage:"template",message:"Creating template engine...",percentage:60});const g=await createTemplateEngineFromFs(l,n,h,u);u.setTemplateSvc({executeTemplate:async(e,t,r)=>await g.executeRaw(e,t,r)}),c.setTemplateSvc({execute:async(e,t)=>await g.executeShortcode(e,t)}),i?.({stage:"pages",message:"Collecting pages...",percentage:65}),await c.collectPages(),i?.({stage:"build",message:"Building site...",percentage:70});const d=await createTemplateAdapter(g);return await async function(e,t,r){const i=r?e=>{const t=70+Math.floor(e.currentPage/e.totalPages*29);r({stage:"build",message:`Rendering pages (${e.currentPage}/${e.totalPages})...`,percentage:t,pageRender:e})}:void 0;await e.buildWithProgress(t,i)}(h,d,i),i?.({stage:"completion",message:"SSG generation completed",percentage:100}),setDomainInstances(h,c,l,n,o,u),createDomainInstances(siteCache,contentCache,fsCache,configCache,modulesCache,resourcesCache)}catch(e){const t=e instanceof Error?e.message:String(e);throw log57.error(`❌ Static site generation failed: ${t}`),new Error(`Failed to generate static site: ${t}`)}}async function createModuleWithProgress(e,t,r){const i={osFs:()=>e.fs(),projDir:()=>e.getDir().getWorkingDir(),moduleDir:()=>e.getDir().getThemesDir(),moduleCacheDir:()=>e.getDir().getThemesCacheDir(),importPaths:()=>e.getModule().importPaths(),defaultLanguageKey:()=>e.getLanguage().defaultLanguage(),otherLanguageKeys:()=>e.getLanguage().otherLanguageKeys(),getRelDir:(t,r)=>e.getLanguage().getRelDir(t,r),httpClient:r?()=>r:void 0};return await async function(e,t){const r=t?e=>{t({stage:"modules",message:`Downloading module: ${e.modulePath}`,percentage:10+Math.floor(.2*e.downloadPercentage),moduleDownload:{modulePath:e.modulePath,downloadPercentage:e.downloadPercentage}})}:void 0;return await async function(e,t){try{const r=e.httpClient?.(),i=newHttpClient(e.osFs(),void 0,void 0,r),s=newZipExtractor(e.osFs()),n=newModuleCache(e.osFs(),e.moduleCacheDir()),a=newModules(e,i,s,n);return await a.load(t),a}catch(e){const t=e instanceof Error?e.message:String(e);throw log5.error(`Failed to create modules: ${t}`),new ModuleError(`Failed to create modules: ${t}`,"FACTORY_FAILED")}}(e,r)}(i,t)}async function processSSGWithProgress(e,t,r,i,s){try{const n=process.cwd();process.chdir(e);try{await generateStaticSiteWithProgress(e,t,r,i,s)}finally{process.chdir(n)}}catch(e){const t=e instanceof Error?e.message:String(e);throw log57.error(`❌ SSG processing failed: ${t}`),new Error(`Failed to process SSG: ${t}`)}}async function serveSSG(e,t,r,i,s){try{return process.chdir(e),await generateStaticSiteWithProgress(e,t,r,i,s)}catch(e){const t=e instanceof Error?e.message:String(e);throw log57.error(`❌ SSG processing failed: ${t}`),new Error(`Failed to process SSG: ${t}`)}}async function collectAllPageTasks(e,t,r,i,s){if(tasks.length>0)return log57.info("Page tasks already collected, returning cached tasks"),tasks;try{let n=performance.now();const a=await loadConfiguration(e,t);let o=performance.now();log57.info(`✅ Configuration loaded in ${(o-n).toFixed(2)} ms`);const l=r;n=performance.now();const c=await createModuleWithProgress(a,i,s);o=performance.now(),log57.info(`✅ Modules created in ${(o-n).toFixed(2)} ms`),n=performance.now();const h=await createFileSystem(a,c);o=performance.now(),log57.info(`✅ Filesystem created in ${(o-n).toFixed(2)} ms`);const u=await createContentEngine(h,a,c,l),g=createSiteForSSG(a,h,u),d=createResourcesEngine(a,h),p=await createTemplateEngineFromFs(h,a,g,d);d.setTemplateSvc({executeTemplate:async(e,t,r)=>await p.executeRaw(e,t,r)}),u.setTemplateSvc({execute:async(e,t)=>await p.executeShortcode(e,t)}),n=performance.now(),await u.collectPages(),o=performance.now(),log57.info(`✅ Pages collected in ${(o-n).toFixed(2)} ms`),n=performance.now();const m=a.getLanguage().languageKeys();for(const e of m){const t=a.getLanguage().getLanguageIndex(e);await u.walkPages(t,async t=>{const r=t.file().paths().base();tasks.push({language:e,pagePath:r}),t&&t.pageIdentity&&t.pageIdentity().clearStale()}),log57.debug(`Collected pages for language: ${e}`)}o=performance.now(),log57.info(`✅ Page tasks collected in ${(o-n).toFixed(2)} ms`);const f=await createTemplateAdapter(p);return n=performance.now(),await g.build(f),o=performance.now(),log57.info(`✅ Site built in ${(o-n).toFixed(2)} ms`),setDomainInstances(g,u,h,a,c,d),tasks}catch(e){const t=e instanceof Error?e.message:String(e);throw log57.error(`❌ Static site generation failed: ${t}`),new Error(`Failed to generate static site: ${t}`)}}var WorkspaceMetadata,ProjectMetadata,init_ssg=__esm({"internal/application/ssg.ts"(){init_config3(),init_module6(),init_fs3(),init_content3(),init_template3(),init_site2(),init_log(),init_resources2(),log57=getDomainLogger("ssg",{component:"application"}),createDomainInstances=(e,t,r,i,s,n)=>({site:e,content:t,fs:r,config:i,modules:s,resources:n}),tasks=[]}}),init_type10=__esm({"internal/domain/workspace/type.ts"(){}}),init_workspace_metadata=__esm({"internal/domain/workspace/value-object/workspace-metadata.ts"(){WorkspaceMetadata=class e{version;id;name;createdAt;updatedAt;paths;defaults;constructor(e){this.version=e.version,this.id=e.id,this.name=e.name,this.createdAt=e.createdAt,this.updatedAt=e.updatedAt,this.paths={...e.paths},this.defaults=e.defaults?{...e.defaults}:{}}static create(t){if(!t.id||!t.name)throw new Error("Workspace ID and name are required");return new e(t)}update(t){return new e({...this,...t,updatedAt:Date.now()})}toJSON(){const e={version:this.version,id:this.id,name:this.name,createdAt:this.createdAt,updatedAt:this.updatedAt,paths:{...this.paths}};return this.defaults&&Object.keys(this.defaults).length>0&&(e.defaults={...this.defaults}),e}}}}),project_metadata_exports={};__export(project_metadata_exports,{ProjectMetadata:()=>ProjectMetadata});var FolderStructure,log68,Workspace,log69,Project,Authentication,Email,Token2,ServerConfig,License,SyncConfig,Device,User,log71,UserFactory,init_project_metadata=__esm({"internal/domain/workspace/value-object/project-metadata.ts"(){ProjectMetadata=class e{id;name;type;workspaceId;createdAt;updatedAt;buildHistory;previews;contentLinks;staticLink;fileLink;baseURLStructure;constructor(e){this.id=e.id,this.name=e.name,this.type=e.type||"site",this.workspaceId=e.workspaceId||"",this.createdAt=e.createdAt,this.updatedAt=e.updatedAt,this.buildHistory=e.buildHistory||[],this.previews=e.previews||{},this.contentLinks=e.contentLinks||[],this.staticLink=e.staticLink||null,this.fileLink=e.fileLink||null,this.baseURLStructure=e.baseURLStructure||null}static create(t){if(!t.id||!t.name)throw new Error("Project ID and name are required");return new e(t)}update(t){return new e({...this,...t,updatedAt:Date.now()})}toJSON(){const e={id:this.id,name:this.name,type:this.type,createdAt:this.createdAt,updatedAt:this.updatedAt};return this.workspaceId&&(e.workspaceId=this.workspaceId),this.buildHistory&&this.buildHistory.length>0&&(e.buildHistory=this.buildHistory),this.previews&&Object.keys(this.previews).length>0&&(e.previews=this.previews),this.contentLinks&&this.contentLinks.length>0&&(e.contentLinks=this.contentLinks),this.staticLink&&(e.staticLink=this.staticLink),this.fileLink&&(e.fileLink=this.fileLink),this.baseURLStructure&&(e.baseURLStructure=this.baseURLStructure),e}}}}),init_folder_structure=__esm({"internal/domain/workspace/value-object/folder-structure.ts"(){FolderStructure=class e{rootPath;contentFolders;staticFolder;isStructured;constructor(e,t,r,i){this.rootPath=e,this.contentFolders=t,this.staticFolder=r,this.isStructured=i}static fromScanResult(t){return new e(t.rootPath,t.contentFolders,t.staticFolder,t.isStructured)}static createEmpty(t){return new e(t,[],null,!1)}static createSingleContent(t,r,i="en"){return new e(t,[{path:r,languageCode:i,weight:0}],null,!0)}getRootPath(){return this.rootPath}getContentFolders(){return[...this.contentFolders]}getStaticFolder(){return this.staticFolder?{...this.staticFolder}:null}getIsStructured(){return this.isStructured}hasContentFolders(){return this.contentFolders.length>0}hasStaticFolder(){return null!==this.staticFolder}getContentFolderCount(){return this.contentFolders.length}getDefaultContentFolder(){return this.contentFolders.find(e=>0===e.weight)||null}getLanguageContentFolders(){return this.contentFolders.filter(e=>e.weight>0)}getContentFolderByLanguage(e){return this.contentFolders.find(t=>t.languageCode===e)||null}getSupportedLanguages(){return this.contentFolders.map(e=>e.languageCode)}isValid(){return!this.isStructured||this.contentFolders.length>0}isMultilingual(){return this.contentFolders.length>1}getSummary(){if(!this.isStructured)return`Empty structure at ${this.rootPath}`;const e=[];if(e.push(`Structured folder at ${this.rootPath}:`),e.push(` - ${this.contentFolders.length} content folder(s)`),this.isMultilingual()){const t=this.getSupportedLanguages().join(", ");e.push(` Languages: ${t}`)}return this.staticFolder&&e.push(" - static folder"),e.join("\n")}toJSON(){return{rootPath:this.rootPath,contentFolders:this.contentFolders,staticFolder:this.staticFolder,isStructured:this.isStructured}}static fromJSON(t){return e.fromScanResult(t)}}}}),init_file_system=__esm({"internal/domain/workspace/repository/file-system.ts"(){}}),init_repository=__esm({"internal/domain/workspace/repository.ts"(){init_file_system()}}),init_workspace=__esm({"internal/domain/workspace/entity/workspace.ts"(){init_log(),log68=getDomainLogger("workspace",{component:"domain"}),Workspace=class{rootPath;metadata;projects;authentication;fileSystemRepo;constructor(e,t,r,i,s){if(this.rootPath=e,this.metadata=t,this.projects=r,this.authentication=i,this.fileSystemRepo=s,!this.fileSystemRepo)throw new Error("FileSystemRepository is required for Workspace")}getPath(){return this.rootPath}getMetadata(){return this.metadata}getId(){return this.metadata.id}getName(){return this.metadata.name}getModulesDir(){return this.fileSystemRepo.join(this.rootPath,this.metadata.paths.modules)}getProjectsDir(){return this.fileSystemRepo.join(this.rootPath,this.metadata.paths.projects)}updateMetadata(e){this.metadata=this.metadata.update(e),log68.debug("Workspace metadata updated",{workspaceId:this.getId()})}updateName(e){this.updateMetadata({name:e})}getProjects(){return Array.from(this.projects.values())}getProject(e){return this.projects.get(e)}getProjectByName(e){for(const t of this.projects.values())if(t.getName()===e)return t}findProject(e){return this.getProject(e)||this.getProjectByName(e)}hasProject(e){return this.projects.has(e)}addProject(e){if(this.projects.has(e.getId()))throw new Error(`Project ${e.getId()} already exists in workspace`);this.projects.set(e.getId(),e),log68.info(`Project added to workspace: ${e.getName()} (${e.getId()})`)}removeProject(e){const t=this.projects.get(e);return t?(this.projects.delete(e),log68.info(`Project removed from workspace: ${t.getName()} (${e})`),t):null}getProjectCount(){return this.projects.size}getProjectRegistry(){const e=[];for(const t of this.projects.values()){const r=t.getMetadata(),i=t.getPath(),s=this.fileSystemRepo.relative(this.getProjectsDir(),i);e.push({id:r.id,name:r.name,path:s,absolutePath:i,createdAt:r.createdAt,updatedAt:r.updatedAt,status:"active"})}return{version:"1.0",projects:e}}getAuthentication(){return this.authentication}hasAuthentication(){return this.authentication.hasAuth()}getConfigPath(){return this.fileSystemRepo.join(this.rootPath,".mdfriday","config.json")}async getConfig(e){const t=this.getConfigPath();try{const r=await this.fileSystemRepo.readFile(t,"utf-8"),i=JSON.parse(r);return this.getNestedValue(i,e)}catch(e){if(e.message?.includes("Cannot access path"))return;throw e}}async getAllConfig(){const e=this.getConfigPath();try{const t=await this.fileSystemRepo.readFile(e,"utf-8");return JSON.parse(t)}catch(e){if(e.message?.includes("Cannot access path"))return{};throw e}}async setConfig(e,t){const r=this.getConfigPath(),i=this.fileSystemRepo.dirname(r);await this.fileSystemRepo.createDirectory(i,!0);let s={};try{const e=await this.fileSystemRepo.readFile(r,"utf-8");s=JSON.parse(e)}catch(e){if(!e.message?.includes("Cannot access path"))throw e}this.setNestedValue(s,e,t),await this.fileSystemRepo.writeFile(r,JSON.stringify(s,null,2),"utf-8"),log68.debug(`Workspace config updated: ${e}`,{workspaceId:this.getId()})}async unsetConfig(e){const t=this.getConfigPath();try{const r=await this.fileSystemRepo.readFile(t,"utf-8"),i=JSON.parse(r),s=this.deleteNestedValue(i,e);return s&&(await this.fileSystemRepo.writeFile(t,JSON.stringify(i,null,2),"utf-8"),log68.debug(`Workspace config deleted: ${e}`,{workspaceId:this.getId()})),s}catch(e){if(e.message?.includes("Cannot access path"))return!1;throw e}}getNestedValue(e,t){const r=t.split(".");let i=e;for(const e of r){if(null==i||"object"!=typeof i)return;i=i[e]}return i}setNestedValue(e,t,r){const i=t.split(".");let s=e;for(let e=0;e<i.length-1;e++){const t=i[e];t in s&&"object"==typeof s[t]||(s[t]={}),s=s[t]}s[i[i.length-1]]=r}deleteNestedValue(e,t){const r=t.split(".");let i=e;for(let e=0;e<r.length-1;e++){const t=r[e];if(!(t in i)||"object"!=typeof i[t])return!1;i=i[t]}const s=r[r.length-1];return s in i&&(delete i[s],!0)}getInfo(){return{id:this.metadata.id,name:this.metadata.name,path:this.rootPath,createdAt:new Date(this.metadata.createdAt),updatedAt:new Date(this.metadata.updatedAt),modulesDir:this.metadata.paths.modules,projectsDir:this.metadata.paths.projects,projectCount:this.projects.size,hasAuth:this.authentication.hasAuth()}}}}}),init_project=__esm({"internal/domain/workspace/entity/project.ts"(){init_log(),log69=getDomainLogger("project",{component:"domain"}),Project=class{metadata;projectPath;config=null;fileSystemRepo;constructor(e,t,r){if(this.projectPath=e,this.metadata=t,this.fileSystemRepo=r,!this.fileSystemRepo)throw new Error("FileSystemRepository is required for Project")}getPath(){return this.projectPath}getMetadata(){return this.metadata}getId(){return this.metadata.id}getName(){return this.metadata.name}getType(){return this.metadata.type}getWorkspaceId(){return this.metadata.workspaceId}getBuildHistory(){return this.metadata.buildHistory||[]}addBuildHistory(e){const t=[e,...this.metadata.buildHistory||[]],r=t.length>50?t.slice(0,50):t;this.metadata=this.metadata.update({buildHistory:r}),log69.debug(`Added build history entry for project: ${this.metadata.name}`)}getLastBuildTime(){const e=this.getBuildHistory();return e.length>0?e[0].timestamp:void 0}updateName(e){this.metadata=this.metadata.update({name:e})}async loadConfig(){if(this.config)return this.config;try{const e=this.fileSystemRepo.join(this.projectPath,"config.json"),t=await this.fileSystemRepo.readFile(e,"utf-8");return this.config=JSON.parse(t),this.config}catch(e){return log69.warn(`Failed to load config for project ${this.metadata.name}, using defaults`),this.config={contentDir:"content",publishDir:"public",defaultContentLanguage:"zh"},this.config}}getConfig(){return this.config}async getContentDirs(){const e=await this.loadConfig(),t=[],r=e.contentDir||"content";if(t.push(this.fileSystemRepo.join(this.projectPath,r)),e.languages)for(const[i,s]of Object.entries(e.languages))s.contentDir&&s.contentDir!==r&&t.push(this.fileSystemRepo.join(this.projectPath,s.contentDir));return[...new Set(t)]}async getPublishDir(){const e=(await this.loadConfig()).publishDir||"public";return this.fileSystemRepo.join(this.projectPath,e)}getStaticDir(){return this.fileSystemRepo.join(this.projectPath,"static")}async getDefaultLanguage(){return(await this.loadConfig()).defaultContentLanguage||"zh"}async getLanguages(){const e=await this.loadConfig();return e.languages?Object.keys(e.languages):[await this.getDefaultLanguage()]}getConfigPath(){return this.fileSystemRepo.join(this.projectPath,"config.json")}getConfigValue(e){if(!this.config)throw new Error("Configuration not loaded. Call loadConfig() first.");return this.getNestedValue(this.config,e)}setConfigValue(e,t){if(!this.config)throw new Error("Configuration not loaded. Call loadConfig() first.");this.setNestedValue(this.config,e,t),log69.debug(`Project config updated: ${e}`,{projectName:this.metadata.name})}setConfig(e){if(null===this.config)throw new Error("Configuration not loaded. Call loadConfig() first.");this.config=e,log69.debug("Project config replaced entirely",{projectName:this.metadata.name})}unsetConfigValue(e){if(!this.config)throw new Error("Configuration not loaded. Call loadConfig() first.");const t=this.deleteNestedValue(this.config,e);return t&&log69.debug(`Project config deleted: ${e}`,{projectName:this.metadata.name}),t}async saveConfig(){if(!this.config)throw new Error("Configuration not loaded. Call loadConfig() first.");const e=this.getConfigPath();await this.fileSystemRepo.writeFile(e,JSON.stringify(this.config,null,2),"utf-8"),log69.debug(`Project config saved: ${e}`,{projectName:this.metadata.name})}getNestedValue(e,t){const r=t.split(".");let i=e;for(const e of r){if(null==i||"object"!=typeof i)return;i=i[e]}return i}setNestedValue(e,t,r){const i=t.split(".");let s=e;for(let e=0;e<i.length-1;e++){const t=i[e];t in s&&"object"==typeof s[t]&&!Array.isArray(s[t])||(s[t]={}),s=s[t]}s[i[i.length-1]]=r}deleteNestedValue(e,t){const r=t.split(".");let i=e;for(let e=0;e<r.length-1;e++){const t=r[e];if(!(t in i)||"object"!=typeof i[t])return!1;i=i[t]}const s=r[r.length-1];return s in i&&(delete i[s],!0)}async readFile(e,t="utf-8"){const r=this.fileSystemRepo.join(this.projectPath,e);return this.fileSystemRepo.readFile(r,t)}async writeFile(e,t,r="utf-8"){const i=this.fileSystemRepo.join(this.projectPath,e),s=this.fileSystemRepo.dirname(i);await this.fileSystemRepo.exists(s)||await this.fileSystemRepo.createDirectory(s,!0),await this.fileSystemRepo.writeFile(i,t,r),log69.debug(`Project file written: ${e}`,{projectName:this.metadata.name,filePath:i})}async fileExists(e){const t=this.fileSystemRepo.join(this.projectPath,e);return this.fileSystemRepo.exists(t)}getFilePath(e){return this.fileSystemRepo.join(this.projectPath,e)}getInfo(){const e=this.getLastBuildTime(),t={id:this.metadata.id,name:this.metadata.name,path:this.projectPath,createdAt:new Date(this.metadata.createdAt),updatedAt:new Date(this.metadata.updatedAt),buildCount:this.getBuildHistory().length};return e&&(t.lastBuild=new Date(e)),t}getSnapshotsDir(){return this.fileSystemRepo.join(this.projectPath,".mdfriday","snapshots")}hasSourceLinks(){return this.metadata.contentLinks.length>0||null!==this.metadata.staticLink}getContentLinks(){return[...this.metadata.contentLinks]}getStaticLink(){return this.metadata.staticLink?{...this.metadata.staticLink}:null}getFileLink(){return this.metadata.fileLink?{...this.metadata.fileLink}:null}setContentLinks(e){this.metadata=this.metadata.update({contentLinks:e}),log69.debug(`Updated content links for project: ${this.metadata.name}`,{count:e.length})}setStaticLink(e){this.metadata=this.metadata.update({staticLink:e}),log69.debug(`Updated static link for project: ${this.metadata.name}`,{hasLink:null!==e})}addContentLink(e,t,r){const i=[...this.getContentLinks(),{sourcePath:e,languageCode:t,weight:r}];this.setContentLinks(i)}getDefaultContentSource(){const e=this.metadata.contentLinks.find(e=>0===e.weight);return e?e.sourcePath:null}getAllContentSources(){return this.metadata.contentLinks.map(e=>e.sourcePath)}getContentSourceByLanguage(e){const t=this.metadata.contentLinks.find(t=>t.languageCode===e);return t?t.sourcePath:null}getSupportedLanguagesFromLinks(){return this.metadata.contentLinks.map(e=>e.languageCode)}isLinkedProject(){return this.hasSourceLinks()}getLinkDirs(){const e=[],t=this.getFileLink();t&&e.push(t.sourcePath);const r=this.getContentLinks();for(const t of r)e.includes(t.sourcePath)||e.push(t.sourcePath);return e}async getBaseURL(){return(await this.loadConfig()).baseURL||"/"}async setBaseURL(e){const t=await this.loadConfig();t.baseURL=e;const r=this.fileSystemRepo.join(this.projectPath,"config.json");await this.fileSystemRepo.writeFile(r,JSON.stringify(t,null,2),"utf-8"),this.config=t}parseBaseURLPath(e){let t=e.trim();if(t.startsWith("/")&&(t=t.slice(1)),t.endsWith("/")&&(t=t.slice(0,-1)),""===t)return{isRoot:!0,pathParts:[],parentParts:[],finalDirName:"",relativeToPublic:"."};const r=t.split("/").filter(e=>""!==e);if(0===r.length)return{isRoot:!0,pathParts:[],parentParts:[],finalDirName:"",relativeToPublic:"."};const i=r.length,s=1===i?".":"../".repeat(i-1).slice(0,-1);return{isRoot:!1,pathParts:r,parentParts:r.slice(0,-1),finalDirName:r[r.length-1],relativeToPublic:s}}getBaseURLStructure(){return this.metadata.baseURLStructure||null}updateBaseURLStructure(e){this.metadata=this.metadata.update({baseURLStructure:e})}}}}),init_authentication=__esm({"internal/domain/workspace/entity/authentication.ts"(){init_log(),getDomainLogger("workspace-auth",{component:"domain"}),Authentication=class{workspacePath;hasAuthFile=!1;constructor(e,t=!1){this.workspacePath=e,this.hasAuthFile=t}getWorkspacePath(){return this.workspacePath}hasAuth(){return this.hasAuthFile}markAuthExists(){this.hasAuthFile=!0}markAuthDeleted(){this.hasAuthFile=!1}getAuthFilePath(){return".mdfriday/auth-user.json"}getServerConfigPath(){return".mdfriday/server-config.json"}}}}),init_email=__esm({"internal/domain/identity/value-object/email.ts"(){Email=class e{value;constructor(e){this.value=e}static create(t){if(!e.isValid(t))throw new Error(`Invalid email address: ${t}`);return new e(t)}static isValid(e){return!(!e||"string"!=typeof e)&&/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(e)}getValue(){return this.value}getDomain(){return this.value.split("@")[1]}getLocalPart(){return this.value.split("@")[0]}equals(e){return this.value.toLowerCase()===e.value.toLowerCase()}toString(){return this.value}toJSON(){return this.value}}}}),init_token=__esm({"internal/domain/identity/value-object/token.ts"(){Token2=class e{value;expiresAt;constructor(e,t){this.value=e,this.expiresAt=t}static create(t,r){if(!t||"string"!=typeof t||0===t.trim().length)throw new Error("Token value cannot be empty");return new e(t,r)}static fromJSON(t){return e.create(t.token,t.expiresAt)}getValue(){return this.value}getExpiresAt(){return this.expiresAt}isExpired(){return!!this.expiresAt&&Date.now()>this.expiresAt}isValid(){return!this.isExpired()}getRemainingTime(){if(!this.expiresAt)return null;const e=this.expiresAt-Date.now();return e>0?e:0}equals(e){return this.value===e.value}toString(){return this.value}toJSON(){const e={token:this.value};return void 0!==this.expiresAt&&(e.expiresAt=this.expiresAt),e}}}}),init_server_config=__esm({"internal/domain/identity/value-object/server-config.ts"(){ServerConfig=class e{apiUrl;websiteUrl;constructor(e,t){this.apiUrl=e,this.websiteUrl=t}static create(t,r){if(!t||"string"!=typeof t||0===t.trim().length)throw new Error("API URL cannot be empty");if(!e.isValidUrl(t))throw new Error(`Invalid API URL: ${t}`);if(r&&!e.isValidUrl(r))throw new Error(`Invalid website URL: ${r}`);return new e(t,r)}static fromJSON(t){return e.create(t.apiUrl,t.websiteUrl)}static createDefault(){return e.create("https://app.mdfriday.com","https://mdfriday.com")}static isValidUrl(e){try{return new URL(e),!0}catch{return!1}}getApiUrl(){return this.apiUrl}getWebsiteUrl(){return this.websiteUrl}withApiUrl(t){return e.create(t,this.websiteUrl)}withWebsiteUrl(t){return e.create(this.apiUrl,t)}equals(e){return this.apiUrl===e.apiUrl&&this.websiteUrl===e.websiteUrl}toJSON(){const e={apiUrl:this.apiUrl};return void 0!==this.websiteUrl&&(e.websiteUrl=this.websiteUrl),e}}}}),init_license=__esm({"internal/domain/identity/value-object/license.ts"(){License=class e{key;plan;expiresAt;features;activatedAt;activated;firstTime;constructor(e,t,r,i,s,n=!1,a=!1){this.key=e,this.plan=t,this.expiresAt=r,this.features=i,this.activatedAt=s,this.activated=n,this.firstTime=a}static create(t,r,i,s,n,a,o){if(!e.isValidFormat(t))throw new Error(`Invalid license key format: ${t}`);return new e(t.toUpperCase(),r,i,s,n||Date.now(),a||!1,o||!1)}static fromJSON(t){return e.create(t.key,t.plan,t.expiresAt,t.features,t.activatedAt,t.activated,t.firstTime)}static isValidFormat(e){return/^MDF-[A-Z0-9]{4}-[A-Z0-9]{4}-[A-Z0-9]{4}$/i.test(e)}isExpired(){return Date.now()>this.expiresAt}isValid(){return!this.isExpired()}getDaysRemaining(){const e=this.expiresAt-Date.now();return Math.max(0,Math.ceil(e/864e5))}getEmail(){return`${this.key.replace(/^MDF-/i,"").toLowerCase()}@mdfriday.com`}getPassword(){const e=this.key.replace(/^MDF-/i,"").toLowerCase();return"undefined"!=typeof btoa?btoa(e):"undefined"!=typeof Buffer?Buffer.from(e).toString("base64"):this.manualBase64Encode(e)}manualBase64Encode(e){const t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";let r="",i=0;for(;i<e.length;){const s=e.charCodeAt(i++)<<16|(i<e.length?e.charCodeAt(i++):0)<<8|(i<e.length?e.charCodeAt(i++):0);r+=t.charAt(s>>18&63),r+=t.charAt(s>>12&63),r+=i-1<e.length?t.charAt(s>>6&63):"=",r+=i<e.length?t.charAt(63&s):"="}return r}getKey(){return this.key}getMaskedKey(){const e=this.key.split("-");return 4===e.length?`MDF-••••-••••-${e[3]}`:this.key.slice(0,-4).replace(/./g,"•")+this.key.slice(-4)}getPlan(){return this.plan}getFormattedPlan(){return this.plan.charAt(0).toUpperCase()+this.plan.slice(1).toLowerCase()}getExpiresAt(){return this.expiresAt}getFormattedExpiresAt(){return new Date(this.expiresAt).toLocaleDateString("en-US",{year:"numeric",month:"short",day:"numeric"})}getFeatures(){return{...this.features}}getActivatedAt(){return this.activatedAt}isActivated(){return this.activated}isFirstTime(){return this.firstTime}isTrial(){return"free"===this.plan}equals(e){return this.key===e.key}toJSON(){return{key:this.key,plan:this.plan,expiresAt:this.expiresAt,features:{...this.features},activatedAt:this.activatedAt,activated:this.activated,firstTime:this.firstTime}}toStorageFormat(){return{key:this.key,maskedKey:this.getMaskedKey(),plan:this.getFormattedPlan(),expiresAt:this.expiresAt,features:{...this.features},activatedAt:this.activatedAt,activated:this.activated,firstTime:this.firstTime,isValid:this.isValid(),daysRemaining:this.getDaysRemaining()}}}}}),init_sync_config=__esm({"internal/domain/identity/value-object/sync-config.ts"(){SyncConfig=class e{dbEndpoint;dbName;email;dbPassword;userDir;status;constructor(e){this.dbEndpoint=e.dbEndpoint,this.dbName=e.dbName,this.email=e.email,this.dbPassword=e.dbPassword,this.userDir=e.userDir,this.status=e.status||"active"}static create(t){if(!(t.dbEndpoint&&t.dbName&&t.email&&t.dbPassword))throw new Error("Missing required sync configuration fields");return new e(t)}static fromJSON(t){return e.create(t)}getDbEndpoint(){return this.dbEndpoint}getDbName(){return this.dbName}getEmail(){return this.email}getDbPassword(){return this.dbPassword}getUserDir(){return this.userDir}getStatus(){return this.status}isActive(){return"active"===this.status}getCouchDbUri(){return this.dbEndpoint.replace(`/${this.dbName}`,"")}toJSON(){return{dbEndpoint:this.dbEndpoint,dbName:this.dbName,email:this.email,dbPassword:this.dbPassword,userDir:this.userDir,status:this.status}}toObsidianLiveSyncFormat(){return{couchDB_URI:this.getCouchDbUri(),couchDB_DBNAME:this.dbName,couchDB_USER:this.email,couchDB_PASSWORD:this.dbPassword,encrypt:!0,syncOnStart:!0,syncOnSave:!0,liveSync:!0}}equals(e){return this.dbEndpoint===e.dbEndpoint&&this.dbName===e.dbName&&this.email===e.email}}}}),init_device=__esm({"internal/domain/identity/value-object/device.ts"(){Device=class e{id;name;type;constructor(e,t,r){this.id=e,this.name=t,this.type=r}static create(t,r,i){if(!t||0===t.trim().length)throw new Error("Device ID cannot be empty");if(!r||0===r.trim().length)throw new Error("Device name cannot be empty");return new e(t,r,i)}static async createFromEnvironment(){const t=await e.generateFingerprint(),r=e.getDeviceName(),i=e.getDeviceType();return e.create(t,r,i)}static async generateFingerprint(){const e=[],t=globalThis,r=t.screen;r&&(e.push(`${r.width}x${r.height}`),e.push(`${r.colorDepth}`),e.push(`${r.pixelDepth||0}`));const i=t.navigator;i&&(e.push(i.language||""),e.push(i.platform||""),e.push(String(i.hardwareConcurrency||0)),e.push(String(i.maxTouchPoints||0)));const s=t.process;s&&s.versions&&(e.push(s.platform),e.push(s.arch),e.push(s.version));try{"undefined"!=typeof Intl&&e.push(Intl.DateTimeFormat().resolvedOptions().timeZone||"")}catch{e.push("")}if(i){const t=(i.userAgent||"").split(" ").slice(0,3).join(" ");e.push(t)}const n=e.join("|"),a=(new TextEncoder).encode(n),o=t.crypto;if(o&&o.subtle)try{const e=await o.subtle.digest("SHA-256",a);return Array.from(new Uint8Array(e)).map(e=>e.toString(16).padStart(2,"0")).join("")}catch{}let l=0;for(let e=0;e<n.length;e++)l=(l<<5)-l+n.charCodeAt(e),l&=l;return Math.abs(l).toString(16).padStart(8,"0")}static getDeviceName(){const e=globalThis,t=e.process;if(t&&t.versions){const e=t.platform;let r="Unknown OS";switch(e){case"darwin":r="macOS";break;case"win32":r="Windows";break;case"linux":r="Linux";break;default:r=e}return`Node.js on ${r}`}const r=e.navigator;if(!r)return"Unknown Device";const i=r.userAgent||"";let s="Unknown OS";i.includes("Mac")?s="macOS":i.includes("Windows")?s="Windows":i.includes("Linux")?s="Linux":i.includes("iPhone")||i.includes("iPad")?s="iOS":i.includes("Android")&&(s="Android");let n="Browser";return i.includes("Obsidian")?n="Obsidian":i.includes("Electron")&&(n="Electron"),`${n} on ${s}`}static getDeviceType(){const e=globalThis,t=e.process;if(t&&t.versions)return"desktop";const r=e.navigator;if(!r)return"desktop";const i=r.userAgent||"";return i.includes("Mobile")||i.includes("Android")||i.includes("iPhone")?"mobile":i.includes("Tablet")||i.includes("iPad")?"tablet":"desktop"}getId(){return this.id}getName(){return this.name}getType(){return this.type}equals(e){return this.id===e.id}toJSON(){return{id:this.id,name:this.name,type:this.type}}}}}),init_user=__esm({"internal/domain/identity/entity/user.ts"(){User=class{email;token;serverConfig;license;syncConfig;constructor(e,t,r,i=null,s=null){this.email=e,this.token=t,this.serverConfig=r,this.license=i,this.syncConfig=s}getEmail(){return this.email}getToken(){return this.token}getServerConfig(){return this.serverConfig}getLicense(){return this.license}getSyncConfig(){return this.syncConfig}setToken(e){this.token=e}clearToken(){this.token=null}updateServerConfig(e){this.serverConfig=e}setLicense(e){this.license=e}clearLicense(){this.license=null}setSyncConfig(e){this.syncConfig=e}clearSyncConfig(){this.syncConfig=null}isAuthenticated(){return!!this.token&&this.token.isValid()}isTokenExpired(){return!this.token||this.token.isExpired()}hasValidLicense(){return!!this.license&&this.license.isValid()}isTrialAccount(){return!!this.license&&this.license.isTrial()}getStatus(){const e={isAuthenticated:this.isAuthenticated(),email:this.email.getValue(),serverUrl:this.serverConfig.getApiUrl(),tokenExpired:this.isTokenExpired(),hasToken:null!==this.token,hasLicense:null!==this.license,license:this.license?.getKey(),licenseValid:this.hasValidLicense(),isTrial:this.isTrialAccount(),licensePlan:this.license?.getPlan(),licenseExpires:this.license?.getFormattedExpiresAt(),licenseDaysRemaining:this.license?.getDaysRemaining(),hasSyncConfig:null!==this.syncConfig};return this.syncConfig&&(e.syncConfig={dbEndpoint:this.syncConfig.getDbEndpoint(),dbName:this.syncConfig.getDbName(),email:this.syncConfig.getEmail(),userDir:this.syncConfig.getUserDir(),status:this.syncConfig.getStatus(),isActive:this.syncConfig.isActive()}),e}toJSON(){return{email:this.email.toJSON(),token:this.token?.toJSON()||null,serverConfig:this.serverConfig.toJSON(),license:this.license?.toJSON()||null,syncConfig:this.syncConfig?.toJSON()||null}}}}}),init_user_factory=__esm({"internal/domain/identity/factory/user-factory.ts"(){init_user(),init_email(),init_token(),init_server_config(),init_license(),init_sync_config(),init_device(),init_log(),log71=getDomainLogger("user-factory",{component:"domain"}),UserFactory=class{httpClient;storageProvider;constructor(e){this.httpClient=e.httpClient,this.storageProvider=e.storageProvider}createAnonymous(e){const t=e||ServerConfig.createDefault(),r=Email.create("anonymous@localhost.local");return new User(r,null,t)}async load(){try{const e=await this.storageProvider.loadUserData();if(!e)return log71.debug("No user data found in storage"),null;const t=e.serverConfig||ServerConfig.createDefault(),r=e.email?Email.create(e.email):Email.create("anonymous@localhost.local"),i=new User(r,e.token,t);if(e.license&&i.setLicense(e.license),e.syncConfig){const t=SyncConfig.fromJSON(e.syncConfig);i.setSyncConfig(t)}return log71.debug("User loaded from storage",{email:r.getValue(),hasToken:!!e.token,hasLicense:!!e.license,hasSyncConfig:!!e.syncConfig}),i}catch(e){return log71.error("Failed to load user from storage",e),null}}async save(e){try{const t=await this.storageProvider.loadUserData(),r=e.getToken(),i=e.getLicense(),s=e.getSyncConfig(),n=e.getServerConfig(),a=e.getEmail().getValue(),o={...t||{},...r?{token:r}:{},...i?{license:i}:{},...s?{syncConfig:s}:{},...n?{serverConfig:n}:{},email:a};!i&&t?.license&&(o.license=t.license,log71.debug("Preserved existing license data during save")),!s&&t?.syncConfig&&(o.syncConfig=t.syncConfig,log71.debug("Preserved existing syncConfig data during save")),await this.storageProvider.saveUserData(o),log71.debug("User saved to storage (merged)",{email:a,hasToken:!!o.token,hasLicense:!!o.license,hasSyncConfig:!!o.syncConfig,preservedLicense:!i&&!!t?.license,preservedSyncConfig:!s&&!!t?.syncConfig})}catch(e){throw log71.error("Failed to save user to storage",e),e}}async loadServerConfig(){try{const e=await this.storageProvider.loadUserData();return e?.serverConfig||null}catch(e){return log71.debug("No server config found in storage"),null}}async login(e,t,r){const i=Email.create(e),s=r||ServerConfig.createDefault();log71.info("Attempting login",{email:e});try{const r=`${s.getApiUrl()}/api/login`;log71.info(`Sending login request to: ${r}`),log71.debug(`Login credentials: email=${e}, password=***`);const n=await this.httpClient.postForm(r,{email:e,password:t});if(log71.info(`Login response status: ${n.status}`),log71.debug("Login response data:",n.data),201!==n.status){const e=await n.text();throw log71.error(`Login failed with status ${n.status}: ${e}`),new Error("Invalid credentials")}log71.debug("Response structure:",JSON.stringify(n.data,null,2));const a=n.data.data[0];if(!a)throw log71.error("No token in response data:",n.data),new Error("No token received from server");log71.info(`Token received: ${a.substring(0,20)}...`);const o=Token2.create(a),l=new User(i,o,s);return await this.save(l),log71.info("Login successful",{email:e}),l}catch(e){throw log71.error("Login failed",e),new Error(`Login failed: ${e.message}`)}}async register(e,t,r){const i=Email.create(e),s=r||ServerConfig.createDefault();log71.info("Attempting registration",{email:e});try{const r=await this.httpClient.postForm(`${s.getApiUrl()}/api/user`,{email:e,password:t});if(201!==r.status)throw new Error("Registration failed");const n=r.data.data[0];if(!n)throw new Error("No token received from server");const a=Token2.create(n),o=new User(i,a,s);return await this.save(o),log71.info("Registration successful",{email:e}),o}catch(e){throw log71.error("Registration failed",e),new Error(`Registration failed: ${e.message}`)}}async logout(){try{await this.storageProvider.clearUserData(),log71.info("Logout successful")}catch(e){throw log71.error("Logout failed",e),new Error(`Logout failed: ${e.message}`)}}async updateServerConfig(e,t){try{let r=e.getServerConfig();t.apiUrl&&(r=r.withApiUrl(t.apiUrl)),void 0!==t.websiteUrl&&(r=r.withWebsiteUrl(t.websiteUrl)),e.updateServerConfig(r),await this.save(e),log71.info("Server config updated")}catch(e){throw log71.error("Failed to update server config",e),new Error(`Failed to update server config: ${e.message}`)}}async requestTrialLicense(e,t){const r=t||ServerConfig.createDefault();Email.create(e),log71.info("Requesting trial license",{email:e});try{const t=await this.httpClient.postMultipart(`${r.getApiUrl()}/api/license/trial`,{email:e});if(200!==t.status&&201!==t.status)throw new Error("Trial license request failed");const i=t.data;if(i&&i.data&&i.data.length>0){const e=i.data[0];return log71.info("Trial license granted",{email:e.email,licenseKey:e.license_key}),e}throw new Error("Invalid trial response format")}catch(e){throw log71.error("Failed to request trial license",e),new Error(`Trial license request failed: ${e.message}`)}}async loginWithLicense(e,t){if(!License.isValidFormat(e))throw new Error(`Invalid license key format: ${e}`);const r=License.create(e,"free",Date.now()+864e5,{},Date.now()),i=r.getEmail(),s=r.getPassword();log71.info("Logging in with license key",{licenseKey:e,email:i});const n=await this.login(i,s,t);return n._pendingLicenseKey=e,n}async activateLicense(e,t,r){if(!License.isValidFormat(t))throw new Error(`Invalid license key format: ${t}`);const i=r||await Device.createFromEnvironment();log71.info("Activating license",{licenseKey:t,deviceId:i.getId()});try{const r=e.getToken();if(!r)throw new Error("User must be logged in to activate license");const s=await this.httpClient.postMultipart(`${e.getServerConfig().getApiUrl()}/api/license/activate`,{license_key:t,device_id:i.getId(),device_name:i.getName(),device_type:i.getType()},{Authorization:`Bearer ${r.getValue()}`});if(200!==s.status&&201!==s.status)throw new Error("License activation failed");const n=s.data.data?.[0]||s.data;if(!n.success)throw new Error("License activation unsuccessful");const a={maxDevices:n.features.max_devices,maxIps:n.features.max_ips,syncEnabled:n.features.sync_enabled,syncQuota:n.features.sync_quota,publishEnabled:n.features.publish_enabled,maxSites:n.features.max_sites,maxStorage:n.features.max_storage,customDomain:n.features.custom_domain,customSubDomain:n.features.custom_sub_domain,validityDays:n.features.validity_days},o=License.create(n.license_key,n.plan,n.expires_at,a,Date.now(),n.activated,n.first_time);if(e.setLicense(o),n.sync&&n.features.sync_enabled){const t=SyncConfig.create({dbEndpoint:n.sync.db_endpoint,dbName:n.sync.db_name,email:n.sync.email,dbPassword:n.sync.db_password,userDir:n.user.user_dir,status:n.sync.status});e.setSyncConfig(t),log71.info("Sync configuration saved",{dbName:t.getDbName(),email:t.getEmail(),userDir:t.getUserDir(),status:t.getStatus(),isActive:t.isActive()})}return await this.save(e),log71.info("License activated successfully",{licenseKey:n.license_key,plan:o.getPlan(),expires:o.getFormattedExpiresAt(),activated:n.activated,firstTime:n.first_time,syncEnabled:n.features.sync_enabled,hasSyncConfig:null!==e.getSyncConfig()}),e}catch(e){throw log71.error("Failed to activate license",e),new Error(`License activation failed: ${e.message}`)}}async requestAndActivateTrial(e,t){log71.info("Starting trial flow",{email:e});try{const r=await this.requestTrialLicense(e,t),i=await this.loginWithLicense(r.license_key,t);return await this.activateLicense(i,r.license_key),log71.info("Trial flow completed successfully",{email:e,licenseKey:r.license_key}),i}catch(e){throw log71.error("Trial flow failed",e),new Error(`Trial flow failed: ${e.message}`)}}async refreshTokenIfNeeded(e){const t=e.getToken(),r=e.getLicense();if(!t)return log71.debug("No token to refresh"),e;if(t.isValid()&&!t.isExpired())return log71.debug("Token is still valid, no refresh needed"),e;if(log71.info("Token expired or expiring soon, attempting auto-refresh"),r)try{const t=r.getKey(),i=e.getServerConfig();log71.info("Refreshing token using license",{licenseKey:t});const s=await this.loginWithLicense(t,i);return s.setLicense(r),await this.save(s),log71.info("Token refreshed successfully using license"),s}catch(e){throw log71.error("Failed to refresh token with license",e),new Error(`Failed to refresh token: ${e.message}`)}throw log71.warn("Token expired but no license available for auto-refresh"),new Error("Token expired and cannot be auto-refreshed (no license available)")}async requestWithAutoRefresh(e,t){const r=e.getToken();if(!r)throw new Error("User is not authenticated");try{return await t(r.getValue())}catch(r){const i=r?.message||r?.toString?.()||String(r);if(i.includes("401")||i.includes("Unauthorized")||r?.status&&401===r.status){log71.info("Received 401 error, attempting token refresh");try{const r=(await this.refreshTokenIfNeeded(e)).getToken();if(!r)throw new Error("Failed to refresh token - no token returned");return log71.info("Token refreshed, retrying request"),await t(r.getValue())}catch(e){throw log71.error("Failed to refresh token and retry request",e),new Error(`Request failed with 401, and token refresh failed: ${e.message}`)}}throw r}}async getLicenseUsage(e){const t=e.getLicense();if(!t)throw new Error("No license found for user");const r=t.getKey(),i=e.getServerConfig();return log71.info("Getting license usage",{licenseKey:r}),this.requestWithAutoRefresh(e,async e=>{const t=Date.now(),s=`${i.getApiUrl()}/api/license/usage?key=${r}&_t=${t}`,n=await this.httpClient.get(s,{Authorization:`Bearer ${e}`,"Cache-Control":"no-cache",Pragma:"no-cache"});if(200!==n.status){const e=await n.text();throw log71.error("License usage fetch failed",{status:n.status,text:e}),new Error(`License usage fetch failed: ${n.status}`)}const a=n.data;if(a&&a.data&&a.data.length>0)return a.data[0];throw new Error("Invalid usage response format")})}async getLicenseInfo(e,t){let r=t;if(!r){const t=e.getLicense();if(!t)throw new Error("No license found for user and no license key provided");r=t.getKey()}const i=e.getServerConfig();return log71.info("Getting license info",{licenseKey:r}),this.requestWithAutoRefresh(e,async e=>{const t=Date.now(),s=`${i.getApiUrl()}/api/license/info?key=${r}&_t=${t}`,n=await this.httpClient.get(s,{Authorization:`Bearer ${e}`,"Cache-Control":"no-cache",Pragma:"no-cache"});if(200!==n.status){const e=await n.text();throw log71.error("License info fetch failed",{status:n.status,text:e}),new Error(`License info fetch failed: ${n.status}`)}const a=n.data;if(a&&a.data&&a.data.length>0)return a.data[0];throw new Error("Invalid license info response format")})}async resetUsage(e){const t=e.getLicense();if(!t)throw new Error("No license found for user");const r=t.getKey(),i=e.getServerConfig();return log71.info("Resetting license usage",{licenseKey:r}),this.requestWithAutoRefresh(e,async e=>{const t=`${i.getApiUrl()}/api/license/usage/reset?key=${r}`,s=await this.httpClient.post(t,{},{Authorization:`Bearer ${e}`});if(200!==s.status&&201!==s.status){const e=await s.text();throw log71.error("License usage reset failed",{status:s.status,text:e}),new Error(`Reset failed: ${s.status}`)}return{success:!0}})}async getDomains(e){const t=e.getLicense();if(!t)throw new Error("No license found for user");const r=t.getKey(),i=e.getServerConfig();return log71.info("Getting domains",{licenseKey:r}),this.requestWithAutoRefresh(e,async e=>{const t=`${i.getApiUrl()}/api/license/domains?key=${r}`,s=await this.httpClient.get(t,{Authorization:`Bearer ${e}`});if(200!==s.status){const e=await s.text();return log71.error("Get domains failed",{status:s.status,text:e}),null}const n=s.data;return n&&n.data&&n.data.length>0?n.data[0]:null})}async checkSubdomainAvailability(e,t){const r=e.getLicense();if(!r)throw new Error("No license found for user");const i=r.getKey(),s=e.getServerConfig();return log71.info("Checking subdomain availability",{licenseKey:i,subdomain:t}),this.requestWithAutoRefresh(e,async e=>{const r=`${s.getApiUrl()}/api/license/subdomain/check`,n=await this.httpClient.postMultipart(r,{license_key:i,subdomain:t},{Authorization:`Bearer ${e}`});if(200!==n.status){const e=await n.text();return log71.error("Check subdomain failed",{status:n.status,text:e}),null}const a=n.data;return a&&a.data&&a.data.length>0?a.data[0]:null})}async updateSubdomain(e,t){const r=e.getLicense();if(!r)throw new Error("No license found for user");const i=r.getKey(),s=e.getServerConfig();return log71.info("Updating subdomain",{licenseKey:i,newSubdomain:t}),this.requestWithAutoRefresh(e,async e=>{const r=`${s.getApiUrl()}/api/license/subdomain/update`,n=await this.httpClient.postMultipart(r,{license_key:i,new_subdomain:t},{Authorization:`Bearer ${e}`});if(200!==n.status){const e=await n.text();return log71.error("Update subdomain failed",{status:n.status,text:e}),null}const a=n.data;return a&&a.data&&a.data.length>0?a.data[0]:null})}async checkCustomDomain(e,t){const r=e.getLicense();if(!r)throw new Error("No license found for user");const i=r.getKey(),s=e.getServerConfig();return log71.info("Checking custom domain",{licenseKey:i,domain:t}),this.requestWithAutoRefresh(e,async e=>{const r=`${s.getApiUrl()}/api/license/domain/check`,n=await this.httpClient.postMultipart(r,{license_key:i,domain:t},{Authorization:`Bearer ${e}`});if(200!==n.status){const e=await n.text();return log71.error("Check custom domain failed",{status:n.status,text:e}),null}const a=n.data;return a&&a.data&&a.data.length>0?a.data[0]:null})}async addCustomDomain(e,t){const r=e.getLicense();if(!r)throw new Error("No license found for user");const i=r.getKey(),s=e.getServerConfig();return log71.info("Adding custom domain",{licenseKey:i,domain:t}),this.requestWithAutoRefresh(e,async e=>{const r=`${s.getApiUrl()}/api/license/domain/add`,n=await this.httpClient.postMultipart(r,{license_key:i,domain:t},{Authorization:`Bearer ${e}`});if(200!==n.status&&201!==n.status){const e=await n.text();return log71.error("Add custom domain failed",{status:n.status,text:e}),null}const a=n.data;return a&&a.data&&a.data.length>0?a.data[0]:null})}async checkCustomDomainHttpsStatus(e,t){const r=e.getLicense();if(!r)throw new Error("No license found for user");const i=r.getKey(),s=e.getServerConfig();return log71.info("Checking HTTPS status",{licenseKey:i,domain:t}),this.requestWithAutoRefresh(e,async e=>{const r=`${s.getApiUrl()}/api/license/domain/https-status`,n=await this.httpClient.postMultipart(r,{license_key:i,domain:t},{Authorization:`Bearer ${e}`});if(200!==n.status){const e=await n.text();return log71.error("Check HTTPS status failed",{status:n.status,text:e}),null}const a=n.data;return a&&a.data&&a.data.length>0?a.data[0]:null})}}}}),init_type11=__esm({"internal/domain/identity/type.ts"(){}}),identity_exports={};__export(identity_exports,{Device:()=>Device,Email:()=>Email,License:()=>License,ServerConfig:()=>ServerConfig,SyncConfig:()=>SyncConfig,Token:()=>Token2,User:()=>User,UserFactory:()=>UserFactory});var log72,WorkspaceFactory,init_identity2=__esm({"internal/domain/identity/index.ts"(){init_email(),init_token(),init_server_config(),init_license(),init_sync_config(),init_device(),init_user(),init_user_factory(),init_type11()}});function generateProjectId(e){return`${e.toLowerCase().replace(/\s+/g,"-").replace(/[^a-z0-9-]/g,"")}-${Date.now().toString(36)}`}var log73,WorkspaceAppService,log74,PublisherAggregator,PublishManifest,WorkspacePublishConfig,log75,FtpPublisher,init_workspace_factory=__esm({"internal/domain/workspace/factory/workspace-factory.ts"(){init_workspace(),init_project(),init_authentication(),init_workspace_metadata(),init_project_metadata(),init_folder_structure(),init_log(),log72=getDomainLogger("workspace-factory",{component:"domain"}),WorkspaceFactory=class{workspaceRepo;projectRepo;snapshotRepo;fileSystemRepo;constructor(e){if(this.workspaceRepo=e.workspaceRepo,this.projectRepo=e.projectRepo,this.snapshotRepo=e.snapshotRepo,this.fileSystemRepo=e.fileSystemRepo,!this.fileSystemRepo)throw new Error("FileSystemRepository is required")}async load(e){const t=this.fileSystemRepo.resolvePathSync(e);log72.info("Loading workspace",{path:t});const r=await this.workspaceRepo.loadWorkspaceMetadata(t),i=WorkspaceMetadata.create(r),s=await this.workspaceRepo.loadProjectRegistry(t),n=new Map;for(const e of s.projects)try{const t=await this.projectRepo.loadProjectMetadata(e.absolutePath),r=ProjectMetadata.create(t),i=new Project(e.absolutePath,r,this.fileSystemRepo);n.set(e.id,i),log72.debug("Project loaded",{projectId:e.id,name:e.name})}catch(t){log72.warn("Failed to load project, skipping",{projectId:e.id,path:e.absolutePath,error:t.message})}const a=await this.checkAuthFile(t),o=new Authentication(t,a),l=new Workspace(t,i,n,o,this.fileSystemRepo);return log72.info("Workspace loaded",{workspaceId:l.getId(),name:l.getName(),projectCount:l.getProjectCount()}),l}async checkAuthFile(e){const t=this.fileSystemRepo.join(e,".mdfriday","auth-token.json");try{return await this.fileSystemRepo.access(t),!0}catch{return!1}}async create(e,t={}){const r=this.fileSystemRepo.resolvePathSync(e);if(log72.info("Creating workspace",{path:r}),await this.workspaceRepo.isWorkspace(r))throw new Error(`Workspace already exists at ${r}`);const i=t.modulesDir||"modules",s=t.projectsDir||"projects";await this.workspaceRepo.initWorkspaceStructure(r,i,s);const n=Date.now(),a=WorkspaceMetadata.create({version:"1.0",id:`workspace-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,name:t.name||this.fileSystemRepo.basename(r),createdAt:n,updatedAt:n,paths:{modules:i,projects:s},defaults:{modulesDir:i,language:"en"}});await this.workspaceRepo.saveWorkspaceMetadata(r,a.toJSON()),await this.workspaceRepo.saveProjectRegistry(r,{version:"1.0",projects:[]});const o=this.fileSystemRepo.join(r,".mdfriday"),l=this.fileSystemRepo.join(o,"config.json");await this.fileSystemRepo.writeFile(l,"{}","utf-8");const c=this.fileSystemRepo.join(o,"user-data.json");await this.fileSystemRepo.writeFile(c,"{}","utf-8"),log72.debug("Initialized configuration files",{configPath:l,userDataPath:c});const h=new Authentication(r,!1),u=new Workspace(r,a,new Map,h,this.fileSystemRepo);return log72.info("Workspace created",{workspaceId:u.getId(),name:u.getName()}),u}async save(e){const t=e.getPath();log72.info("Saving workspace",{workspaceId:e.getId(),path:t}),await this.workspaceRepo.saveWorkspaceMetadata(t,e.getMetadata().toJSON());const r=e.getProjectRegistry();await this.workspaceRepo.saveProjectRegistry(t,r);for(const t of e.getProjects())await this.projectRepo.saveProjectMetadata(t.getPath(),t.getMetadata().toJSON());log72.info("Workspace saved",{workspaceId:e.getId(),projectCount:e.getProjectCount()})}async findWorkspaceRoot(e){let t=this.fileSystemRepo.resolvePathSync(e);const r=this.fileSystemRepo.parsePath(t).root;for(;t!==r;){if(await this.workspaceRepo.isWorkspace(t))return t;t=this.fileSystemRepo.dirname(t)}return null}async isWorkspace(e){const t=this.fileSystemRepo.resolvePathSync(e);return this.workspaceRepo.isWorkspace(t)}async loadOrFind(e){const t=e||process.cwd(),r=await this.findWorkspaceRoot(t);if(!r)throw new Error('No workspace found. Run "mdf workspace init" to create one.');return this.load(r)}async createProject(e,t,r={}){const i=generateProjectId(t),s=this.fileSystemRepo.join(e.getProjectsDir(),t);if(log72.info("Creating project",{projectId:i,name:t,path:s}),e.findProject(t))throw new Error(`Project ${t} already exists`);const n=r.contentDir||"content",a=r.staticDir||"static",o=r.publishDir||"public";await this.projectRepo.initProjectStructure(s,n,a,o);const l=Date.now(),c=ProjectMetadata.create({id:i,name:t,type:r.type||"site",workspaceId:e.getId(),createdAt:l,updatedAt:l}),h=r.theme||"https://gohugo.net/quartz-theme.zip?version=1.2",u={baseURL:r.baseURL||"/",title:t,contentDir:n,publishDir:o,defaultContentLanguage:r.language||"en",module:{imports:[{path:h}]}};await this.projectRepo.saveProjectMetadata(s,c.toJSON()),await this.projectRepo.saveProjectConfig(s,u);const g=this.fileSystemRepo.join(s,n,"index.md");await this.projectRepo.createSampleContent(g,this.createSampleContent());const d=new Project(s,c,this.fileSystemRepo);return e.addProject(d),await this.save(e),log72.info("Project created",{projectId:i,name:t}),d}async deleteProject(e,t,r={}){const i=e.findProject(t);if(!i)throw new Error(`Project not found: ${t}`);log72.info("Deleting project",{projectId:i.getId(),name:i.getName(),deleteFiles:r.deleteFiles}),e.removeProject(i.getId()),await this.save(e),r.deleteFiles&&(await this.projectRepo.deleteProjectFiles(i.getPath()),log72.info("Project files deleted",{projectId:i.getId()})),log72.info("Project deleted",{projectId:i.getId(),name:i.getName()})}async createProjectFromFolder(e,t,r,i={}){if(!this.fileSystemRepo)throw new Error("FileSystemRepository is required to create project from folder");const s=generateProjectId(t),n=this.fileSystemRepo.join(e.getProjectsDir(),t);if(log72.info("Creating project from folder",{projectId:s,name:t,sourcePath:r,targetPath:n}),e.findProject(t))throw new Error(`Project ${t} already exists`);const a=await this.fileSystemRepo.scanFolderStructure(r),o=FolderStructure.fromScanResult(a);let l;log72.debug("Scanned folder structure",{isStructured:o.getIsStructured(),contentFolders:o.getContentFolderCount(),hasStatic:o.hasStaticFolder()}),o.getIsStructured()&&0!==o.getContentFolderCount()?l=o:(log72.info("No standard structure found, treating source folder as content directory"),l=FolderStructure.createSingleContent(r,r,i.language||"en")),await this.projectRepo.initProjectStructure(n,"content","static","public");const c=[],h=[];for(const e of l.getContentFolders()){const t=0===e.weight?this.fileSystemRepo.join(n,"content"):this.fileSystemRepo.join(n,`content.${e.languageCode}`);c.push({source:e.path,target:t}),h.push({sourcePath:e.path,languageCode:e.languageCode,weight:e.weight})}let u=null;if(l.hasStaticFolder()){const e=l.getStaticFolder();c.push({source:e.path,target:this.fileSystemRepo.join(n,"static")}),u={sourcePath:e.path}}const g=(await this.fileSystemRepo.createSymlinks(c)).filter(e=>!e.success);if(g.length>0)throw log72.error("Some symlinks failed to create",{failed:g}),new Error(`Failed to create symlinks: ${g.map(e=>e.error).join(", ")}`);const d=Date.now(),p=ProjectMetadata.create({id:s,name:t,type:i.type||"site",workspaceId:e.getId(),createdAt:d,updatedAt:d,contentLinks:h,staticLink:u}),m=i.theme||"https://gohugo.net/quartz-theme.zip?version=1.2",f={baseURL:"/",title:t,contentDir:"content",publishDir:"public",defaultContentLanguage:l.getDefaultContentFolder()?.languageCode||i.language||"en",module:{imports:[{path:m}]}};if(l.hasContentFolders()){const e={};for(const t of l.getContentFolders()){const r=0===t.weight?"content":`content.${t.languageCode}`;e[t.languageCode]={contentDir:r,weight:t.weight+1}}f.languages=e}await this.projectRepo.saveProjectMetadata(n,p.toJSON()),await this.projectRepo.saveProjectConfig(n,f);const y=new Project(n,p,this.fileSystemRepo);return e.addProject(y),await this.save(e),log72.info("Project created from folder",{projectId:s,name:t,linkedContentFolders:h.length,hasStaticLink:null!==u}),y}async createProjectFromFile(e,t,r,i={}){if(!this.fileSystemRepo)throw new Error("FileSystemRepository is required to create project from file");const s=generateProjectId(t),n=this.fileSystemRepo.join(e.getProjectsDir(),t);if(log72.info("Creating project from file",{projectId:s,name:t,sourceFile:r,targetPath:n}),e.findProject(t))throw new Error(`Project ${t} already exists`);if(!await this.fileSystemRepo.exists(r))throw new Error(`Source file not found: ${r}`);if(!(await this.fileSystemRepo.stat(r)).isFile())throw new Error(`Source path is not a file: ${r}`);await this.projectRepo.initProjectStructure(n,"content","static","public");const a=this.fileSystemRepo.join(n,"content"),o=this.fileSystemRepo.join(a,"index.md");let l=!1,c=null;try{await this.fileSystemRepo.exists(a)&&await this.fileSystemRepo.remove(a,!0),await this.fileSystemRepo.createDirectory(a,!0);const e=await this.fileSystemRepo.createSymlink(r,o);if(!e.success)throw new Error(e.error||"Failed to create symlink");l=!0,c={source:r,target:o},log72.info("Created symlink for file",{source:r,target:o})}catch(e){log72.warn("Symlink creation failed, falling back to file copy",{error:e});try{await this.fileSystemRepo.copyFile(r,o),l=!1,c={source:r,target:o},log72.info("Copied file as fallback",{source:r,target:o,isSymlink:!1})}catch(e){throw log72.error("Failed to copy file",e),new Error(`Failed to create file link or copy: ${e.message}`)}}const h=Date.now(),u=ProjectMetadata.create({id:s,name:t,type:i.type||"site",workspaceId:e.getId(),createdAt:h,updatedAt:h,fileLink:c?{sourcePath:c.source,targetPath:c.target,isSymlink:l}:null}),g=i.theme||"https://gohugo.net/note.zip?version=1.2",d={baseURL:"/",title:t,contentDir:"content",publishDir:"public",defaultContentLanguage:i.language||"en",module:{imports:[{path:g}]}};await this.projectRepo.saveProjectMetadata(n,u.toJSON()),await this.projectRepo.saveProjectConfig(n,d);const p=new Project(n,u,this.fileSystemRepo);return e.addProject(p),await this.save(e),log72.info("Project created from file",{projectId:s,name:t,sourceFile:r,useSymlink:l}),p}async loadProject(e){const t=this.fileSystemRepo.resolvePathSync(e);if(!await this.projectRepo.isProject(t))throw new Error(`No project found at ${t}`);const r=await this.projectRepo.loadProjectMetadata(t),{ProjectMetadata:i}=await Promise.resolve().then(()=>(init_project_metadata(),project_metadata_exports)),s=i.create(r);return new Project(t,s,this.fileSystemRepo)}async saveProject(e){const t=e.getPath();await this.projectRepo.saveProjectMetadata(t,e.getMetadata().toJSON()),e.getConfig()&&await e.saveConfig(),log72.debug(`Saved project: ${e.getName()}`)}async findProjectRoot(e){let t=this.fileSystemRepo.resolvePathSync(e);const r=this.fileSystemRepo.parsePath(t).root;for(;t!==r;){if(await this.projectRepo.isProject(t))return t;t=this.fileSystemRepo.dirname(t)}return null}async createSnapshot(e,t){const r=e.getPath(),i=await e.getPublishDir(),s=`${(new Date).toISOString().replace(/[:.]/g,"-").split(".")[0]}Z`;log72.info("Creating snapshot",{projectId:e.getId(),snapshotId:s});const n=await this.snapshotRepo.createSnapshot(r,s,i);if(t&&t!==n.id){if(!this.fileSystemRepo)throw new Error("FileSystemRepository is required to update snapshot metadata");n.name=t;const r=this.fileSystemRepo.join(e.getPath(),".mdfriday","snapshots",`${n.id}.json`);await this.fileSystemRepo.writeFile(r,JSON.stringify(n,null,2))}return log72.info("Snapshot created",{snapshotId:s,size:n.size,fileCount:n.fileCount}),n}async listSnapshots(e){return(await this.snapshotRepo.listSnapshots(e.getPath())).sort((e,t)=>t.timestamp-e.timestamp)}async restoreSnapshot(e,t,r){const i=r||await e.getPublishDir();await this.snapshotRepo.restoreSnapshot(e.getPath(),t,i)}async deleteSnapshot(e,t){await this.snapshotRepo.deleteSnapshot(e.getPath(),t)}async getSnapshot(e,t){return await this.snapshotRepo.getSnapshot(e.getPath(),t)}createIdentityStorage(e){const t=e.getPath(),r=e.getAuthentication(),i=this.fileSystemRepo;if(!i)throw new Error("FileSystemRepository is required for identity storage");return{async saveUserData(e){const s=i.join(t,".mdfriday","user-data.json");await i.createDirectory(i.dirname(s),!0);const n={};e.serverConfig&&(n.serverConfig=e.serverConfig.toJSON()),e.token&&(n.token=e.token.toJSON(),r.markAuthExists()),e.license&&(n.license=e.license.toJSON()),e.syncConfig&&(n.syncConfig=e.syncConfig.toJSON()),e.email&&(n.email=e.email),await i.writeFile(s,JSON.stringify(n,null,2))},async loadUserData(){const e=i.join(t,".mdfriday","user-data.json");try{const t=await i.readFile(e,"utf-8"),r=JSON.parse(t),{Token:s,ServerConfig:n,License:a,SyncConfig:o}=await Promise.resolve().then(()=>(init_identity2(),identity_exports)),l={};return r.serverConfig&&(l.serverConfig=n.create(r.serverConfig.apiUrl,r.serverConfig.websiteUrl)),r.token&&(l.token=s.create(r.token.token||r.token.value,r.token.expiresAt)),r.license&&(l.license=a.create(r.license.key,r.license.plan,r.license.expiresAt,r.license.features,r.license.activatedAt,r.license.activated,r.license.firstTime)),r.syncConfig&&(l.syncConfig=o.fromJSON(r.syncConfig)),r.email&&(l.email=r.email),l}catch{return null}},async clearUserData(){const e=i.join(t,".mdfriday","user-data.json");try{await i.unlink(e)}catch{}r.markAuthDeleted()}}}async setupBaseURLStructure(e){if(!this.fileSystemRepo)throw new Error("FileSystemRepository is required for baseURL structure");const t=await e.getBaseURL(),r=e.parseBaseURLPath(t),i=e.getPath(),s=this.fileSystemRepo.join(i,"public");if(r.isRoot)return log72.debug("baseURL is root, no structure needed"),{serverRoot:s,baseURL:"/",symlinkCreated:!1};log72.info("Creating baseURL structure in public/",{baseURL:t,pathParts:r.pathParts});let n=s;for(const e of r.parentParts)n=this.fileSystemRepo.join(n,e),await this.fileSystemRepo.exists(n)||(await this.fileSystemRepo.createDirectory(n,!1),log72.debug(`Created parent directory: ${e}`));const a=this.fileSystemRepo.join(n,r.finalDirName);await this.fileSystemRepo.exists(a)&&(await this.fileSystemRepo.remove(a,!0),log72.debug(`Removed existing symlink: ${a}`));const o=await this.fileSystemRepo.createSymlink(r.relativeToPublic,a);if(!o.success)throw log72.error("Failed to create baseURL symlink",{target:r.relativeToPublic,link:a,error:o.error}),new Error(`Failed to create baseURL structure: ${o.error}`);return log72.info("baseURL structure created successfully",{symlinkPath:r.pathParts.join("/"),target:r.relativeToPublic}),e.updateBaseURLStructure({baseURL:t,createdAt:Date.now(),pathParts:r.pathParts}),await this.projectRepo.saveProjectMetadata(e.getPath(),e.getMetadata().toJSON()),{serverRoot:s,baseURL:t,symlinkCreated:!0}}async cleanBaseURLStructure(e){if(!this.fileSystemRepo)return;const t=e.getBaseURLStructure();if(!t||0===t.pathParts.length)return;const r=e.getPath(),i=this.fileSystemRepo.join(r,"public");log72.info("Cleaning baseURL structure in public/",{pathParts:t.pathParts});for(let e=t.pathParts.length;e>0;e--){const r=this.fileSystemRepo.join(i,...t.pathParts.slice(0,e));if(await this.fileSystemRepo.exists(r)&&(await this.fileSystemRepo.remove(r,!0),log72.debug(`Removed: ${t.pathParts.slice(0,e).join("/")}`)),e>1){const r=this.fileSystemRepo.join(i,...t.pathParts.slice(0,e-1));if(await this.fileSystemRepo.exists(r)&&(await this.fileSystemRepo.readDirectory(r)).length>0)break}}e.updateBaseURLStructure(null),await this.projectRepo.saveProjectMetadata(e.getPath(),e.getMetadata().toJSON()),log72.info("baseURL structure cleaned")}async ensureBaseURLStructure(e){const t=await e.getBaseURL(),r=e.getBaseURLStructure();return r&&r.baseURL===t?{serverRoot:this.fileSystemRepo.join(e.getPath(),"public"),baseURL:t,recreated:!1}:(r&&(log72.info("baseURL changed, recreating structure",{old:r.baseURL,new:t}),await this.cleanBaseURLStructure(e)),{...await this.setupBaseURLStructure(e),recreated:!0})}async scanFolderStructure(e){if(!this.fileSystemRepo)throw new Error("FileSystemRepository is required to scan folder structure");log72.info("Scanning folder structure",{path:e});const t=await this.fileSystemRepo.scanFolderStructure(e),r=FolderStructure.fromScanResult(t);return log72.debug("Folder structure scanned",{isStructured:r.getIsStructured(),contentFolders:r.getContentFolderCount(),hasStatic:r.hasStaticFolder(),languages:r.getSupportedLanguages()}),r}createSampleContent(){return`---\ntitle: Welcome to MDFriday\ndate: ${(new Date).toISOString()}\n---\n\n# Welcome to MDFriday\n\nThis is a sample page. Edit this file to get started!\n\n## Features\n\n- **Markdown Support**: Write content in Markdown\n- **Themes**: Beautiful themes out of the box\n- **Fast**: Static site generation for speed\n- **Flexible**: Customize everything\n\n## Getting Started\n\n1. Edit files in the \`content/\` directory\n2. Run \`mdf serve\` to preview\n3. Run \`mdf build\` to generate your site\n`}}}}),init_workspace2=__esm({"internal/domain/workspace/index.ts"(){init_type10(),init_workspace_metadata(),init_project_metadata(),init_folder_structure(),init_repository(),init_workspace(),init_project(),init_authentication(),init_workspace_factory()}}),init_workspace3=__esm({"internal/application/workspace.ts"(){init_log(),log73=getDomainLogger("workspace-app",{component:"application"}),WorkspaceAppService=class{workspaceFactory;constructor(e){this.workspaceFactory=e.workspaceFactory}async loadWorkspace(e){return e?this.workspaceFactory.load(e):this.workspaceFactory.loadOrFind()}async createWorkspace(e,t){return this.workspaceFactory.create(e,t)}async saveWorkspace(e){return this.workspaceFactory.save(e)}async findWorkspaceRoot(e){return this.workspaceFactory.findWorkspaceRoot(e||process.cwd())}async createProject(e,t,r){return this.workspaceFactory.createProject(e,t,r)}async createProjectFromFolder(e,t,r,i){return this.workspaceFactory.createProjectFromFolder(e,t,r,i)}async createProjectFromFile(e,t,r,i){return this.workspaceFactory.createProjectFromFile(e,t,r,i)}async deleteProject(e,t,r){return this.workspaceFactory.deleteProject(e,t,r)}async loadWorkspaceAndProject(e,t){const r=await this.loadWorkspace(t);let i;if(e){if(i=r.findProject(e),!i){const t=r.getProjects(),s=this.workspaceFactory.fileSystemRepo;if(s){const r=s.resolvePathSync(e);for(const e of t){const t=e.getPath();if(r.startsWith(t)||t===r){i=e;break}try{const n=await s.resolvePath(r),a=await s.resolvePath(t);if(n.startsWith(a)||a===n){i=e;break}}catch(e){}}}else i=void 0;if(!i)throw new Error(`Project not found: ${e}`)}}else{const e=process.cwd(),t=r.getProjects(),s=this.workspaceFactory.fileSystemRepo;if(s)for(const r of t){const t=r.getPath();if(e.startsWith(t)){i=r;break}try{const n=await s.resolvePath(e),a=await s.resolvePath(t);if(n.startsWith(a)){i=r;break}}catch(e){}}if(i||1!==t.length||(i=t[0]),!i){if(0===t.length)throw new Error("No projects found in workspace");throw new Error(`Project not found in current directory: ${e}\nPlease specify a project name with --project <name>`)}}return log73.debug("Loaded workspace and project",{workspaceId:r.getId(),projectId:i.getId(),projectName:i.getName()}),{workspace:r,project:i}}async createSnapshot(e,t){return this.workspaceFactory.createSnapshot(e,t)}async listSnapshots(e){return this.workspaceFactory.listSnapshots(e)}async restoreSnapshot(e,t,r){return this.workspaceFactory.restoreSnapshot(e,t,r)}async deleteSnapshot(e,t){return this.workspaceFactory.deleteSnapshot(e,t)}async getSnapshot(e,t){return this.workspaceFactory.getSnapshot(e,t)}async loadProject(e){return this.workspaceFactory.loadProject(e)}async saveProject(e){return this.workspaceFactory.saveProject(e)}async findProjectRoot(e){return this.workspaceFactory.findProjectRoot(e)}async scanFolderStructure(e){return this.workspaceFactory.scanFolderStructure(e)}createIdentityStorage(e){return this.workspaceFactory.createIdentityStorage(e)}async setupProjectBaseURLStructure(e){return this.workspaceFactory.setupBaseURLStructure(e)}async cleanProjectBaseURLStructure(e){return this.workspaceFactory.cleanBaseURLStructure(e)}async ensureProjectBaseURLStructure(e){return this.workspaceFactory.ensureBaseURLStructure(e)}}}}),init_type12=__esm({"internal/domain/publish/type.ts"(){}}),init_publisher3=__esm({"internal/domain/publish/entity/publisher.ts"(){init_log(),log74=getDomainLogger("publisher-aggregator",{component:"domain"}),PublisherAggregator=class{constructor(e,t,r,i,s){this.projectId=e,this.projectPath=t,this.config=r,this.strategy=i,this.manifestRepo=s}async publish(e,t){const r=Date.now(),i=!1!==t?.incremental&&!t?.force;log74.info(`Publishing project: ${this.projectId}`,{type:this.config.type,incremental:i,force:t?.force});try{t?.onProgress?.({phase:"scanning",percentage:5,message:"Scanning files..."});const s=await this.manifestRepo.generateManifest(this.projectId,e,this.config.type,this.getRemoteConfig());log74.debug(`Scanned ${s.getFileCount()} files`);const n=i?await this.manifestRepo.loadManifest(this.projectPath,this.config.type):null;let a=[],o=[];if(n){if(a=n.getChangedFiles(s),o=n.getDeletedFiles(s),log74.info(`Incremental: ${a.length} changed, ${o.length} deleted`),0===a.length&&0===o.length)return log74.info("No changes detected"),{success:!0,filesUploaded:0,bytesTransferred:0,duration:Date.now()-r}}else a=s.getAllFiles(),log74.info(`Full publish: ${a.length} files`);const l=await this.strategy.publish(e,{...t,incremental:null!==n});return l.success&&(await this.manifestRepo.saveManifest(this.projectPath,s),log74.info("Manifest saved")),l}catch(e){throw log74.error("Publish failed",e),e}}async testConnection(){return this.strategy.testConnection?await this.strategy.testConnection():{success:!0}}getConfig(){return this.config}getType(){return this.config.type}getProjectId(){return this.projectId}getProjectPath(){return this.projectPath}getRemoteConfig(){if("ftp"===this.config.type)return{host:this.config.host,remotePath:this.config.remotePath}}}}}),init_publish_manifest=__esm({"internal/domain/publish/value-object/publish-manifest.ts"(){PublishManifest=class e{projectId;publishMethod;lastPublishTime;files;remoteConfig;constructor(e){this.projectId=e.projectId,this.publishMethod=e.publishMethod,this.lastPublishTime=e.lastPublishTime,this.remoteConfig=e.remoteConfig,e.files instanceof Map?this.files=e.files:this.files=new Map(Object.entries(e.files))}getProjectId(){return this.projectId}getPublishMethod(){return this.publishMethod}getLastPublishTime(){return this.lastPublishTime}getRemoteConfig(){return this.remoteConfig}getAllFiles(){return Array.from(this.files.keys())}getFile(e){return this.files.get(e)}hasFile(e){return this.files.has(e)}getFileCount(){return this.files.size}getChangedFiles(e){const t=[];for(const[r,i]of e.files.entries()){const e=this.files.get(r);e&&e.hash===i.hash||t.push(r)}return t}getDeletedFiles(e){const t=[];for(const r of this.files.keys())e.files.has(r)||t.push(r);return t}toJSON(){const e={};for(const[t,r]of this.files.entries())e[t]=r;return{projectId:this.projectId,publishMethod:this.publishMethod,lastPublishTime:this.lastPublishTime,remoteConfig:this.remoteConfig,files:e}}static fromJSON(t){return new e({projectId:t.projectId,publishMethod:t.publishMethod,lastPublishTime:t.lastPublishTime,remoteConfig:t.remoteConfig,files:t.files||{}})}static create(t){return new e({...t,lastPublishTime:Date.now()})}}}}),init_publish_config=__esm({"internal/domain/publish/value-object/publish-config.ts"(){WorkspacePublishConfig=class e{ftp;netlify;mdfriday;constructor(e){e.ftp&&(this.ftp=e.ftp),e.netlify&&(this.netlify=e.netlify),e.mdfriday&&(this.mdfriday=e.mdfriday)}hasFTP(){return!!this.ftp&&!!this.ftp.host&&!!this.ftp.username}hasNetlify(){return!!this.netlify&&!!this.netlify.accessToken&&!!this.netlify.siteId}hasMDFriday(){return!!this.mdfriday&&!0===this.mdfriday.enabled}getFTPConfig(){return this.hasFTP()?this.ftp:null}getNetlifyConfig(){return this.hasNetlify()?this.netlify:null}getMDFridayConfig(){return this.hasMDFriday()?this.mdfriday:null}static fromGlobalConfig(t){const r=t?.publish||{};return new e({ftp:r.ftp,netlify:r.netlify,mdfriday:r.mdfriday})}merge(t,r){const i={};switch(this.ftp&&(i.ftp=this.ftp),this.netlify&&(i.netlify=this.netlify),this.mdfriday&&(i.mdfriday=this.mdfriday),r){case"ftp":this.ftp&&(i.ftp={...this.ftp,...t});break;case"netlify":this.netlify&&(i.netlify={...this.netlify,...t});break;case"mdfriday":this.mdfriday&&(i.mdfriday={...this.mdfriday,...t})}return new e(i)}}}});import*as ftp from"basic-ftp";import path32 from"path";import{promises as fs5}from"fs";var log76,NetlifyPublisher,init_ftp_publisher=__esm({"internal/domain/publish/value-object/ftp-publisher.ts"(){init_log(),log75=getDomainLogger("ftp-publisher",{component:"domain"}),FtpPublisher=class{constructor(e,t,r,i){this.config=e,this.manifestRepo=t,this.projectId=r,this.projectPath=i}async publish(e,t){const r=Date.now();let i=0,s=0;const n=new ftp.Client;n.ftp.ipFamily=4,n.ftp.verbose=!1;try{t?.onProgress?.({phase:"scanning",percentage:0,message:"Connecting to FTP server..."});const a=await this.connectWithFallback(n);if(log75.info(`Connected to FTP: ${this.config.host} (${a.usedSecure?"FTPS":"FTP"})`),this.config.remotePath&&"/"!==this.config.remotePath)try{await n.cd(this.config.remotePath)}catch(e){await n.ensureDir(this.config.remotePath),await n.cd(this.config.remotePath)}const{changedFiles:o,deletedFiles:l}=await this.getFileLists(e,t?.incremental),c=o.length+l.length;let h=0;t?.onProgress?.({phase:"uploading",percentage:10,message:`Uploading ${o.length} file(s)...`,filesCompleted:0,filesTotal:c});const u=new Set;for(const r of o){const a=path32.join(e,r),o=this.config.remotePath&&"/"!==this.config.remotePath?`${this.config.remotePath}/${r}`.replace(/\\/g,"/"):r.replace(/\\/g,"/");try{const e=path32.dirname(o).replace(/\\/g,"/");if(e&&"."!==e&&"/"!==e&&!u.has(e))try{await n.ensureDir(e),u.add(e)}catch(t){log75.warn(`Failed to ensure directory ${e}`,t),log75.warn("Will attempt upload anyway...")}await this.uploadFileWithRetry(n,a,o,r,2),s+=(await fs5.stat(a)).size,i++,h++;const l=10+Math.floor(h/c*80);t?.onProgress?.({phase:"uploading",percentage:l,message:"Uploading files...",currentFile:r,filesCompleted:h,filesTotal:c,bytesTransferred:s}),log75.debug(`Uploaded: ${r}`)}catch(e){throw log75.error(`Failed to upload: ${r}`,e),new Error(`Failed to upload ${r}: ${e.message}`)}}if(l.length>0){t?.onProgress?.({phase:"uploading",percentage:90,message:`Deleting ${l.length} file(s)...`,filesCompleted:h,filesTotal:c});for(const e of l){const r=this.config.remotePath&&"/"!==this.config.remotePath?`${this.config.remotePath}/${e}`.replace(/\\/g,"/"):e.replace(/\\/g,"/");try{await n.remove(r),h++,t?.onProgress?.({phase:"uploading",percentage:90+Math.floor((h-o.length)/l.length*10),message:"Deleting files...",currentFile:e,filesCompleted:h,filesTotal:c}),log75.debug(`Deleted: ${e}`)}catch(t){log75.warn(`Failed to delete: ${e}`,t)}}}t?.onProgress?.({phase:"complete",percentage:100,message:"Upload complete!",filesCompleted:h,filesTotal:c});const g=Date.now()-r;return{success:!0,url:`${this.config.secure?"ftps":"ftp"}://${this.config.host}${this.config.remotePath}`,filesUploaded:i,bytesTransferred:s,duration:g}}catch(e){return log75.error("FTP publish failed",e),{success:!1,filesUploaded:i,bytesTransferred:s,duration:Date.now()-r,error:e.message}}finally{n.close()}}async testConnection(){const e=new ftp.Client;e.ftp.ipFamily=4,e.ftp.verbose=!1;try{return await this.connectWithFallback(e),e.close(),{success:!0}}catch(e){return{success:!1,error:e.message}}}getConfig(){return this.config}getType(){return"ftp"}async connectWithFallback(e){try{return await e.access({host:this.config.host,port:this.config.port,user:this.config.username,password:this.config.password,secure:!1}),{usedSecure:!1}}catch(t){log75.warn("Plain FTP failed, trying FTPS...");try{e.close();const t=new ftp.Client;return t.ftp.ipFamily=4,t.ftp.verbose=!1,await t.access({host:this.config.host,port:this.config.port,user:this.config.username,password:this.config.password,secure:!0,secureOptions:{rejectUnauthorized:!this.config.secure}}),Object.assign(e,t),{usedSecure:!0}}catch(e){throw log75.error("Both plain FTP and FTPS failed"),t}}}async uploadFileWithRetry(e,t,r,i,s=2){let n=null;for(let a=1;a<=s;a++)try{try{await e.remove(r)}catch(e){}return void await e.uploadFrom(t,r)}catch(e){if(n=e,!(a<s))throw log75.error(`All upload attempts failed for ${i}`),n;{log75.warn(`Upload attempt ${a}/${s} failed for ${i}, retrying...`),log75.warn(`Error: ${n.message}`);const e=1e3*a;await new Promise(t=>setTimeout(t,e))}}throw n||new Error("Upload failed with unknown error")}async getFileLists(e,t){const r=await this.manifestRepo.generateManifest(this.projectId,e,"ftp",{host:this.config.host,remotePath:this.config.remotePath});if(!t)return{changedFiles:r.getAllFiles(),deletedFiles:[]};const i=await this.manifestRepo.loadManifest(this.projectPath,"ftp");return i?{changedFiles:i.getChangedFiles(r),deletedFiles:i.getDeletedFiles(r)}:{changedFiles:r.getAllFiles(),deletedFiles:[]}}}}});import path33 from"path";import{promises as fs6}from"fs";var log77,MDFridayPublisher,init_netlify_publisher=__esm({"internal/domain/publish/value-object/netlify-publisher.ts"(){init_log(),log76=getDomainLogger("netlify-publisher",{component:"domain"}),NetlifyPublisher=class{constructor(e,t,r,i,s){this.config=e,this.manifestRepo=t,this.httpClient=r,this.projectId=i,this.projectPath=s}async publish(e,t){const r=Date.now();let i=0,s=0;try{log76.info(`Starting Netlify digest deployment from: ${e}`),log76.info("Incremental mode: "+(t?.incremental?"enabled":"disabled")),t?.onProgress?.({phase:"scanning",percentage:5,message:"Scanning files..."});const{changedFiles:n,unchangedFiles:a}=await this.getFileLists(e,t?.incremental),o=n.length;if(log76.info(`Files to upload: ${n.length}, unchanged: ${a.length}`),t?.onProgress?.({phase:"scanning",percentage:20,message:`Scanned ${o} files`}),0===n.length)return log76.info("No files to upload, deployment skipped"),{success:!0,url:await this.getSiteUrl(),filesUploaded:0,bytesTransferred:0,duration:Date.now()-r};t?.onProgress?.({phase:"uploading",percentage:25,message:"Creating deploy..."});const l=await this.manifestRepo.generateManifest(this.projectId,e,"netlify",{siteId:this.config.siteId}),c=l.getAllFiles();log76.info(`Sending ${c.length} files to Netlify (changed: ${n.length}, unchanged: ${a.length})`);const{deployId:h,requiredFiles:u,hashToPath:g}=await this.createDeployWithDigests(l,c);if(log76.info(`Deploy created: ${h}`),log76.info(`Required files: ${u.length}/${c.length} (${c.length-u.length} cached on CDN)`),u.length>0){t?.onProgress?.({phase:"uploading",percentage:30,message:`Uploading ${u.length} file(s)...`});const r=await this.uploadRequiredFiles(e,h,u,l,(e,r)=>{i=e;const s=30+Math.floor(e/r*60);t?.onProgress?.({phase:"uploading",percentage:s,message:"Uploading files...",filesCompleted:e,filesTotal:r})});s=r.bytesTransferred,i=r.filesUploaded}else log76.info("All files are cached on Netlify CDN, no upload needed");t?.onProgress?.({phase:"deploying",percentage:90,message:"Deploying..."});try{await this.waitForDeployment(h)}catch(e){log76.warn("Failed to confirm deployment status, but upload was successful",e)}const d=await this.getSiteUrl();t?.onProgress?.({phase:"complete",percentage:100,message:"Deployment complete!"});const p=Date.now()-r;return log76.info(`Deployment successful: ${d}`),log76.info(`Uploaded ${i} files (${this.formatBytes(s)})`),{success:!0,url:d,filesUploaded:i,bytesTransferred:s,duration:p}}catch(e){log76.error("Netlify deployment failed",e);const t=Date.now()-r;let n=e.message;return n.includes("401")||n.includes("Unauthorized")?n="Invalid Netlify access token. Please check your configuration.":n.includes("404")||n.includes("Not Found")?n="Netlify site not found. Please check your site ID.":(n.includes("network")||n.includes("CORS"))&&(n="Network error. Please check your internet connection."),{success:!1,filesUploaded:i,bytesTransferred:s,duration:t,error:n}}}async testConnection(){try{return await this.getSiteUrl(),{success:!0}}catch(e){return{success:!1,error:e.message}}}getConfig(){return this.config}getType(){return"netlify"}async getFileLists(e,t){const r=await this.manifestRepo.generateManifest(this.projectId,e,"netlify",{siteId:this.config.siteId});if(!t)return{changedFiles:r.getAllFiles(),unchangedFiles:[]};const i=await this.manifestRepo.loadManifest(this.projectPath,"netlify");if(!i)return{changedFiles:r.getAllFiles(),unchangedFiles:[]};const s=i.getChangedFiles(r),n=r.getAllFiles().filter(e=>!s.includes(e));return{changedFiles:s,unchangedFiles:n}}async createDeployWithDigests(e,t){log76.info(`Creating deploy with ${t.length} file digests...`);const r={},i=new Map;for(const s of t){const t=e.getFile(s);t&&(r[s]=t.hash,i.set(t.hash,s))}log76.debug(`Built hash to path mapping for ${i.size} files`);const s=await this.httpClient.postJSON(`https://api.netlify.com/api/v1/sites/${this.config.siteId}/deploys`,{files:r},{Authorization:`Bearer ${this.config.accessToken}`});if(!s.ok){const e=await s.text();throw log76.error(`Create deploy failed: ${s.status} - ${e}`),new Error(`Create deploy failed: ${s.status} - ${e}`)}const n=s.data,a=n.id,o=n.required||[];log76.debug(`Netlify returned ${o.length} required hashes`);const l=[];for(const e of o){const t=i.get(e);t?l.push(t):log76.warn(`Hash not found in mapping: ${e}`)}return log76.info(`Resolved ${l.length} file paths from ${o.length} hashes`),{deployId:a,requiredFiles:l,hashToPath:i}}async uploadRequiredFiles(e,t,r,i,s){let n=0,a=0;for(const o of r){const l=i.getFile(o);if(!l){log76.warn(`File not found in manifest: ${o}`);continue}const c=path33.join(e,o);try{const e=await fs6.readFile(c);await this.uploadFileWithRetry(t,o,e,l.hash),n++,a+=l.size,s?.(n,r.length),log76.debug(`Uploaded ${n}/${r.length}: ${o}`)}catch(e){throw log76.error(`Failed to upload file: ${o}`,e),e}}return log76.info(`Upload complete: ${n} files, ${this.formatBytes(a)}`),{filesUploaded:n,bytesTransferred:a}}async uploadFileWithRetry(e,t,r,i,s=2){let n=null;for(let a=1;a<=s;a++)try{const s=t.split("/").map(encodeURIComponent).join("/"),n=await this.httpClient.putBinary(`https://api.netlify.com/api/v1/deploys/${e}/files/${s}`,r,{Authorization:`Bearer ${this.config.accessToken}`});if(!n.ok){const e=await n.text();throw new Error(`Upload failed (${n.status}): ${e}`)}const a=n.data,o=(a.sha||a.SHA||"").toLowerCase();if(o!==i.toLowerCase())throw new Error(`SHA1 mismatch: expected ${i}, got ${o}`);return}catch(e){if(n=e,!(a<s))throw log76.error(`All upload attempts failed for ${t}`),n;log76.warn(`Upload attempt ${a}/${s} failed for ${t}, retrying...`),await new Promise(e=>setTimeout(e,1e3*a))}throw n||new Error("Upload failed with unknown error")}async waitForDeployment(e,t=30){log76.info(`Waiting for deployment to complete: ${e}`);for(let r=0;r<t;r++)try{log76.debug(`Checking deployment status (attempt ${r+1}/${t})...`);const i=await this.httpClient.get(`https://api.netlify.com/api/v1/deploys/${e}`,{Authorization:`Bearer ${this.config.accessToken}`});if(log76.debug(`Status check response: ${i.status}`),i.ok){const e=i.data;if(log76.info(`Deployment state: ${e.state}`,{published_at:e.published_at}),"ready"===e.state)return void log76.info("Deployment is ready!");if("error"===e.state)throw new Error(`Deployment failed: ${e.error_message||"Unknown error"}`);log76.debug(`Current state: ${e.state}, waiting...`)}else log76.warn(`Unexpected status code: ${i.status}`);await new Promise(e=>setTimeout(e,2e3))}catch(e){if(log76.error(`Error checking deployment status (attempt ${r+1}):`,e),r===t-1)throw e;await new Promise(e=>setTimeout(e,2e3))}throw log76.warn("Deployment status check timed out (60 seconds)"),new Error("Deployment timed out")}async getSiteUrl(){try{log76.debug(`Fetching site URL for: ${this.config.siteId}`);const e=await this.httpClient.get(`https://api.netlify.com/api/v1/sites/${this.config.siteId}`,{Authorization:`Bearer ${this.config.accessToken}`});if(log76.debug(`Get site URL response: ${e.status}`),!e.ok){const t=await e.text();throw log76.error(`Failed to get site URL: ${e.status} - ${t}`),new Error(`Failed to get site URL: ${e.status}`)}const t=e.data,r=t.ssl_url||t.url;return log76.info(`Site URL: ${r}`,{name:t.name}),r}catch(e){throw log76.error("Failed to get site URL:",e),e}}formatBytes(e){if(0===e)return"0 Bytes";const t=Math.floor(Math.log(e)/Math.log(1024));return Math.round(e/Math.pow(1024,t)*100)/100+" "+["Bytes","KB","MB","GB"][t]}}}});import path34 from"path";import{promises as fs7}from"fs";import JSZip2 from"jszip";var log78,PublisherFactory,log79,PublishAppService,NodeWorkspaceRepository,NodeProjectRepository,init_mdfriday_publisher=__esm({"internal/domain/publish/value-object/mdfriday-publisher.ts"(){init_log(),log77=getDomainLogger("mdfriday-publisher",{component:"domain"}),MDFridayPublisher=class{constructor(e,t,r,i,s){this.config=e,this.manifestRepo=t,this.httpClient=r,this.projectId=i,this.projectPath=s}async publish(e,t){const r=Date.now();try{if(log77.info(`Starting MDFriday deployment from: ${e}`),log77.info(`Deployment type: ${this.config.deploymentType}`),"free"!==this.config.deploymentType&&!this.config.accessToken)throw new Error("MDFriday access token not found.\nPlease login first:\n mdf auth login");const{changedFiles:i,allFiles:s}=await this.getFileLists(e,t?.incremental),n=t?.incremental&&i.length<s.length&&i.length>0;if(n)log77.info(`Incremental deploy: ${i.length}/${s.length} files (${Math.round(i.length/s.length*100)}%)`);else if(t?.incremental&&0===i.length)return log77.info("No files changed, skipping deployment"),{success:!0,url:"",filesUploaded:0,bytesTransferred:0,duration:Date.now()-r};t?.onProgress?.({phase:"scanning",percentage:5,message:n?`Creating incremental package (${i.length} files)...`:"Creating deployment package..."});const a=n?await this.createIncrementalZip(e,i):await this.createZipFromDirectory(e),o=a.length;log77.info(`Created ${n?"incremental":"full"} ZIP package: ${this.formatBytes(o)}`),t?.onProgress?.({phase:"scanning",percentage:30,message:"Package created"}),t?.onProgress?.({phase:"uploading",percentage:30,message:"Uploading to MDFriday..."});const l=await this.uploadToMDFriday(a,this.projectId,e=>{const r=30+e/100*40;t?.onProgress?.({phase:"uploading",percentage:r,message:"Uploading...",bytesTransferred:Math.floor(o*(e/100))})});log77.info(`Upload complete, preview ID: ${l}`),t?.onProgress?.({phase:"deploying",percentage:70,message:"Deploying..."});const c=await this.deployPreview(l);log77.info(`Deploy complete: ${c}`),t?.onProgress?.({phase:"deploying",percentage:90,message:"Saving manifest..."});const h=await this.manifestRepo.generateManifest(this.projectId,e,"mdfriday",{previewId:l,deploymentType:this.config.deploymentType});await this.manifestRepo.saveManifest(this.projectPath,h,this.config.deploymentType),t?.onProgress?.({phase:"complete",percentage:100,message:"Deployment complete!"});const u=Date.now()-r;return log77.info(`Deployment successful: ${c}`),{success:!0,url:c,filesUploaded:i.length,bytesTransferred:o,duration:u}}catch(e){log77.error("MDFriday deployment failed",e);const t=Date.now()-r;let i=e.message;return i.includes("401")||i.includes("Unauthorized")?i="Invalid access token. Please login again:\n mdf auth login":i.includes("403")||i.includes("Forbidden")?i="Access forbidden. Please check your account permissions.":i.includes("network")&&(i="Network error. Please check your internet connection."),{success:!1,filesUploaded:0,bytesTransferred:0,duration:t,error:i}}}async testConnection(){try{return"free"===this.config.deploymentType||this.config.accessToken?{success:!0}:{success:!1,error:"Access token not found. Please login first: mdf auth login"}}catch(e){return{success:!1,error:e.message}}}getConfig(){return this.config}getType(){return"mdfriday"}async getFileLists(e,t){const r=await this.manifestRepo.generateManifest(this.projectId,e,"mdfriday",{deploymentType:this.config.deploymentType}),i=r.getAllFiles();if(!t)return log77.debug("Full publish mode: deploying all files"),{changedFiles:i,allFiles:i};const s=await this.manifestRepo.loadManifest(this.projectPath,"mdfriday",this.config.deploymentType);if(!s)return log77.info("No previous manifest found, performing full deploy"),{changedFiles:i,allFiles:i};const n=s.getChangedFiles(r);return log77.info(`Incremental mode: ${n.length}/${i.length} files changed`),{changedFiles:n,allFiles:i}}async createIncrementalZip(e,t){const r=new JSZip2;log77.debug(`Creating incremental ZIP with ${t.length} files`);for(const i of t){const t=path34.join(e,i);try{const e=await fs7.readFile(t);r.file(i,new Uint8Array(e))}catch(e){throw log77.error(`Failed to add file to ZIP: ${i}`,e),new Error(`Failed to add file to incremental ZIP: ${i}`)}}return await r.generateAsync({type:"uint8array"})}async createZipFromDirectory(e){const t=new JSZip2,r=async(e,t)=>{const i=await fs7.readdir(e,{withFileTypes:!0});for(const s of i){const i=path34.join(e,s.name);if(s.isDirectory()){const e=t.folder(s.name);e&&await r(i,e)}else if(s.isFile()){const e=await fs7.readFile(i);t.file(s.name,new Uint8Array(e))}}};return await r(e,t),await t.generateAsync({type:"uint8array"})}async uploadToMDFriday(e,t,r){try{log77.info(`Uploading ${this.formatBytes(e.length)} to MDFriday...`);const i=this.simulateUploadProgress(e.length,r),s=this.buildFormData(e,t,this.config.path||"",this.config.deploymentType),n="free"===this.config.deploymentType,a=n?`${this.getApiUrl()}/api/mdf/preview/friday?type=MDFPreview`:`${this.getApiUrl()}/api/mdf/preview?type=MDFPreview`,o={};!n&&this.config.accessToken&&(o.Authorization=`Bearer ${this.config.accessToken}`);const l=await this.httpClient.postMultipart(a,s,o);if(clearInterval(i),r?.(100),!l.ok){const e=await l.text();throw log77.error(`Upload failed: ${l.status} - ${e}`),new Error(`Upload failed: ${l.status} - ${e}`)}const c=l.data.data[0].id;return log77.info(`Preview created: ${c}`),c}catch(e){throw log77.error("MDFriday upload error:",e),e}}async deployPreview(e){try{log77.info(`Deploying preview: ${e}`);const t={type:"MDFPreview",id:e,host_name:"MDFriday Preview",license_key:this.config.licenseKey||""},r="free"===this.config.deploymentType,i=r?`${this.getApiUrl()}/api/mdf/preview/friday/deploy?type=MDFPreview&id=${e}`:`${this.getApiUrl()}/api/mdf/preview/deploy?type=MDFPreview&id=${e}`,s={};!r&&this.config.accessToken&&(s.Authorization=`Bearer ${this.config.accessToken}`);const n=await this.httpClient.postMultipart(i,t,s);if(!n.ok){const e=await n.text();throw log77.error(`Deploy failed: ${n.status} - ${e}`),new Error(`Deploy failed: ${n.status} - ${e}`)}return n.data.data[0]}catch(e){throw log77.error("MDFriday deploy error:",e),e}}buildFormData(e,t,r,i){return{type:i,path:r,id:"-1",name:t,size:e.length.toString(),asset:{data:e,filename:`${t}.zip`,contentType:"application/zip"}}}getApiUrl(){return this.config.apiUrl||"https://api.mdfriday.com"}simulateUploadProgress(e,t){let r=0;const i=500/Math.min(Math.max(e/1024/1024*2e3,3e3),3e4)*100;return setInterval(()=>{r=Math.min(r+i,95),t?.(r)},500)}formatBytes(e){if(0===e)return"0 Bytes";const t=Math.floor(Math.log(e)/Math.log(1024));return Math.round(e/Math.pow(1024,t)*100)/100+" "+["Bytes","KB","MB","GB"][t]}}}}),init_publisher_factory=__esm({"internal/domain/publish/factory/publisher-factory.ts"(){init_publisher3(),init_ftp_publisher(),init_netlify_publisher(),init_mdfriday_publisher(),init_log(),log78=getDomainLogger("publisher-factory",{component:"domain"}),PublisherFactory=class{constructor(e,t){this.manifestRepo=e,this.httpClient=t}create(e,t,r){let i;switch(log78.debug(`Creating publisher: ${r.type}`,{projectId:e}),r.type){case"ftp":i=this.createFtpPublisher(e,t,r);break;case"netlify":i=this.createNetlifyPublisher(e,t,r);break;case"mdfriday":i=this.createMDFridayPublisher(e,t,r);break;default:throw new Error(`Unknown publish type: ${r.type}`)}return new PublisherAggregator(e,t,r,i,this.manifestRepo)}createFtpPublisher(e,t,r){return new FtpPublisher(r,this.manifestRepo,e,t)}createNetlifyPublisher(e,t,r){return new NetlifyPublisher(r,this.manifestRepo,this.httpClient,e,t)}createMDFridayPublisher(e,t,r){return new MDFridayPublisher(r,this.manifestRepo,this.httpClient,e,t)}}}}),init_manifest_repository=__esm({"internal/domain/publish/repository/manifest-repository.ts"(){}}),init_http_client=__esm({"internal/domain/publish/repository/http-client.ts"(){}}),init_publish=__esm({"internal/domain/publish/index.ts"(){init_type12(),init_publisher3(),init_publish_manifest(),init_publish_config(),init_ftp_publisher(),init_netlify_publisher(),init_mdfriday_publisher(),init_publisher_factory(),init_manifest_repository(),init_http_client()}}),init_publish2=__esm({"internal/application/publish.ts"(){init_publish(),init_log(),log79=getDomainLogger("publish-service",{component:"application"}),PublishAppService=class{constructor(e,t){this.publisherFactory=e,this.workspaceService=t}async publish(e,t,r,i){log79.info(`Publishing project: ${e.getName()} to ${t.type}`);try{const s=await e.getPublishDir(),n=this.publisherFactory.create(e.getId(),e.getPath(),t),a={incremental:!r?.force};return r?.force&&(a.force=!0),i&&(a.onProgress=i),await n.publish(s,a)}catch(e){throw log79.error(`Publish failed: ${t.type}`,e),e}}async testConnection(e,t){log79.info(`Testing ${t.type} connection for project: ${e.getName()}`);try{const r=this.publisherFactory.create(e.getId(),e.getPath(),t);return r.testConnection?await r.testConnection():{success:!0}}catch(e){return log79.error(`Test connection failed: ${t.type}`,e),{success:!1,error:e.message}}}async prepareFinalConfig(e,t,r){const i=await e.getAllConfig();let s=WorkspacePublishConfig.fromGlobalConfig(i);await t.loadConfig();const n=t.getConfig();if(n?.publish){log79.debug("Merging project publish config");const e=n.publish;s=s.merge(e,r)}return this.getMethodConfig(s,r,e)}async getMethodConfig(e,t,r){switch(t){case"ftp":const i=e.getFTPConfig();if(!i)throw new Error("FTP configuration not found.\nPlease configure FTP settings:\n mdf config:set publish.ftp.host <host> --global\n mdf config:set publish.ftp.username <username> --global\n mdf config:set publish.ftp.password <password> --global\n mdf config:set publish.ftp.remotePath /public_html --global");return{type:"ftp",...i};case"netlify":const s=e.getNetlifyConfig();if(!s)throw new Error("Netlify configuration not found.\nPlease configure Netlify settings:\n mdf config:set publish.netlify.siteId <site-id> --global\n mdf config:set publish.netlify.accessToken <token> --global");return{type:"netlify",...s};case"mdfriday":const n=e.getMDFridayConfig();if(!n)throw new Error("MDFriday configuration not found.\nPlease configure MDFriday settings:\n mdf config:set publish.mdfriday.enabled true --global");const a=n.licenseKey||"";if(!a)throw new Error("❌ MDFriday license key is required for publishing.\n\nDifferent licenses deploy to different servers.\nYou must explicitly configure a license key:\n\nConfigure license globally (recommended):\n mdf config:set publish.mdfriday.licenseKey MDF-XXXX-XXXX-XXXX --global\n\nOr configure for project only:\n mdf config:set publish.mdfriday.licenseKey MDF-XXXX-XXXX-XXXX\n\n💡 Note: License login (mdf license:login) only gets TOKEN.\n Publishing requires explicitly setting a license key.");const{createIdentityService:o}=await Promise.resolve().then(()=>(init_container(),container_exports));let l=null,c="https://app.mdfriday.com";try{const e=await o(r.getInfo().path);await e.initialize(),l=e.getToken();const t=e.getServerConfig();t&&(c=t.getApiUrl(),log79.debug(`Using API URL from auth: ${c}`))}catch(e){log79.warn("Failed to get identity info",e)}if(!l)throw new Error("❌ Not authenticated.\n\nPlease login first:\n mdf auth:login\n\nOr use license login:\n mdf license:login --key YOUR-LICENSE-KEY");return{type:"mdfriday",licenseKey:a,accessToken:l,apiUrl:c,deploymentType:n.type||"share",path:"",enabled:!0};default:throw new Error(`Unsupported publish method: ${t}`)}}}}});import{promises as fs8}from"fs";import path35 from"path";var NodeSnapshotRepository,init_node_workspace_repository=__esm({"internal/infrastructure/persistence/node-workspace-repository.ts"(){NodeWorkspaceRepository=class{async isWorkspace(e){try{const t=path35.join(e,".mdfriday","workspace.json");return await fs8.access(t),!0}catch{return!1}}async initWorkspaceStructure(e,t,r){const i=path35.join(e,".mdfriday"),s=path35.join(e,t),n=path35.join(e,r);await fs8.mkdir(i,{recursive:!0}),await fs8.mkdir(s,{recursive:!0}),await fs8.mkdir(n,{recursive:!0})}async saveWorkspaceMetadata(e,t){const r=path35.join(e,".mdfriday","workspace.json");await fs8.writeFile(r,JSON.stringify(t,null,2))}async loadWorkspaceMetadata(e){const t=path35.join(e,".mdfriday","workspace.json"),r=await fs8.readFile(t,"utf-8");return JSON.parse(r)}async saveProjectRegistry(e,t){const r=path35.join(e,".mdfriday","projects.json");await fs8.writeFile(r,JSON.stringify(t,null,2))}async loadProjectRegistry(e){const t=path35.join(e,".mdfriday","projects.json"),r=await fs8.readFile(t,"utf-8");return JSON.parse(r)}},NodeProjectRepository=class{async isProject(e){try{const t=path35.join(e,".mdfriday","project.json");return await fs8.access(t),!0}catch{return!1}}async initProjectStructure(e,t,r,i){const s=path35.join(e,".mdfriday"),n=path35.join(e,t),a=path35.join(e,r),o=path35.join(e,i);await fs8.mkdir(s,{recursive:!0}),await fs8.mkdir(n,{recursive:!0}),await fs8.mkdir(a,{recursive:!0}),await fs8.mkdir(o,{recursive:!0})}async saveProjectMetadata(e,t){const r=path35.join(e,".mdfriday","project.json");await fs8.writeFile(r,JSON.stringify(t,null,2))}async loadProjectMetadata(e){const t=path35.join(e,".mdfriday","project.json"),r=await fs8.readFile(t,"utf-8");return JSON.parse(r)}async saveProjectConfig(e,t){const r=path35.join(e,"config.json");await fs8.writeFile(r,JSON.stringify(t,null,2))}async createSampleContent(e,t){await fs8.writeFile(e,t)}async deleteProjectFiles(e){await fs8.rm(e,{recursive:!0,force:!0})}async deleteProjectDirectory(e){await fs8.rm(e,{recursive:!0,force:!0})}}}});import{promises as fs9}from"fs";import path36 from"path";var log80,LANGUAGE_CODE_MAP,NodeFileSystemRepository,init_node_snapshot_repository=__esm({"internal/infrastructure/persistence/node-snapshot-repository.ts"(){NodeSnapshotRepository=class{async createSnapshot(e,t,r){const i=path36.join(e,".mdfriday","snapshots");await fs9.mkdir(i,{recursive:!0});const s=path36.join(i,t);await fs9.mkdir(s,{recursive:!0}),await this.copyDirectory(r,s);const n=await this.getDirectorySize(s),a=await this.countFiles(s),o={id:t,name:t,timestamp:Date.now(),outputDir:path36.relative(e,r),storageDir:path36.relative(e,s),size:n,fileCount:a},l=path36.join(i,`${t}.json`);return await fs9.writeFile(l,JSON.stringify(o,null,2)),o}async listSnapshots(e){const t=path36.join(e,".mdfriday","snapshots");try{await fs9.access(t)}catch{return[]}const r=(await fs9.readdir(t)).filter(e=>e.endsWith(".json")),i=[];for(const e of r)try{const r=await fs9.readFile(path36.join(t,e),"utf-8");i.push(JSON.parse(r))}catch{}return i}async getSnapshot(e,t){const r=path36.join(e,".mdfriday","snapshots"),i=path36.join(r,`${t}.json`);try{const e=await fs9.readFile(i,"utf-8"),t=JSON.parse(e);if(!t.storageDir)throw new Error("This is a legacy metadata-only snapshot and cannot be restored");return t}catch(e){if("ENOENT"===e.code)throw new Error(`Snapshot not found: ${t}`);throw e}}async restoreSnapshot(e,t,r){const i=await this.getSnapshot(e,t),s=path36.join(e,i.storageDir);try{await fs9.access(s)}catch{throw new Error(`Snapshot storage not found: ${t}`)}try{await fs9.rm(r,{recursive:!0,force:!0})}catch{}await this.copyDirectory(s,r)}async deleteSnapshot(e,t){const r=path36.join(e,".mdfriday","snapshots"),i=path36.join(r,`${t}.json`);try{const t=await fs9.readFile(i,"utf-8"),r=JSON.parse(t);if(r.storageDir){const t=path36.join(e,r.storageDir);try{await fs9.rm(t,{recursive:!0,force:!0})}catch{}}await fs9.rm(i,{force:!0})}catch(e){if("ENOENT"===e.code)throw new Error(`Snapshot not found: ${t}`);throw e}}async copyDirectory(e,t){await fs9.mkdir(t,{recursive:!0});const r=await fs9.readdir(e,{withFileTypes:!0});await Promise.all(r.map(async r=>{const i=path36.join(e,r.name),s=path36.join(t,r.name);r.isDirectory()?await this.copyDirectory(i,s):await fs9.copyFile(i,s)}))}async getDirectorySize(e){let t=0;const r=await fs9.readdir(e,{withFileTypes:!0});for(const i of r){const r=path36.join(e,i.name);i.isDirectory()?t+=await this.getDirectorySize(r):t+=(await fs9.stat(r)).size}return t}async countFiles(e){let t=0;const r=await fs9.readdir(e,{withFileTypes:!0});for(const i of r){const r=path36.join(e,i.name);i.isDirectory()?t+=await this.countFiles(r):t++}return t}}}});import{promises as fs10}from"fs";import path37 from"path";function mapLanguageCode(e){const t=e.toLowerCase().trim();return LANGUAGE_CODE_MAP[t]||t}var log81,NodeManifestRepository,init_node_file_system=__esm({"internal/infrastructure/persistence/node-file-system.ts"(){init_log(),log80=getDomainLogger("node-fs",{component:"infrastructure"}),LANGUAGE_CODE_MAP={zh:"zh",cn:"zh","zh-cn":"zh","zh-hans":"zh",en:"en",ja:"ja",jp:"ja",ko:"ko",kr:"ko",es:"es",fr:"fr",de:"de",it:"it",pt:"pt",ru:"ru"},NodeFileSystemRepository=class{async exists(e){try{return await fs10.access(e),!0}catch{return!1}}async isDirectory(e){try{return(await fs10.stat(e)).isDirectory()}catch{return!1}}async isFile(e){try{return(await fs10.stat(e)).isFile()}catch{return!1}}async readDirectory(e){try{return(await fs10.readdir(e,{withFileTypes:!0})).map(t=>({path:path37.join(e,t.name),name:t.name,isDirectory:t.isDirectory(),isFile:t.isFile()}))}catch(t){throw log80.error(`Failed to read directory: ${e}`,t),new Error(`Failed to read directory: ${t.message}`)}}async scanFolderStructure(e){try{if(!await this.exists(e))throw new Error(`Path does not exist: ${e}`);if(!await this.isDirectory(e))throw new Error(`Path is not a directory: ${e}`);const t=await this.readDirectory(e),r=[];let i=null;for(const e of t){if(!e.isDirectory)continue;const t=e.name.toLowerCase();if("content"===t)r.push({path:e.path,languageCode:"en",weight:0});else if(t.startsWith("content.")){const i=mapLanguageCode(t.split(".")[1]);r.push({path:e.path,languageCode:i,weight:1})}"static"===t&&(i={path:e.path})}r.sort((e,t)=>e.weight!==t.weight?e.weight-t.weight:path37.basename(e.path).localeCompare(path37.basename(t.path)));const s=r.length>0;return log80.debug(`Scanned folder structure: ${e}`,{contentFolders:r.length,hasStatic:!!i,isStructured:s}),{rootPath:e,contentFolders:r,staticFolder:i,isStructured:s}}catch(t){throw log80.error(`Failed to scan folder structure: ${e}`,t),t}}async createSymlink(e,t){try{if(!await this.exists(e))return{source:e,target:t,success:!1,error:`Source does not exist: ${e}`};if(await this.exists(t)){if(await this.isSymlink(t)&&await this.readSymlink(t)===e)return log80.debug(`Symlink already exists: ${t} -> ${e}`),{source:e,target:t,success:!0};await this.remove(t,!0)}const r=this.dirname(t);await this.createDirectory(r,!0);const i=(await fs10.stat(e)).isFile(),s="win32"===process.platform;return i?s?await fs10.symlink(e,t,"file"):await fs10.symlink(e,t):s?await fs10.symlink(e,t,"junction"):await fs10.symlink(e,t,"dir"),log80.debug(`Created symlink: ${t} -> ${e}`),{source:e,target:t,success:!0}}catch(r){return log80.error(`Failed to create symlink: ${t} -> ${e}`,r),{source:e,target:t,success:!1,error:r.message}}}async createSymlinks(e){const t=[];for(const r of e){const e=await this.createSymlink(r.source,r.target);t.push(e)}return t}async removeSymlink(e){try{await this.isSymlink(e)&&(await fs10.unlink(e),log80.debug(`Removed symlink: ${e}`))}catch(t){throw log80.error(`Failed to remove symlink: ${e}`,t),t}}async isSymlink(e){try{return(await fs10.lstat(e)).isSymbolicLink()}catch{return!1}}async readSymlink(e){try{return await fs10.readlink(e)}catch(t){throw log80.error(`Failed to read symlink: ${e}`,t),t}}async createDirectory(e,t=!1){try{await fs10.mkdir(e,{recursive:t}),log80.debug(`Created directory: ${e}`)}catch(t){throw log80.error(`Failed to create directory: ${e}`,t),t}}async remove(e,t=!1){try{(await fs10.lstat(e)).isDirectory()?await fs10.rm(e,{recursive:t,force:!0}):await fs10.unlink(e),log80.debug(`Removed: ${e}`)}catch(t){throw log80.error(`Failed to remove: ${e}`,t),t}}async stat(e){try{const t=await fs10.stat(e);return{isFile:()=>t.isFile(),isDirectory:()=>t.isDirectory(),isSymbolicLink:()=>t.isSymbolicLink(),size:t.size,mtime:t.mtime}}catch(t){throw log80.error(`Failed to stat: ${e}`,t),t}}async copyFile(e,t){try{const r=path37.dirname(t);await this.exists(r)||await fs10.mkdir(r,{recursive:!0}),await fs10.copyFile(e,t),log80.debug(`Copied file: ${e} -> ${t}`)}catch(r){throw log80.error(`Failed to copy file: ${e} -> ${t}`,r),r}}async readFile(e,t="utf-8"){try{return await fs10.readFile(e,t)}catch(t){throw log80.error(`Failed to read file: ${e}`,t),t}}async writeFile(e,t,r="utf-8"){try{const i=path37.dirname(e);await this.exists(i)||await fs10.mkdir(i,{recursive:!0}),await fs10.writeFile(e,t,r),log80.debug(`Wrote file: ${e}`)}catch(t){throw log80.error(`Failed to write file: ${e}`,t),t}}async unlink(e){try{await fs10.unlink(e),log80.debug(`Deleted file: ${e}`)}catch(t){throw log80.error(`Failed to delete file: ${e}`,t),t}}async access(e){try{await fs10.access(e)}catch(t){throw new Error(`Cannot access path: ${e}`)}}async resolvePath(e){return path37.resolve(e)}basename(e){return path37.basename(e)}dirname(e){return path37.dirname(e)}join(...e){return path37.join(...e)}resolvePathSync(...e){return path37.resolve(...e)}relative(e,t){return path37.relative(e,t)}parsePath(e){return path37.parse(e)}normalize(e){return path37.normalize(e)}isAbsolute(e){return path37.isAbsolute(e)}}}});import path38 from"path";import{promises as fs11}from"fs";import{createReadStream}from"fs";import crypto3 from"crypto";var log82,NodeHttpClient2,log83,NetlifyHttpClient,LLMError,LLMConnectError,LLMHttpError,LLMAbortError,FetchHttpClient,init_node_manifest_repository=__esm({"internal/infrastructure/persistence/node-manifest-repository.ts"(){init_publish(),init_log(),log81=getDomainLogger("node-manifest-repo",{component:"infrastructure"}),NodeManifestRepository=class{async loadManifest(e,t,r){const i=this.getManifestPath(e,t,r);try{const e=await fs11.readFile(i,"utf-8"),t=JSON.parse(e);return PublishManifest.fromJSON(t)}catch(e){if("ENOENT"===e.code)return log81.debug(`Manifest not found: ${i}`),null;throw log81.error(`Failed to load manifest: ${i}`,e),e}}async saveManifest(e,t,r){const i=path38.join(e,".mdfriday");await fs11.mkdir(i,{recursive:!0});const s=this.getManifestPath(e,t.getPublishMethod(),r);await fs11.writeFile(s,JSON.stringify(t.toJSON(),null,2),"utf-8"),log81.debug(`Manifest saved: ${s}`)}async generateManifest(e,t,r,i){log81.debug(`Generating manifest for: ${t}`);const s=new Map,n="netlify"===r?"sha1":"md5";return await this.scanDirectory(t,"",s,n),log81.debug(`Scanned ${s.size} files`),PublishManifest.create({projectId:e,publishMethod:r,files:s,remoteConfig:i})}async deleteManifest(e,t,r){const i=this.getManifestPath(e,t,r);try{return await fs11.unlink(i),log81.debug(`Manifest deleted: ${i}`),!0}catch(e){if("ENOENT"===e.code)return!1;throw e}}getManifestPath(e,t,r){const i=r?`manifest-${t}-${r}.json`:`manifest-${t}.json`;return path38.join(e,".mdfriday",i)}async scanDirectory(e,t,r,i="md5"){const s=await fs11.readdir(e,{withFileTypes:!0});for(const n of s){const s=path38.join(e,n.name),a=t?path38.join(t,n.name):n.name;if(n.isDirectory())await this.scanDirectory(s,a,r,i);else if(n.isFile()){const e=await fs11.stat(s),t=await this.calculateFileHash(s,i),n=a.replace(/\\/g,"/");r.set(n,{hash:t,size:e.size,mtime:e.mtimeMs,relativePath:n})}}}async calculateFileHash(e,t="md5"){return new Promise((r,i)=>{const s=crypto3.createHash(t),n=createReadStream(e);n.on("data",e=>s.update(e)),n.on("end",()=>r(s.digest("hex"))),n.on("error",i)})}}}}),init_node_http_client=__esm({"internal/infrastructure/http/node-http-client.ts"(){init_log(),log82=getDomainLogger("node-http-client",{component:"infrastructure"}),NodeHttpClient2=class{async post(e,t,r){log82.debug(`POST ${e} (JSON)`);const i=t&&Object.keys(t).length>0,s=await fetch(e,{method:"POST",headers:i?{"Content-Type":"application/json",...r}:{...r},...i&&{body:JSON.stringify(t)}}),n=await s.text();let a;try{a=JSON.parse(n)}catch{a={text:n}}return log82.debug(`Response status: ${s.status}`),{status:s.status,data:a,text:async()=>n}}async postForm(e,t){const r=Object.entries(t).map(([e,t])=>`${encodeURIComponent(e)}=${encodeURIComponent(t)}`).join("&");log82.debug(`POST ${e} (form-urlencoded)`),log82.debug(`Request body: ${r.replace(/password=[^&]+/,"password=***")}`);const i=await fetch(e,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:r}),s=await i.text();let n;log82.debug(`Response status: ${i.status}`),log82.debug(`Response text: ${s.substring(0,500)}`);try{n=JSON.parse(s)}catch(e){log82.error("Failed to parse response as JSON:",e),n={text:s}}return{status:i.status,data:n,text:async()=>s}}async postMultipart(e,t,r){const i=`----WebKitFormBoundary${Math.random().toString(36).substring(2,9)}`,s=[];new TextEncoder;for(const[e,r]of Object.entries(t))s.push(Buffer.from(`--${i}\r\n`)),s.push(Buffer.from(`Content-Disposition: form-data; name="${e}"\r\n\r\n`)),"string"==typeof r?s.push(Buffer.from(r)):Buffer.isBuffer(r)?s.push(r):s.push(Buffer.from(String(r))),s.push(Buffer.from("\r\n"));s.push(Buffer.from(`--${i}--\r\n`));const n=Buffer.concat(s);log82.debug(`POST ${e} (multipart/form-data)`),log82.debug(`Boundary: ${i}, Body size: ${n.length} bytes`);const a=await fetch(e,{method:"POST",headers:{"Content-Type":`multipart/form-data; boundary=${i}`,...r},body:n}),o=await a.text();let l;log82.debug(`Response status: ${a.status}`),log82.debug(`Response text: ${o.substring(0,500)}`);try{l=JSON.parse(o)}catch(e){log82.error("Failed to parse response as JSON:",e),l={text:o}}return{status:a.status,data:l,text:async()=>o}}async get(e,t){log82.debug(`GET ${e}`);const r=await fetch(e,{method:"GET",...t&&{headers:t}}),i=await r.text();let s;try{s=JSON.parse(i)}catch{s={text:i}}return log82.debug(`Response status: ${r.status}`),{status:r.status,data:s,text:async()=>i}}}}}),init_netlify_http_client=__esm({"internal/infrastructure/http/netlify-http-client.ts"(){init_log(),log83=getDomainLogger("netlify-http-client",{component:"infrastructure"}),NetlifyHttpClient=class{async postJSON(e,t,r){log83.debug(`POST ${e}`);const i=await fetch(e,{method:"POST",headers:{"Content-Type":"application/json",...r},body:JSON.stringify(t)});return this.createResponse(i)}async postMultipart(e,t,r){log83.debug(`POST ${e} (multipart)`);const i=`----WebKitFormBoundary${Math.random().toString(36).substring(2,15)}`,s=[];for(const[e,r]of Object.entries(t))r&&"object"==typeof r&&"data"in r?(s.push(Buffer.from(`--${i}\r\nContent-Disposition: form-data; name="${e}"; filename="${r.filename}"\r\nContent-Type: ${r.contentType}\r\n\r\n`)),s.push(Buffer.from(r.data)),s.push(Buffer.from("\r\n"))):s.push(Buffer.from(`--${i}\r\nContent-Disposition: form-data; name="${e}"\r\n\r\n${r}\r\n`));s.push(Buffer.from(`--${i}--\r\n`));const n=Buffer.concat(s),a=await fetch(e,{method:"POST",headers:{"Content-Type":`multipart/form-data; boundary=${i}`,...r},body:n});return this.createResponse(a)}async putBinary(e,t,r){log83.debug(`PUT ${e} (${t.byteLength} bytes)`);const i=await fetch(e,{method:"PUT",headers:{"Content-Type":"application/octet-stream",...r},body:t});return this.createResponse(i)}async get(e,t){log83.debug(`GET ${e}`);const r=await fetch(e,{method:"GET",...t?{headers:t}:{}});return this.createResponse(r)}async createResponse(e){const t=await e.text();let r;try{r=JSON.parse(t)}catch{r=t}return{status:e.status,ok:e.ok,statusText:e.statusText,data:r,text:async()=>t,json:async()=>"object"==typeof r?r:JSON.parse(t)}}}}}),init_provider2=__esm({"internal/infrastructure/llm/provider.ts"(){LLMError=class extends Error{constructor(e,t){super(e),this.provider=t,this.name="LLMError"}},LLMConnectError=class extends LLMError{constructor(e,t){super(`Failed to connect to ${e}: ${t?.message||"Unknown error"}`,e),this.name="LLMConnectError"}},LLMHttpError=class extends LLMError{constructor(e,t,r){super(`${e} HTTP error: ${t} ${r}`,e),this.status=t,this.statusText=r,this.name="LLMHttpError"}},LLMAbortError=class extends LLMError{constructor(e){super(`${e} request aborted`,e),this.name="LLMAbortError"}}}});function createDefaultLLMHttpClient(){return new FetchHttpClient}var OpenAICompatibleEmbeddingProvider,OllamaProvider,OllamaEmbeddingProvider,NodeFileSystem,init_fetch_http_client=__esm({"internal/infrastructure/llm/fetch-http-client.ts"(){FetchHttpClient=class{async fetch(e){const t={method:e.method};e.headers&&(t.headers=e.headers),e.body&&(t.body=e.body),e.signal&&(t.signal=e.signal);const r=await fetch(e.url,t);return{status:r.status,statusText:r.statusText,ok:r.ok,body:r.body,text:()=>r.text(),json:()=>r.json()}}}}}),init_lmstudio_provider=__esm({"internal/infrastructure/llm/lmstudio-provider.ts"(){init_provider2(),init_fetch_http_client(),OpenAICompatibleEmbeddingProvider=class{constructor(e="http://localhost:1234/v1",t="text-embedding-nomic-embed-text-v2-moe",r,i,s){this.baseURL=e,this.apiKey=i,this.embeddingModel=t,this.httpClient=r||createDefaultLLMHttpClient(),this.name=s||this.inferProviderName(e)}name;embeddingModel;httpClient;inferProviderName(e){return e.includes("localhost")||e.includes("127.0.0.1")?"LMStudio":e.includes("openai.com")?"OpenAI":e.includes("bigmodel.cn")?"GLM":e.includes("deepseek.com")?"DeepSeek":e.includes("moonshot.cn")?"Moonshot":"OpenAI-Compatible"}buildHeaders(){const e={"Content-Type":"application/json"};return this.apiKey&&(e.Authorization=`Bearer ${this.apiKey}`),e}async*complete(e,t,r){const i=`${this.baseURL}/chat/completions`,s=[];t.systemMessage&&s.push({role:"system",content:t.systemMessage}),s.push({role:"user",content:e});const n={model:t.model||this.embeddingModel,messages:s,temperature:t.temperature??.7,max_tokens:t.maxTokens??16384,stream:!0};let a;try{const e={url:i,method:"POST",headers:this.buildHeaders(),body:JSON.stringify(n)};r&&(e.signal=r),a=await this.httpClient.fetch(e)}catch(e){if("AbortError"===e.name)throw new LLMAbortError(this.name);throw new LLMConnectError(this.name,e)}if(!a.ok)throw new LLMHttpError(this.name,a.status,a.statusText);if(!a.body)throw new LLMConnectError(this.name,new Error("No response body"));const o=a.body.getReader(),l=new TextDecoder;let c="";try{for(;;){const{done:e,value:t}=await o.read();if(e)break;c+=l.decode(t,{stream:!0});const r=c.split("\n");c=r.pop()||"";for(const e of r){const t=e.trim();if(t&&"data: [DONE]"!==t&&t.startsWith("data: ")){const e=t.slice(6);try{const t=JSON.parse(e),r=t.choices[0]?.delta,i=r?.content||r?.reasoning_content||"",s=t.choices[0]?.finish_reason;if(i&&(yield{text:i,done:!1}),s)return void(yield{text:"",done:!0})}catch{}}}}yield{text:"",done:!0}}finally{o.releaseLock()}}async completeSync(e,t,r,i){const s=`${this.baseURL}/chat/completions`,n=[];t.systemMessage&&n.push({role:"system",content:t.systemMessage}),n.push({role:"user",content:e});const a={model:t.model||this.embeddingModel,messages:n,temperature:t.temperature??.7,max_tokens:t.maxTokens??16384,stream:!1};let o;try{const e={url:s,method:"POST",headers:this.buildHeaders(),body:JSON.stringify(a)};r&&(e.signal=r),o=await this.httpClient.fetch(e)}catch(e){if("AbortError"===e.name)throw new LLMAbortError(this.name);throw new LLMConnectError(this.name,e)}if(!o.ok){const e=await o.text();throw new LLMHttpError(this.name,o.status,`${o.statusText}: ${e}`)}const l=await o.json();if(i&&l.usage){const e=l.model||t.model||this.embeddingModel;i({promptTokens:l.usage.prompt_tokens??0,completionTokens:l.usage.completion_tokens??0,totalTokens:l.usage.total_tokens??0,...e?{model:e}:{}})}const c=l.choices?.[0]?.message?.content||"",h=l.choices?.[0]?.message?.reasoning_content||"",u=l.choices?.[0]?.finish_reason;return!c&&"length"===u&&h?(console.warn(`⚠️ [${this.name}] Model hit maxTokens limit during reasoning. Consider increasing maxTokens.`),h.trim()):c.trim()}async generateEmbedding(e,t,r){return this.embed({text:e,model:t,...r?{onUsage:r}:{}})}async embed(e){const t=`${this.baseURL}/embeddings`,r=e.model||this.embeddingModel,i={model:r,input:e.text};let s;try{const r={url:t,method:"POST",headers:this.buildHeaders(),body:JSON.stringify(i)};e.signal&&(r.signal=e.signal),s=await this.httpClient.fetch(r)}catch(e){if("AbortError"===e.name)throw new Error("Embedding request aborted");throw new Error(`[${this.name}] Failed to connect to embedding API: ${e.message}`)}if(!s.ok){const e=await s.text();throw new Error(`[${this.name}] Embedding API error (${s.status}): ${e}`)}const n=await s.json();if(!n.data?.[0]?.embedding)throw new Error(`[${this.name}] Invalid embedding response format`);if(e.onUsage){const t=n.usage?.prompt_tokens??0,i=n.usage?.total_tokens??t,s=t>0?t:Math.max(1,Math.ceil(e.text.length/4)),a=i>0?i:s,o=n.model||r;e.onUsage({promptTokens:s,completionTokens:0,totalTokens:a,...o?{model:o}:{}})}return n.data[0].embedding}async embedBatch(e){const t=`${this.baseURL}/embeddings`,r={model:this.embeddingModel,input:e},i=await this.httpClient.fetch({url:t,method:"POST",headers:this.buildHeaders(),body:JSON.stringify(r)});if(!i.ok){const e=await i.text();throw new Error(`[${this.name}] Embedding batch API error (${i.status}): ${e}`)}const s=await i.json();if(!s.data||!Array.isArray(s.data))throw new Error(`[${this.name}] Invalid batch embedding response format`);return s.data.sort((e,t)=>e.index-t.index).map(e=>e.embedding)}async healthCheck(){try{return(await this.httpClient.fetch({url:`${this.baseURL}/models`,method:"GET",headers:this.buildHeaders()})).ok}catch{return!1}}}}}),init_ollama_provider=__esm({"internal/infrastructure/llm/ollama-provider.ts"(){init_provider2(),OllamaProvider=class{constructor(e="http://localhost:11434"){this.baseURL=e}name="Ollama";async*complete(e,t,r){t.systemMessage?yield*this.completeWithChat(e,t,r):yield*this.completeWithGenerate(e,t,r)}async*completeWithChat(e,t,r){const i=`${this.baseURL}/api/chat`,s=[];t.systemMessage&&s.push({role:"system",content:t.systemMessage}),s.push({role:"user",content:e});const n={model:t.model||"llama2",messages:s,stream:!0,options:{temperature:t.temperature??.7,num_predict:t.maxTokens??16384}};let a;try{a=await fetch(i,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n),...r?{signal:r}:{}})}catch(e){if("AbortError"===e.name)throw new LLMAbortError(this.name);throw new LLMConnectError(this.name,e)}if(!a.ok)throw new LLMHttpError(this.name,a.status,a.statusText);if(!a.body)throw new LLMConnectError(this.name,new Error("No response body"));const o=a.body.getReader(),l=new TextDecoder;try{for(;;){const{done:e,value:r}=await o.read();if(e)break;const i=l.decode(r,{stream:!0}).split("\n").filter(e=>e.trim());for(const e of i)try{const r=JSON.parse(e),i=r.message?.content||"";if(i&&(yield{text:i,done:!1}),r.done){const e=void 0!==r.prompt_eval_count||void 0!==r.eval_count?{promptTokens:r.prompt_eval_count??0,completionTokens:r.eval_count??0,totalTokens:(r.prompt_eval_count??0)+(r.eval_count??0),model:r.model||t.model}:void 0;return void(yield{text:"",done:!0,...e?{usage:e}:{}})}}catch(t){console.warn("Failed to parse Ollama chunk:",e)}}}finally{o.releaseLock()}}async*completeWithGenerate(e,t,r){const i=`${this.baseURL}/api/generate`,s={model:t.model||"llama2",prompt:e,stream:!0,options:{temperature:t.temperature??.7,num_predict:t.maxTokens??4096}};let n;try{n=await fetch(i,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(s),...r?{signal:r}:{}})}catch(e){if("AbortError"===e.name)throw new LLMAbortError(this.name);throw new LLMConnectError(this.name,e)}if(!n.ok)throw new LLMHttpError(this.name,n.status,n.statusText);if(!n.body)throw new LLMConnectError(this.name,new Error("No response body"));const a=n.body.getReader(),o=new TextDecoder;try{for(;;){const{done:e,value:r}=await a.read();if(e)break;const i=o.decode(r,{stream:!0}).split("\n").filter(e=>e.trim());for(const e of i)try{const r=JSON.parse(e);if(r.done){const e=void 0!==r.prompt_eval_count||void 0!==r.eval_count?{promptTokens:r.prompt_eval_count??0,completionTokens:r.eval_count??0,totalTokens:(r.prompt_eval_count??0)+(r.eval_count??0),model:r.model||t.model}:void 0;return void(yield{text:r.response||"",done:!0,...e?{usage:e}:{}})}yield{text:r.response||"",done:!1}}catch(t){console.warn("Failed to parse Ollama chunk:",e)}}}finally{a.releaseLock()}}async completeSync(e,t,r,i){let s="";for await(const n of this.complete(e,t,r))n.done?n.usage&&i&&i(n.usage):s+=n.text;return s.trim()}async healthCheck(){try{return(await fetch(`${this.baseURL}/api/tags`,{method:"GET"})).ok}catch{return!1}}}}}),init_llm=__esm({"internal/infrastructure/llm/index.ts"(){init_provider2(),init_lmstudio_provider(),init_ollama_provider()}}),init_embedding_provider_interface=__esm({"internal/infrastructure/embedding/embedding-provider.interface.ts"(){}}),init_ollama_embedding_provider=__esm({"internal/infrastructure/embedding/ollama-embedding-provider.ts"(){OllamaEmbeddingProvider=class{config;constructor(e){this.config={timeout:3e4,...e}}async generateEmbedding(e,t,r){return this.embed({text:e,model:t,...r?{onUsage:r}:{}})}async embed(e){const t=e.model??this.config.model,r=`${this.config.baseUrl}/api/embeddings`,i=new AbortController,s=setTimeout(()=>i.abort(),this.config.timeout);try{const s=await fetch(r,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({model:t,prompt:e.text}),signal:e.signal??i.signal});if(!s.ok)throw new Error(`Ollama embedding failed: ${s.status} ${s.statusText}`);const n=await s.json();if(!n.embedding||!Array.isArray(n.embedding))throw new Error("Invalid embedding response from Ollama");if(e.onUsage){const r=n.prompt_eval_count??0,i=r>0?r:Math.max(1,Math.ceil(e.text.length/4)),s=n.model||t;e.onUsage({promptTokens:i,completionTokens:0,totalTokens:i,...s?{model:s}:{}})}return n.embedding}finally{clearTimeout(s)}}async embedBatch(e){const t=[];for(const r of e){const e=await this.embed({text:r});t.push(e)}return t}async healthCheck(){try{const e=await this.embed({text:"test"});return Array.isArray(e)&&e.length>0}catch(e){return console.error("Ollama embedding health check failed:",e),!1}}}}}),init_embedding=__esm({"internal/infrastructure/embedding/index.ts"(){init_embedding_provider_interface(),init_ollama_embedding_provider()}});import*as fs12 from"fs/promises";import*as fsSync from"fs";var NodePathService,init_node_file_system2=__esm({"internal/infrastructure/node/node-file-system.ts"(){NodeFileSystem=class{async readFile(e,t){return await fs12.readFile(e,t)}async writeFile(e,t,r){await fs12.writeFile(e,t,r)}async stat(e){const t=await fs12.stat(e);return{mtimeMs:t.mtimeMs,isFile:()=>t.isFile(),isDirectory:()=>t.isDirectory()}}async exists(e){try{return await fs12.access(e),!0}catch{return!1}}async mkdir(e,t){await fs12.mkdir(e,t)}async readdir(e){return await fs12.readdir(e)}async unlink(e){await fs12.unlink(e)}existsSync(e){return fsSync.existsSync(e)}readFileSync(e,t){return fsSync.readFileSync(e,t)}statSync(e){const t=fsSync.statSync(e);return{mtimeMs:t.mtimeMs,isFile:()=>t.isFile(),isDirectory:()=>t.isDirectory()}}}}});import*as path39 from"path";var NodeCryptoService,init_node_path_service=__esm({"internal/infrastructure/node/node-path-service.ts"(){NodePathService=class{join(...e){return path39.join(...e)}basename(e,t){return path39.basename(e,t)}dirname(e){return path39.dirname(e)}relative(e,t){return path39.relative(e,t)}resolve(...e){return path39.resolve(...e)}extname(e){return path39.extname(e)}}}});import*as crypto4 from"crypto";var NodeConversationRepository,EntityId,EntityType,ConnectionType,SourceRecord,ExtractionResult,init_node_crypto_service=__esm({"internal/infrastructure/node/node-crypto-service.ts"(){NodeCryptoService=class{hash(e,t){return crypto4.createHash(t).update(e).digest("hex")}randomUUID(){return crypto4.randomUUID()}}}}),init_node_conversation_repository=__esm({"internal/infrastructure/node/node-conversation-repository.ts"(){NodeConversationRepository=class{constructor(e,t,r){this.baseDir=e,this.fileSystem=t,this.pathService=r,this.ensureDirectory()}async save(e,t={}){const r=e.getFilename(),i=this.pathService.join(this.baseDir,r);if(await this.fileSystem.exists(this.baseDir)||await this.fileSystem.mkdir(this.baseDir,{recursive:!0}),!t.overwrite&&await this.fileSystem.exists(i))throw new Error(`Conversation file already exists: ${i}`);const s=e.formatAsMarkdown();return await this.fileSystem.writeFile(i,s,"utf-8"),i}async list(){if(!await this.fileSystem.exists(this.baseDir))return[];const e=await this.fileSystem.readdir(this.baseDir);for(const t of e)if(t.endsWith(".md")){const e=this.pathService.join(this.baseDir,t);try{await this.fileSystem.readFile(e,"utf-8")}catch(t){console.warn(`Failed to read conversation file: ${e}`,t)}}return[]}async exists(e){const t=`${e}.md`,r=this.pathService.join(this.baseDir,t);return await this.fileSystem.exists(r)}getFilePath(e){const t=`${e}.md`;return this.pathService.join(this.baseDir,t)}ensureDirectory(){}}}}),init_entity_id=__esm({"internal/domain/wiki/value-object/entity-id.ts"(){EntityId=class e{_value;constructor(e){this._value=e}get value(){return this._value}static create(t){const r=t.toLowerCase().trim().replace(/[^\w\s\u4e00-\u9fa5-]/g,"").replace(/\s+/g,"-").replace(/-+/g,"-").replace(/^-|-$/g,"");if(!r)throw new Error("Cannot create EntityId from empty string");return new e(r)}equals(e){return this._value===e._value}toString(){return this._value}}}}),init_entity_type=__esm({"internal/domain/wiki/value-object/entity-type.ts"(){EntityType=class e{static VALID_TYPES=new Set(["person","org","tool","project","book","article","place","event","other"]);_value;constructor(e){this._value=e}get value(){return this._value}static fromString(t){const r=t.toLowerCase();return e.VALID_TYPES.has(r)?new e(r):new e("other")}equals(e){return this._value===e._value}toString(){return this._value}static PERSON=new e("person");static ORG=new e("org");static TOOL=new e("tool");static PROJECT=new e("project");static BOOK=new e("book");static ARTICLE=new e("article");static PLACE=new e("place");static EVENT=new e("event");static OTHER=new e("other")}}}),init_connection_type=__esm({"internal/domain/wiki/value-object/connection-type.ts"(){ConnectionType=class e{static VALID_TYPES=new Set(["influences","uses","critiques","extends","part-of","created-by","related-to","applies-to","contrasts-with"]);_value;constructor(e){this._value=e}get value(){return this._value}static fromString(t){const r=t.toLowerCase();return e.VALID_TYPES.has(r)?new e(r):new e("related-to")}equals(e){return this._value===e._value}toString(){return this._value}static INFLUENCES=new e("influences");static USES=new e("uses");static CRITIQUES=new e("critiques");static EXTENDS=new e("extends");static PART_OF=new e("part-of");static CREATED_BY=new e("created-by");static RELATED_TO=new e("related-to");static APPLIES_TO=new e("applies-to");static CONTRASTS_WITH=new e("contrasts-with")}}}),init_source_record=__esm({"internal/domain/wiki/value-object/source-record.ts"(){SourceRecord=class e{path;summary;date;mtime;origin;contentHash;constructor(e,t,r,i,s,n){this.path=e,this.summary=t,this.date=r,this.mtime=i,this.origin=s,this.contentHash=n}toJSON(){return{path:this.path,summary:this.summary,date:this.date.toISOString(),mtime:this.mtime,origin:this.origin,contentHash:this.contentHash}}static fromJSON(t){return new e(t.path,t.summary,new Date(t.date),t.mtime,t.origin,t.contentHash)}}}}),init_extraction_result=__esm({"internal/domain/wiki/value-object/extraction-result.ts"(){ExtractionResult=class e{sourceSummary;entities;concepts;connections;constructor(e,t,r,i){this.sourceSummary=e,this.entities=t,this.concepts=r,this.connections=i}static fromJSON(t){return new e(t.source_summary||"",t.entities||[],t.concepts||[],t.connections||[])}toJSON(){return{source_summary:this.sourceSummary,entities:this.entities,concepts:this.concepts,connections:this.connections}}}}});function cleanString(e){return"string"!=typeof e?"":e.trim()}function cleanEntities(e){return Array.isArray(e)?e.filter(e=>e&&e.name).map(e=>({name:cleanString(e.name),type:cleanString(e.type||"other"),aliases:cleanArray(e.aliases),facts:cleanArray(e.facts)})).filter(e=>e.name.length>0):[]}function cleanConcepts(e){return Array.isArray(e)?e.filter(e=>e&&e.name).map(e=>({name:cleanString(e.name),definition:cleanString(e.definition||""),related:cleanArray(e.related)})).filter(e=>e.name.length>0):[]}function cleanConnections(e){return Array.isArray(e)?e.filter(e=>e&&e.from&&e.to).map(e=>({from:cleanString(e.from),to:cleanString(e.to),type:cleanString(e.type||"related-to"),description:cleanString(e.description||"")})).filter(e=>e.from.length>0&&e.to.length>0):[]}function cleanArray(e){return Array.isArray(e)?e.filter(e=>"string"==typeof e).map(e=>e.trim()).filter(e=>e.length>0):[]}var WIKI_KB_FILENAME,WIKI_EMBEDDINGS_FILENAME,init_extraction_parser=__esm({"internal/domain/wiki/value-object/extraction-parser.ts"(){init_extraction_result()}});function createWikiConfig(e){return{kbPath:WIKI_KB_FILENAME,embeddingsPath:WIKI_EMBEDDINGS_FILENAME,wikiDir:e,entitiesDir:`${e}/entities`,conceptsDir:`${e}/concepts`,sourcesDir:`${e}/sources`,conversationsDir:`${e}/conversations`,indexFile:`${e}/index.md`,glossaryFile:`${e}/GLOSSARY.md`,logFile:`${e}/log.md`}}var Retrieval,ContentAnnotator,MODEL_PRICING,init_wiki_config=__esm({"internal/domain/wiki/value-object/wiki-config.ts"(){WIKI_KB_FILENAME="kb.json",WIKI_EMBEDDINGS_FILENAME="embeddings.json",createWikiConfig(".wiki/wiki")}}),init_retrieval=__esm({"internal/domain/wiki/value-object/retrieval.ts"(){Retrieval=class{static extractQueryTerms(e){return e.toLowerCase().split(/\s+/).filter(e=>e.length>=3)}static rankByKeyword(e,t){if(0===t.length)return[];const r=[];for(const i of e.getAllEntities()){let e=0;const s=i.name.toLowerCase(),n=Array.from(i.aliases).map(e=>e.toLowerCase());for(const r of t){(s.includes(r)||n.some(e=>e.includes(r)))&&(e+=3);for(const t of i.facts)t.toLowerCase().includes(r)&&(e+=1)}for(let r=0;r<t.length-1;r++){const i=`${t[r]} ${t[r+1]}`;s.includes(i)&&(e+=6)}e>0&&r.push({id:i.id.value,score:e,richness:i.facts.length+i.sources.length})}for(const i of e.getAllConcepts()){let e=0;const s=i.name.toLowerCase(),n=Array.from(i.aliases).map(e=>e.toLowerCase()),a=(i.definition??"").toLowerCase();for(const r of t)(s.includes(r)||n.some(e=>e.includes(r)))&&(e+=3),a.includes(r)&&(e+=1);for(let r=0;r<t.length-1;r++){const i=`${t[r]} ${t[r+1]}`;s.includes(i)&&(e+=6)}e>0&&r.push({id:`concept:${i.id.value}`,score:e,richness:i.related.length+i.sources.length})}return r.sort((e,t)=>t.score-e.score||t.richness-e.richness),r.map(({id:e,score:t})=>({id:e,score:t}))}static rankByPath(e,t){if(0===t.length)return[];const r=[];for(const i of e.getAllEntities()){let e=0;for(const r of i.sources){const i=r.toLowerCase();for(const r of t)i.includes(r)&&(e+=1)}e>0&&r.push({id:i.id.value,score:e})}for(const i of e.getAllConcepts()){let e=0;for(const r of i.sources){const i=r.toLowerCase();for(const r of t)i.includes(r)&&(e+=1)}e>0&&r.push({id:`concept:${i.id.value}`,score:e})}return r.sort((e,t)=>t.score-e.score),r}static rankByEmbedding(e,t){const r=[],i=(Map,()=>e.keys()),s=t=>e.get(t);for(const e of i()){const i=s(e);if(!i)continue;const n=this.cosineSimilarity(t,i);n>0&&r.push({id:e,score:n})}return r.sort((e,t)=>t.score-e.score),r.slice(0,50)}static rrfFuse(e,t,r=60){const i=new Map;for(let s=0;s<e.length;s++){const n=e[s],a=t[s]??1;for(let e=0;e<n.length;e++){const t=n[e],s=a/(r+e+1);i.set(t.id,(i.get(t.id)??0)+s)}}return Array.from(i.entries()).map(([e,t])=>({id:e,score:t})).sort((e,t)=>t.score-e.score)}static qualityMultiplier(e,t){if(e.startsWith("concept:")){const r=e.slice(8),i=t.getConcept(r);return i?1+.1*(i.related.length+i.sources.length):1}{const r=t.getEntity(e);return r?1+.1*(r.facts.length+r.sources.length):1}}static cosineSimilarity(e,t){const r=Math.min(e.length,t.length);let i=0,s=0,n=0;for(let a=0;a<r;a++){const r=e[a],o=t[a];i+=r*o,s+=r*r,n+=o*o}return 0===s||0===n?0:i/(Math.sqrt(s)*Math.sqrt(n))}static contextualTextForEntity(e){const t=[`Entity [${e.type.value}]: ${e.name}.`],r=Array.from(e.aliases);return r.length>0&&t.push(`Also known as: ${r.join(", ")}.`),e.facts.length>0&&t.push(e.facts.slice(0,5).join(" ")),t.join(" ")}static contextualTextForConcept(e){const t=[`Concept: ${e.name}.`],r=(e.definition??"").slice(0,200);return r.length>0&&t.push(r),e.related&&e.related.length>0&&t.push(`Related to: ${e.related.join(", ")}.`),t.join(" ")}static async buildEmbeddingIndex(e){const t=new Map,r=e.kb.getAllEntities(),i=e.kb.getAllConcepts(),s=r.length+i.length;let n=0;const a=t=>{n+=1,e.onProgress?.({current:n,total:s,phase:t})};for(const i of r){if(e.signal?.aborted)throw new Error("Embedding index build aborted");const r=i.id.value,s=this.contextualTextForEntity(i),n=e.cache.entries[r];if(n&&n.sourceText===s){t.set(r,n.vector),a("entities");continue}const o=await e.provider.embed({text:s,model:e.model,...e.signal?{signal:e.signal}:{}});e.cache.entries[r]={sourceText:s,vector:o},t.set(r,o),a("entities")}for(const r of i){if(e.signal?.aborted)throw new Error("Embedding index build aborted");const i=`concept:${r.id.value}`,s=this.contextualTextForConcept(r),n=e.cache.entries[i];if(n&&n.sourceText===s){t.set(i,n.vector),a("concepts");continue}const o=await e.provider.embed({text:s,model:e.model,...e.signal?{signal:e.signal}:{}});e.cache.entries[i]={sourceText:s,vector:o},t.set(i,o),a("concepts")}return t}static createEmbeddingCache(){return{entries:{}}}static loadEmbeddingCache(e){try{return JSON.parse(e)}catch{return this.createEmbeddingCache()}}static saveEmbeddingCache(e){return JSON.stringify(e,null,2)}}}}),init_content_annotator=__esm({"internal/domain/wiki/value-object/content-annotator.ts"(){ContentAnnotator=class{options;constructor(e={}){this.options={markFirstOccurrenceOnly:e.markFirstOccurrenceOnly??!0,contextAware:e.contextAware??!0,differentMarkers:e.differentMarkers??!1}}annotate(e,t,r){const i=this.collectTerms(t,r),s=[];i.forEach(e=>{s.push({term:e,text:e.name,isAlias:!1}),e.aliases.forEach(t=>{t&&t!==e.name&&s.push({term:e,text:t,isAlias:!0})})});const n=s.sort((e,t)=>t.text.length-e.text.length);return this.markTerms(e,n)}collectTerms(e,t){const r=[];return e.forEach(e=>{r.push({name:e.name,aliases:Array.from(e.aliases),type:"entity"})}),t.forEach(e=>{r.push({name:e.name,aliases:Array.from(e.aliases),type:"concept"})}),r}markTerms(e,t){const r=this.options.contextAware?this.extractSkipRanges(e):[];let i=e;const s=new Set;for(const{term:e,text:n,isAlias:a}of t){const t=e.name;i=this.markSingleTerm(i,n,t,e.type,r,s)}return i}extractSkipRanges(e){const t=[],r=e.match(/^---\n[\s\S]*?\n---\n/);r&&t.push([0,r[0].length]);const i=/```[\s\S]*?```/g;let s;for(;null!==(s=i.exec(e));)t.push([s.index,s.index+s[0].length]);const n=/`[^`]+`/g;for(;null!==(s=n.exec(e));)t.push([s.index,s.index+s[0].length]);const a=/\[\[[^\]]+\]\]/g;for(;null!==(s=a.exec(e));)t.push([s.index,s.index+s[0].length]);const o=/^#{1,6}\s+/gm;for(;null!==(s=o.exec(e));)t.push([s.index,s.index+s[0].length]);return t.sort((e,t)=>e[0]-t[0]),t}isInSkipRange(e,t){return t.some(([t,r])=>e>=t&&e<r)}markSingleTerm(e,t,r,i,s,n){const a=t.toLowerCase();if(this.options.markFirstOccurrenceOnly&&n.has(a))return e;const o=this.escapeRegex(t),l=/[\u4e00-\u9fa5]/.test(t),c=new RegExp(l?`(?<!\\[\\[)${o}(?!\\]\\])`:`(?<!\\[\\[)\\b${o}\\b(?!\\]\\])`,"gi");let h,u="",g=0,d=0;for(;null!==(h=c.exec(e));){const t=h.index,n=t+h[0].length;if(!this.options.contextAware||!this.isInSkipRange(t,s)){if(this.options.markFirstOccurrenceOnly&&d>0)break;u+=e.substring(g,t),this.options.differentMarkers?u+="entity"===i?`[[${r}]]`:`**[[${r}]]**`:u+=`[[${r}]]`,g=n,d++}}return u+=e.substring(g),d>0&&n.add(a),u}escapeRegex(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}}}}),init_wiki_page_renderer=__esm({"internal/domain/wiki/value-object/wiki-page-renderer.ts"(){init_content_annotator()}}),init_wiki_index_generator=__esm({"internal/domain/wiki/value-object/wiki-index-generator.ts"(){}}),init_token_usage=__esm({"internal/domain/wiki/value-object/token-usage.ts"(){}});function findPricing(e,t){const r=e.toLowerCase(),i=t.toLowerCase();return MODEL_PRICING.find(e=>e.provider.toLowerCase()===r&&e.model.toLowerCase()===i)||MODEL_PRICING.find(e=>e.provider.toLowerCase()===r&&"*"===e.model)}function estimateCost(e,t,r,i){const s=findPricing(e,t);if(!s)return;const n=r/1e6*s.inputPer1M,a=i/1e6*s.outputPer1M,o=s.model.toLowerCase()===t.toLowerCase();return{provider:s.provider,model:"*"===s.model?t:s.model,inputTokens:r,outputTokens:i,inputCost:n,outputCost:a,totalCost:n+a,currency:"USD",isLocal:s.isLocal??!1,isExact:o}}var Entity,Concept,Connection,OperationLog,EmbeddingIndex,KnowledgeBase,Conversation,WikiFactory,NodeKBRepository,NodeWikiPageRepository,log84,IdentityAppService,init_pricing=__esm({"internal/domain/wiki/value-object/pricing.ts"(){MODEL_PRICING=[{provider:"openai",model:"gpt-4.1",inputPer1M:2,outputPer1M:8,currency:"USD"},{provider:"openai",model:"gpt-4.1-mini",inputPer1M:.4,outputPer1M:1.6,currency:"USD"},{provider:"openai",model:"gpt-4o",inputPer1M:5,outputPer1M:15,currency:"USD"},{provider:"openai",model:"gpt-4o-mini",inputPer1M:.15,outputPer1M:.6,currency:"USD"},{provider:"deepseek",model:"deepseek-chat",inputPer1M:.27,outputPer1M:1.1,currency:"USD"},{provider:"deepseek",model:"deepseek-reasoner",inputPer1M:.55,outputPer1M:2.19,currency:"USD"},{provider:"glm",model:"glm-4-plus",inputPer1M:.7,outputPer1M:.7,currency:"USD"},{provider:"glm",model:"glm-4-air",inputPer1M:.14,outputPer1M:.14,currency:"USD"},{provider:"glm",model:"glm-5.1",inputPer1M:.88,outputPer1M:3.52,currency:"USD"},{provider:"moonshot",model:"moonshot-v1-128k",inputPer1M:.7,outputPer1M:2.8,currency:"USD"},{provider:"moonshot",model:"moonshot-v1-32k",inputPer1M:.4,outputPer1M:1.6,currency:"USD"},{provider:"ollama",model:"*",inputPer1M:0,outputPer1M:0,currency:"USD",isLocal:!0},{provider:"lmstudio",model:"*",inputPer1M:0,outputPer1M:0,currency:"USD",isLocal:!0}]}}),init_entity2=__esm({"internal/domain/wiki/entity/entity.ts"(){init_entity_id(),init_entity_type(),Entity=class e{_id;_name;_type;_aliases;_facts;_sources;constructor(e,t,r,i=[],s=[],n=[]){this._id=e,this._name=t,this._type=r,this._aliases=[...i],this._facts=[...s],this._sources=[...n]}get id(){return this._id}get name(){return this._name}get type(){return this._type}get aliases(){return this._aliases}get facts(){return this._facts}get sources(){return this._sources}merge(e,t,r){for(const t of e)this._aliases.includes(t)||this._aliases.push(t);for(const e of t)this._facts.includes(e)||this._facts.push(e);this._sources.includes(r)||this._sources.push(r)}qualityScore(){return 2*this._facts.length+this._sources.length}toJSON(){return{id:this._id.value,name:this._name,type:this._type.value,aliases:this._aliases,facts:this._facts,sources:this._sources}}static fromJSON(t){return new e(EntityId.create(t.name),t.name,EntityType.fromString(t.type),t.aliases||[],t.facts||[],t.sources||[])}}}}),init_concept=__esm({"internal/domain/wiki/entity/concept.ts"(){init_entity_id(),Concept=class e{_id;_name;_definition;_related;_sources;_aliases;constructor(e,t,r,i=[],s=[],n=[]){this._id=e,this._name=t,this._definition=r,this._related=[...i],this._sources=[...s],this._aliases=new Set(n)}get id(){return this._id}get name(){return this._name}get definition(){return this._definition}get related(){return this._related}get sources(){return this._sources}get aliases(){return this._aliases}merge(e,t,r,i){e&&e.length>this._definition.length&&(this._definition=e);for(const e of t)this._related.includes(e)||this._related.push(e);for(const e of r)e&&e!==this._name&&this._aliases.add(e);this._sources.includes(i)||this._sources.push(i)}qualityScore(){return(this._definition.length>0?10:0)+2*this._related.length+this._sources.length}toJSON(){return{id:this._id.value,name:this._name,definition:this._definition,related:this._related,sources:this._sources,aliases:Array.from(this._aliases)}}static fromJSON(t){return new e(EntityId.create(t.name),t.name,t.definition||"",t.related||[],t.sources||[],t.aliases||[])}}}}),init_connection=__esm({"internal/domain/wiki/entity/connection.ts"(){init_connection_type(),Connection=class e{_from;_to;_type;_description;_sources;constructor(e,t,r,i="",s=[]){this._from=e,this._to=t,this._type=r,this._description=i,this._sources=[...s]}get from(){return this._from}get to(){return this._to}get type(){return this._type}get description(){return this._description}get sources(){return this._sources}addSource(e){this._sources.includes(e)||this._sources.push(e)}updateDescription(e){e&&e.length>this._description.length&&(this._description=e)}toJSON(){return{from:this._from,to:this._to,type:this._type.value,description:this._description,sources:this._sources}}static fromJSON(t){return new e(t.from,t.to,ConnectionType.fromString(t.type),t.description||"",t.sources||[])}}}}),init_operation_log=__esm({"internal/domain/wiki/entity/operation-log.ts"(){OperationLog=class e{entries=[];addIngest(e){const t=`${this.getFilename(e.sourcePath)} → ${e.entities}E, ${e.concepts}C, ${e.connections}Conn`;this.entries.push({timestamp:new Date,operation:"ingest",details:t,metadata:e})}addQuery(e){const t=e.answerSaved?" [saved]":"",r=`"${this.truncate(e.query,60)}" → ${e.resultCount} results${t}`;this.entries.push({timestamp:new Date,operation:"query",details:r,metadata:e})}addLint(e){const t=`${e.issuesCount} issues found`+(e.issuesCount>0?` (${this.formatCategories(e.categories)})`:"");this.entries.push({timestamp:new Date,operation:"lint",details:t,metadata:e})}addGenerate(e){const t=`${e} pages generated`;this.entries.push({timestamp:new Date,operation:"generate",details:t,metadata:{pageCount:e}})}addSaveAnswer(e,t){const r=`"${this.truncate(e,50)}" → ${t}`;this.entries.push({timestamp:new Date,operation:"save-answer",details:r,metadata:{query:e,filepath:t}})}toMarkdown(){return 0===this.entries.length?"# Operation Log\n\nNo operations recorded yet.\n":"# Operation Log\n\n> This file records all operations performed on the wiki (ingests, queries, lints, etc.)\n\n"+this.entries.map(e=>`## [${this.formatTimestamp(e.timestamp)}] ${this.formatOperation(e.operation)} | ${e.details}`).join("\n\n")+"\n"}appendToExisting(e){if(0===this.entries.length)return e;if(!e||e.includes("No operations recorded yet"))return this.toMarkdown();const t=this.entries.map(e=>`## [${this.formatTimestamp(e.timestamp)}] ${this.formatOperation(e.operation)} | ${e.details}`).join("\n\n");return e.trim()+"\n\n"+t+"\n"}get count(){return this.entries.length}clear(){this.entries=[]}static fromJSON(t){const r=new e;return t&&Array.isArray(t.entries)&&(r.entries=t.entries.map(e=>({...e,timestamp:new Date(e.timestamp)}))),r}toJSON(){return{entries:this.entries}}formatTimestamp(e){return`${e.getFullYear()}-${String(e.getMonth()+1).padStart(2,"0")}-${String(e.getDate()).padStart(2,"0")} ${String(e.getHours()).padStart(2,"0")}:${String(e.getMinutes()).padStart(2,"0")}`}formatOperation(e){return{ingest:"ingest",query:"query",lint:"lint",generate:"generate","save-answer":"save-answer"}[e]||e}getFilename(e){const t=e.split("/");return t[t.length-1]}truncate(e,t){return e.length<=t?e:e.slice(0,t-3)+"..."}formatCategories(e){return Object.entries(e).map(([e,t])=>`${e}:${t}`).join(", ")}}}}),init_embedding_index=__esm({"internal/domain/wiki/entity/embedding-index.ts"(){EmbeddingIndex=class e{index;cachePath;isDirty=!1;constructor(e,t){this.cachePath=e,this.index=t||new Map}set(e,t){this.index.set(e,t),this.isDirty=!0}get(e){return this.index.get(e)}findSimilar(e,t){const r=[];for(const[t,i]of this.index.entries()){const s=this.cosineSimilarity(e,i);r.push({key:t,similarity:s})}return r.sort((e,t)=>t.similarity-e.similarity).slice(0,t)}getReadOnlyIndex(){return this.index}keys(){return this.index.keys()}has(e){return this.index.has(e)}toJSON(){return Object.fromEntries(this.index.entries())}static fromJSON(t,r){const i=new Map(Object.entries(r)),s=new e(t,i);return s.isDirty=!1,s}cosineSimilarity(e,t){if(e.length!==t.length)return 0;let r=0,i=0,s=0;for(let n=0;n<e.length;n++)r+=e[n]*t[n],i+=e[n]*e[n],s+=t[n]*t[n];const n=Math.sqrt(i)*Math.sqrt(s);return 0===n?0:r/n}getCachePath(){return this.cachePath}isDirtyState(){return this.isDirty}markClean(){this.isDirty=!1}size(){return this.index.size}clear(){this.index.clear(),this.isDirty=!0}}}}),init_knowledge_base=__esm({"internal/domain/wiki/entity/knowledge-base.ts"(){init_entity2(),init_concept(),init_connection(),init_operation_log(),init_embedding_index(),init_source_record(),init_entity_id(),init_entity_type(),init_connection_type(),init_extraction_parser(),init_retrieval(),init_content_annotator(),KnowledgeBase=class e{_entities;_concepts;_connections;_sources;_operationLog;_embeddingIndex=null;_version;_createdAt;_updatedAt;constructor(){this._entities=new Map,this._concepts=new Map,this._connections=[],this._sources=new Map,this._operationLog=new OperationLog,this._embeddingIndex=null,this._version=1,this._createdAt=new Date,this._updatedAt=new Date}addOrMergeEntity(e,t,r,i,s){const n=EntityId.create(e),a=n.value,o=this._entities.get(a);if(o)return o.merge(r,i,s),this._updatedAt=new Date,o;{const o=new Entity(n,e,EntityType.fromString(t),r,i,[s]);return this._entities.set(a,o),this._updatedAt=new Date,o}}addOrMergeConcept(e,t,r,i,s){const n=EntityId.create(e),a=n.value,o=this._concepts.get(a);if(o)return o.merge(t,r,i,s),this._updatedAt=new Date,o;{const o=new Concept(n,e,t,r,[s],i);return this._concepts.set(a,o),this._updatedAt=new Date,o}}addConnection(e,t,r,i,s){const n=EntityId.create(e).value,a=EntityId.create(t).value,o=this._connections.find(e=>e.from===n&&e.to===a&&e.type.value===r);if(o)return o.addSource(s),o.updateDescription(i),this._updatedAt=new Date,o;{const e=new Connection(n,a,ConnectionType.fromString(r),i,[s]);return this._connections.push(e),this._updatedAt=new Date,e}}markSource(e){this._sources.set(e.path,e),this._updatedAt=new Date}getOperationLog(){return this._operationLog}getStats(){return{entities:this._entities.size,concepts:this._concepts.size,connections:this._connections.length,sources:this._sources.size,operations:this._operationLog.count}}needsExtraction(e,t,r){const i=this._sources.get(e);return!i||i.contentHash!==r}isNewSource(e){return!this._sources.has(e)}getIngestedPaths(){return new Set(this._sources.keys())}backfillContentHash(e,t,r){const i=this._sources.get(e);if(i){const s=new SourceRecord(i.path,i.summary,i.date,r,i.origin,t);this._sources.set(e,s)}}get entities(){return this._entities.values()}get concepts(){return this._concepts.values()}get connections(){return this._connections}get sources(){return this._sources.values()}getEntity(e){return this._entities.get(e)}getConcept(e){return this._concepts.get(e)}getSource(e){return this._sources.get(e)}getAllEntities(){return Array.from(this._entities.values())}getAllConcepts(){return Array.from(this._concepts.values())}getAllSources(){return Array.from(this._sources.values())}getConnectionsByEntity(e){const t=e.value;return this._connections.filter(e=>e.from===t||e.to===t)}getEntitiesBySource(e){return Array.from(this._entities.values()).filter(t=>t.sources.includes(e))}getConceptsBySource(e){return Array.from(this._concepts.values()).filter(t=>t.sources.includes(e))}exportVocabulary(){let e="ENTITIES:\n";for(const t of this._entities.values())e+=`- ${t.name} (${t.type.value})\n`;e+="\nCONCEPTS:\n";for(const t of this._concepts.values())e+=`- ${t.name}\n`;return e}toJSON(){return{meta:{version:this._version,created:this._createdAt.toISOString(),updated:this._updatedAt.toISOString()},entities:Object.fromEntries(Array.from(this._entities.entries()).map(([e,t])=>[e,t.toJSON()])),concepts:Object.fromEntries(Array.from(this._concepts.entries()).map(([e,t])=>[e,t.toJSON()])),connections:this._connections.map(e=>e.toJSON()),sources:Object.fromEntries(Array.from(this._sources.entries()).map(([e,t])=>[e,t.toJSON()]))}}static fromJSON(t){const r="string"==typeof t?JSON.parse(t):t,i=new e;if(i._version=r.meta?.version||1,i._createdAt=r.meta?.created?new Date(r.meta.created):new Date,i._updatedAt=r.meta?.updated?new Date(r.meta.updated):new Date,r.entities)for(const[e,t]of Object.entries(r.entities))i._entities.set(e,Entity.fromJSON(t));if(r.concepts)for(const[e,t]of Object.entries(r.concepts))i._concepts.set(e,Concept.fromJSON(t));if(r.connections&&(i._connections=r.connections.map(e=>Connection.fromJSON(e))),r.sources)for(const[e,t]of Object.entries(r.sources))i._sources.set(e,SourceRecord.fromJSON(t));return i}mergeExtraction(e,t,r,i,s){for(const r of e.entities)this.addOrMergeEntity(r.name,r.type,r.aliases||[],r.facts||[],t);for(const r of e.concepts)this.addOrMergeConcept(r.name,r.definition||"",r.related||[],r.aliases||[],t);for(const r of e.connections)this.addConnection(r.from,r.to,r.type,r.description||"",t);const n=new SourceRecord(t,e.sourceSummary,new Date,r,s,i);this.markSource(n)}async ingestFromSource(e,t,r){const i=Date.now();try{const s=await r.fileSystem.stat(e),n=r.crypto.hash(t,"sha256");if(!this.needsExtraction(e,s.mtimeMs,n))return{success:!0,extractedEntities:0,extractedConcepts:0,extractedConnections:0,timeMs:Date.now()-i,error:"Already processed (same content hash)"};const a=this.exportVocabulary(),o=this.buildExtractionPrompt(a,e,t,r.outputLanguage||"English"),l={model:r.model,temperature:r.temperature??.1,maxTokens:r.maxTokens??32768,systemMessage:"You are a knowledge extraction system. Output ONLY valid JSON, no explanations, no thinking process, no commentary."};let c;if(r.onIngestProgress){let e="",t=0;const i=e=>Math.max(1,Math.ceil(e.length/3));for await(const s of r.llmProvider.complete(o,l))s.done?s.usage&&r.onIngestTokenUsage&&r.onIngestTokenUsage(s.usage):(e+=s.text,t+=i(s.text),r.onIngestProgress(t));c=e.trim()}else c=await r.llmProvider.completeSync(o,l,void 0,r.onIngestTokenUsage);const h=function(e){let t=e.trim();t=t.replace(/```json\s*/g,""),t=t.replace(/```\s*/g,"");const r=[];let i=0;for(;i<t.length;){const e=t.indexOf("{",i);if(-1===e)break;let s=0,n=-1,a=!1,o=!1;for(let r=e;r<t.length;r++){const e=t[r];if(o)o=!1;else if("\\"!==e)if('"'!==e){if(!a&&("{"===e&&s++,"}"===e&&(s--,0===s))){n=r;break}}else a=!a;else o=!0}if(!(n>e))break;{const s=t.substring(e,n+1);r.push(s),i=n+1}if(r.length>=5)break}for(let e=0;e<r.length;e++){const t=r[e];try{const e=JSON.parse(t);if(!e||"object"!=typeof e)continue;const r=e.source_summary||e.summary||"";if("..."===r||"Brief summary"===r||r.includes("..."))continue;const i={source_summary:cleanString(r),entities:cleanEntities(e.entities||[]),concepts:cleanConcepts(e.concepts||[]),connections:cleanConnections(e.connections||[])};if(0===i.entities.length&&0===i.concepts.length)continue;return ExtractionResult.fromJSON(i)}catch(e){continue}}return null}(c);return h?(this.mergeExtraction(h,e,s.mtimeMs,n,"user-note"),this._operationLog.addIngest({sourcePath:e,entities:h.entities.length,concepts:h.concepts.length,connections:h.connections.length}),{success:!0,extractedEntities:h.entities.length,extractedConcepts:h.concepts.length,extractedConnections:h.connections.length,timeMs:Date.now()-i}):{success:!1,extractedEntities:0,extractedConcepts:0,extractedConnections:0,timeMs:Date.now()-i,error:"Failed to parse extraction result"}}catch(e){return{success:!1,extractedEntities:0,extractedConcepts:0,extractedConnections:0,timeMs:Date.now()-i,error:e.message||"Unknown error"}}}buildExtractionPrompt(e,t,r,i){return`You are analyzing a knowledge source to extract structured information.\n\nEXISTING VOCABULARY (merge with these if applicable):\n${e}\n\nSOURCE: ${t}\nCONTENT:\n${r}\n\nExtract the following in ${i}:\n1. ENTITIES: People, places, organizations, tools, etc.\n2. CONCEPTS: Abstract ideas, methodologies, principles.\n3. CONNECTIONS: Relationships between entities and concepts.\n\nOutput ONLY valid JSON in this exact format:\n{\n "entities": [{"name": "...", "type": "...", "aliases": [...], "facts": [...]}],\n "concepts": [{"name": "...", "definition": "...", "related": [...], "aliases": [...]}],\n "connections": [{"from": "...", "to": "...", "type": "...", "description": "..."}],\n "sourceSummary": "..."\n}`}retrieve(e,t={}){const r=t.maxEntities??12,i=t.maxConcepts??8,s=[2,.5,1],n=Retrieval.extractQueryTerms(e),a=[Retrieval.rankByKeyword(this,n),Retrieval.rankByPath(this,n)],o=[s[0],s[1]];if(t.embeddingIndex&&t.queryEmbedding){const e=Retrieval.rankByEmbedding(t.embeddingIndex,t.queryEmbedding);a.push(e),o.push(s[2])}const l=Retrieval.rrfFuse(a,o,60).map(e=>({id:e.id,score:e.score*Retrieval.qualityMultiplier(e.id,this)})).sort((e,t)=>t.score-e.score),c=[],h=[];for(const e of l)if(e.id.startsWith("concept:")){if(h.length>=i)continue;const t=e.id.slice(8),r=this._concepts.get(t);r&&h.push(r)}else{if(c.length>=r)continue;const t=this._entities.get(e.id);t&&c.push(t)}const u=new Set(c.map(e=>e.id.value)),g=this._connections.filter(e=>u.has(e.from)||u.has(e.to)),d=new Set;for(const e of c)for(const t of e.sources)d.add(t);for(const e of h)for(const t of e.sources)d.add(t);return{question:e,queryType:"entity_lookup",entities:c,concepts:h,connections:g,sources:Array.from(this._sources.values()).filter(e=>d.has(e.path))}}lint(){const e=[],t=new Set;for(const e of this._connections)t.add(e.from),t.add(e.to);for(const r of this._entities.values())t.has(r.id.value)||e.push({severity:"info",type:"orphan-entity",message:`Entity "${r.name}" has no connections`,location:`entity/${r.id.value}`,suggestion:"Consider adding relationships to other entities or concepts"});for(const t of this._entities.values())0===t.facts.length&&e.push({severity:"warning",type:"empty-entity",message:`Entity "${t.name}" has no facts`,location:`entity/${t.id.value}`,suggestion:"Add descriptive facts about this entity"});for(const t of this._concepts.values())t.definition&&0!==t.definition.trim().length||e.push({severity:"warning",type:"missing-definition",message:`Concept "${t.name}" lacks a definition`,location:`concept/${t.id.value}`,suggestion:"Add a clear definition for this concept"});const r=new Set;for(const e of this._entities.values())r.add(e.id.value);for(const e of this._concepts.values())r.add(e.id.value);for(const t of this._connections)r.has(t.from)||e.push({severity:"error",type:"broken-connection",message:`Connection references non-existent entity: "${t.from}"`,suggestion:"Remove this connection or create the missing entity"}),r.has(t.to)||e.push({severity:"error",type:"broken-connection",message:`Connection references non-existent entity: "${t.to}"`,suggestion:"Remove this connection or create the missing entity"});for(const t of this._entities.values())1===t.sources.length&&t.facts.length<3&&e.push({severity:"info",type:"single-source",message:`Entity "${t.name}" has only one source and few facts`,location:`entity/${t.id.value}`,suggestion:"Consider gathering more information from additional sources"});return e}async query(e,t){const r=t.maxResults||10;let i;if(this.hasEmbeddingIndex()&&t.embeddingProvider)try{const r=t.embeddingModel||t.model;i=await t.embeddingProvider.generateEmbedding(e,r,t.onEmbeddingUsage)}catch(e){console.warn("Failed to generate query embedding, falling back to keyword search",e)}const s={maxEntities:r,maxConcepts:r};this._embeddingIndex&&(s.embeddingIndex=this._embeddingIndex.getReadOnlyIndex()),i&&(s.queryEmbedding=i);const n=this.retrieve(e,s);return{entities:n.entities.map((e,t)=>({id:e.id.value,name:e.name,type:e.type.value,relevance:1-.05*t})),concepts:n.concepts.map((e,t)=>({name:e.name,definition:e.definition,relevance:1-.05*t})),connections:n.connections.map(e=>({from:e.from,to:e.to,type:e.type.value,description:e.description}))}}async generateWikiPages(e){const t=new Map,r=new ContentAnnotator;for(const e of this._entities.values()){const i=this.renderEntityPage(e,r),s=this.sanitizeFilename(e.name);t.set(`entities/${s}.md`,i)}for(const e of this._concepts.values()){const i=this.renderConceptPage(e,r),s=this.sanitizeFilename(e.name);t.set(`concepts/${s}.md`,i)}for(const i of this._sources.values()){const s=await this.renderSourcePage(i,r,e.pathService,e.fileSystem),n=this.getSourceFilename(i.path,e.pathService);t.set(`sources/${n}`,s)}t.set("index.md",this.generateIndex()),t.set("GLOSSARY.md",this.generateGlossary()),this._operationLog.count>0&&t.set("log.md",this._operationLog.toMarkdown()),await e.wikiPageRepo.writePages(t)}renderEntityPage(e,t){let r=`---\ntitle: ${e.name}\ntype: entity\ncategory: ${e.type.value}\n---\n\n`;r+=`# ${e.name}\n\n`,r+=`**Type**: ${e.type.value}\n\n`,e.aliases&&e.aliases.length>0&&(r+=`**Aliases**: ${e.aliases.join(", ")}\n\n`),r+="## Facts\n\n";for(const i of e.facts)r+=`- ${t.annotate(i,this.getAllEntities(),this.getAllConcepts())}\n`;const i=this.getConnectionsByEntity(e.id);if(i.length>0){r+="\n## Connections\n\n";for(const e of i){const t=this._entities.get(e.from),i=this._entities.get(e.to)||this._concepts.get(e.to);t&&i&&(r+=`- [[${t.name}]] ${e.type.value} [[${i.name}]]: ${e.description}\n`)}}r+="\n## Sources\n\n";for(const t of e.sources)this._sources.get(t)&&(r+=`- [[${this.sanitizeFilename(t)}]]\n`);return r}renderConceptPage(e,t){let r=`---\ntitle: ${e.name}\ntype: concept\n---\n\n`;if(r+=`# ${e.name}\n\n`,e.aliases&&e.aliases.size>0&&(r+=`**Aliases**: ${Array.from(e.aliases).join(", ")}\n\n`),r+="## Definition\n\n",r+=`${t.annotate(e.definition,this.getAllEntities(),this.getAllConcepts())}\n\n`,e.related&&e.related.length>0){r+="## Related Concepts\n\n";for(const t of e.related)r+=`- [[${t}]]\n`;r+="\n"}r+="## Sources\n\n";for(const t of e.sources)this._sources.get(t)&&(r+=`- [[${this.sanitizeFilename(t)}]]\n`);return r}async renderSourcePage(e,t,r,i){let s=`---\ntitle: ${r.basename(e.path)}\ntype: source\npath: ${e.path}\ndate: ${e.date.toISOString()}\n---\n\n`;s+=`# ${r.basename(e.path)}\n\n`,s+=`**Path**: \`${e.path}\`\n\n`,s+=`**Summary**: ${e.summary}\n\n`;const n=this.getEntitiesBySource(e.path);if(n.length>0){s+="## Entities\n\n";for(const e of n)s+=`- [[${e.name}]] (${e.type.value})\n`;s+="\n"}const a=this.getConceptsBySource(e.path);if(a.length>0){s+="## Concepts\n\n";for(const e of a)s+=`- [[${e.name}]]\n`;s+="\n"}s+="## Original Content\n\n";try{const r=await i.readFile(e.path,"utf-8"),n=this.getAllEntities(),a=this.getAllConcepts();s+=`${t.annotate(r,n,a)}\n\n`}catch(t){s+=`*Could not read original content from \`${e.path}\`: ${t.message}*\n\n`}return s}generateIndex(){let e="---\ntitle: Knowledge Base Index\n---\n\n";e+="# Knowledge Base\n\n",e+=`**Last Updated**: ${this._updatedAt.toISOString()}\n\n`,e+="## Statistics\n\n";const t=this.getStats();if(e+=`- **Entities**: ${t.entities}\n`,e+=`- **Concepts**: ${t.concepts}\n`,e+=`- **Connections**: ${t.connections}\n`,e+=`- **Sources**: ${t.sources}\n\n`,this._entities.size>0){e+="## Entities\n\n";const t=new Map;for(const e of this._entities.values()){const r=e.type.value;t.has(r)||t.set(r,[]),t.get(r).push(e)}const r=Array.from(t.keys()).sort();for(const i of r){const s=t.get(i).sort((e,t)=>e.name.localeCompare(t.name));r.length>1&&"other"!==i&&(e+=`### ${i.charAt(0).toUpperCase()+i.slice(1)}\n\n`);for(const t of s){const r=t.facts.length>0?t.facts[0].substring(0,80)+(t.facts[0].length>80?"...":""):t.type.value,i=t.sources.length;e+=`- [[${t.name}]] - ${r} (${i} source${1!==i?"s":""})\n`}e+="\n"}}if(this._concepts.size>0){e+="## Concepts\n\n";const t=Array.from(this._concepts.values()).sort((e,t)=>e.name.localeCompare(t.name));for(const r of t){const t=r.definition.split(/[.!?]\s/)[0],i=t.length>100?t.substring(0,100)+"...":t,s=r.sources.length;e+=`- [[${r.name}]] - ${i} (${s} source${1!==s?"s":""})\n`}e+="\n"}if(this._sources.size>0){e+="## Sources\n\n";const t=Array.from(this._sources.values()).sort((e,t)=>t.date.getTime()-e.date.getTime());for(const r of t){const t=this.sanitizeFilename(r.path),i=r.date.toISOString().split("T")[0],s=this.getEntitiesBySource(r.path).length,n=this.getConceptsBySource(r.path).length,a=r.summary.split(/[.!?]\s/)[0];e+=`- [[${t}]] - ${a.length>80?a.substring(0,80)+"...":a} (${i}, ${s} entities, ${n} concepts)\n`}e+="\n"}return e+="## Quick Links\n\n",e+="- [[GLOSSARY]]\n",this._operationLog.count>0&&(e+="- [[log]]\n"),e}generateGlossary(){let e="---\ntitle: Glossary\n---\n\n";e+="# Glossary\n\n",e+="## Entities\n\n";const t=Array.from(this._entities.values()).sort((e,t)=>e.name.localeCompare(t.name));for(const r of t)e+=`- [[${r.name}]] - ${r.type.value}\n`;e+="\n## Concepts\n\n";const r=Array.from(this._concepts.values()).sort((e,t)=>e.name.localeCompare(t.name));for(const t of r)e+=`- [[${t.name}]]\n`;return e}sanitizeFilename(e){return e.toLowerCase().replace(/[^a-z0-9-]/g,"-").replace(/-+/g,"-").replace(/^-|-$/g,"")}getSourceFilename(e,t){const r=t.basename(e,".md"),i=t.dirname(e).split(t.join("/")).filter(e=>e&&"."!==e);if(i.length>0){const e=i[i.length-1];return`${this.sanitizeFilename(e)}-${this.sanitizeFilename(r)}.md`}return`${this.sanitizeFilename(r)}.md`}async buildEmbeddingIndex(e){const{embeddingProvider:t,model:r,cachePath:i,fileSystem:s,onEmbeddingUsage:n}=e;if(!this._embeddingIndex&&await s.exists(i))try{const e=await s.readFile(i,"utf-8"),t=JSON.parse(e);this._embeddingIndex=EmbeddingIndex.fromJSON(i,t)}catch(e){console.warn("Failed to load embedding cache, will rebuild from scratch",e)}this._embeddingIndex||(this._embeddingIndex=new EmbeddingIndex(i));const a=this.getAllEntities(),o=this.getAllConcepts();for(const e of a)if(!this._embeddingIndex.has(e.id.value)){const i=`${e.name}: ${e.facts.join(". ")}`;try{const s=await t.generateEmbedding(i,r,n);this._embeddingIndex.set(e.id.value,s)}catch(t){throw console.error(`[kb] generateEmbedding FAILED for entity "${e.name}": ${t.message}`),t}}for(const e of o){const i=`concept:${e.id.value}`;if(!this._embeddingIndex.has(i)){const s=`${e.name}: ${e.definition}`;try{const e=await t.generateEmbedding(s,r,n);this._embeddingIndex.set(i,e)}catch(t){throw console.error(`[kb] generateEmbedding FAILED for concept "${e.name}": ${t.message}`),t}}}}async saveEmbeddingIndex(e,t){if(!this._embeddingIndex||!this._embeddingIndex.isDirtyState())return;const r=this._embeddingIndex.getCachePath(),i=t.dirname(r);await e.mkdir(i,{recursive:!0}),await e.writeFile(r,JSON.stringify(this._embeddingIndex.toJSON(),null,2),"utf-8"),this._embeddingIndex.markClean()}getEmbeddingIndex(){return this._embeddingIndex}hasEmbeddingIndex(){return null!==this._embeddingIndex&&this._embeddingIndex.size()>0}buildQueryContext(e){let t="";if(e.entities.length>0){t+="ENTITIES:\n";for(const r of e.entities)t+=`- ${r.name} (${r.type.value}): ${r.facts.join(". ")}\n`;t+="\n"}if(e.concepts.length>0){t+="CONCEPTS:\n";for(const r of e.concepts)t+=`- ${r.name}: ${r.definition}\n`;t+="\n"}if(e.connections.length>0){t+="CONNECTIONS:\n";for(const r of e.connections)t+=`- ${r.from} ${r.type.value} ${r.to}\n`;t+="\n"}return t}buildQueryPrompt(e,t){return`You are answering a question based on the following knowledge base context.\n\nCONTEXT:\n${t}\n\nQUESTION:\n${e}\n\nPlease provide a comprehensive answer based on the context above. If the context doesn't contain enough information, say so.`}async*queryStream(e,t){const r=t.maxResults||10;let i;if(this.hasEmbeddingIndex()&&t.embeddingProvider)try{const r=t.embeddingModel||t.model;i=await t.embeddingProvider.generateEmbedding(e,r,t.onEmbeddingUsage)}catch(e){console.warn("Failed to generate query embedding",e)}const s={maxEntities:r,maxConcepts:r};this._embeddingIndex&&(s.embeddingIndex=this._embeddingIndex.getReadOnlyIndex()),i&&(s.queryEmbedding=i);const n=this.retrieve(e,s),a=this.buildQueryContext(n),o=this.buildQueryPrompt(e,a);for await(const e of t.llmProvider.complete(o,{model:t.model,temperature:t.temperature??.7,maxTokens:8192,systemMessage:"You are a helpful assistant answering questions based on the provided knowledge base."}))e.done?e.usage&&t.onTokenUsage&&t.onTokenUsage(e.usage):e.text&&(yield e.text)}}}}),init_conversation=__esm({"internal/domain/wiki/entity/conversation.ts"(){Conversation=class e{id;query;answer;metadata;constructor(e,t,r,i){this.id=e,this.query=t,this.answer=r,this.metadata=i}static create(t,r,i){const s=new Date,n=e.generateId(t,s);return new e(n,t,r,{query:t,timestamp:s,...i})}static generateId(t,r){return`${e.formatDate(r)}-${e.slugify(t)}`}formatAsMarkdown(){return this.buildFrontmatter()+this.buildBody()+this.buildFooter()}getFilename(){return`${this.id}.md`}getId(){return this.id}getQuery(){return this.query}getAnswer(){return this.answer}getMetadata(){return{...this.metadata}}getTimestamp(){return this.metadata.timestamp}getSources(){return[...this.metadata.sources]}buildFrontmatter(){return["---","type: query-answer",`query: "${this.escapeYaml(this.query)}"`,`timestamp: ${this.metadata.timestamp.toISOString()}`,"retrieval:",` entities: ${this.metadata.retrieval.entityCount}`,` concepts: ${this.metadata.retrieval.conceptCount}`,` total: ${this.metadata.retrieval.totalResults}`,"sources:",...this.metadata.sources.map(e=>` - ${e}`),"---",""].join("\n")}buildBody(){return[`# ${this.query}`,"",`> 📅 Generated on ${this.formatDateTime(this.metadata.timestamp)}`,`> 🔍 Based on ${this.metadata.retrieval.totalResults} results (${this.metadata.retrieval.entityCount} entities, ${this.metadata.retrieval.conceptCount} concepts)`,"","## Answer","",this.answer,""].join("\n")}buildFooter(){return["## Sources","",...this.metadata.sources.map((e,t)=>`${t+1}. \`${e}\``),"","---","","*This document was automatically generated from a query. It can be re-ingested to extract new entities and concepts.*"].join("\n")}static formatDate(e){return`${e.getFullYear()}-${String(e.getMonth()+1).padStart(2,"0")}-${String(e.getDate()).padStart(2,"0")}`}formatDateTime(e){return e.toLocaleString("en-US",{year:"numeric",month:"long",day:"numeric",hour:"2-digit",minute:"2-digit"})}static slugify(e){return e.toLowerCase().replace(/[^a-z0-9\s-]/g,"").replace(/\s+/g,"-").replace(/-+/g,"-").slice(0,50).replace(/^-+|-+$/g,"")}escapeYaml(e){return e.replace(/"/g,'\\"')}toJSON(){return{id:this.id,query:this.query,answer:this.answer,metadata:this.metadata}}static fromJSON(t){return new e(t.id,t.query,t.answer,{...t.metadata,timestamp:new Date(t.metadata.timestamp)})}}}}),init_wiki_factory=__esm({"internal/domain/wiki/factory/wiki-factory.ts"(){init_knowledge_base(),WikiFactory=class{kbRepo;wikiPageRepo;constructor(e){this.kbRepo=e.kbRepo,this.wikiPageRepo=e.wikiPageRepo}create(){return new KnowledgeBase}async load(){return await this.kbRepo.load()}async save(e){await this.kbRepo.save(e)}getWikiPageRepository(){return this.wikiPageRepo}}}}),init_kb_repository_interface=__esm({"internal/domain/wiki/repository/kb-repository.interface.ts"(){}}),init_wiki_page_repository_interface=__esm({"internal/domain/wiki/repository/wiki-page-repository.interface.ts"(){}}),init_conversation_repository_interface=__esm({"internal/domain/wiki/repository/conversation-repository.interface.ts"(){}}),init_llm_provider=__esm({"internal/domain/wiki/repository/llm-provider.ts"(){}}),init_llm_http_client=__esm({"internal/domain/wiki/repository/llm-http-client.ts"(){}}),init_embedding_provider=__esm({"internal/domain/wiki/repository/embedding-provider.ts"(){}}),init_file_system2=__esm({"internal/domain/wiki/repository/file-system.ts"(){}}),init_path_service=__esm({"internal/domain/wiki/repository/path-service.ts"(){}}),init_crypto_service=__esm({"internal/domain/wiki/repository/crypto-service.ts"(){}}),init_repository2=__esm({"internal/domain/wiki/repository/index.ts"(){init_kb_repository_interface(),init_wiki_page_repository_interface(),init_conversation_repository_interface(),init_llm_provider(),init_llm_http_client(),init_embedding_provider(),init_file_system2(),init_path_service(),init_crypto_service()}}),init_wiki=__esm({"internal/domain/wiki/index.ts"(){init_entity_id(),init_entity_type(),init_connection_type(),init_source_record(),init_extraction_result(),init_extraction_parser(),init_wiki_config(),init_retrieval(),init_content_annotator(),init_wiki_page_renderer(),init_wiki_index_generator(),init_token_usage(),init_pricing(),init_entity2(),init_concept(),init_connection(),init_knowledge_base(),init_conversation(),init_embedding_index(),init_wiki_factory(),init_repository2()}}),init_node_kb_repository=__esm({"internal/infrastructure/node/node-kb-repository.ts"(){init_wiki(),NodeKBRepository=class{constructor(e,t,r){this.filePath=e,this.fileSystem=t,this.pathService=r}async load(){if(!await this.fileSystem.exists(this.filePath))return null;try{const e=await this.fileSystem.readFile(this.filePath,"utf-8");return KnowledgeBase.fromJSON(e)}catch(e){return console.error(`Failed to load KB from ${this.filePath}:`,e),null}}async exists(){return await this.fileSystem.exists(this.filePath)}async save(e){const t=this.pathService.dirname(this.filePath);await this.fileSystem.exists(t)||await this.fileSystem.mkdir(t,{recursive:!0});const r=JSON.stringify(e.toJSON(),null,2);await this.fileSystem.writeFile(this.filePath,r,"utf-8")}async getLastModified(){return await this.fileSystem.exists(this.filePath)?(await this.fileSystem.stat(this.filePath)).mtimeMs:0}async getSize(){return await this.fileSystem.exists(this.filePath)?(await this.fileSystem.stat(this.filePath),0):0}}}}),init_node_wiki_page_repository=__esm({"internal/infrastructure/node/node-wiki-page-repository.ts"(){NodeWikiPageRepository=class{constructor(e,t,r){this.baseDir=e,this.fileSystem=t,this.pathService=r,this.wikiDir=e}wikiDir;async writePage(e,t){const r=this.pathService.join(this.wikiDir,e),i=this.pathService.dirname(r);await this.fileSystem.exists(i)||await this.fileSystem.mkdir(i,{recursive:!0}),await this.fileSystem.writeFile(r,t,"utf-8")}async deletePage(e){const t=this.pathService.join(this.wikiDir,e);await this.fileSystem.exists(t)&&await this.fileSystem.unlink(t)}async writePages(e){for(const[t,r]of e.entries())await this.writePage(t,r)}async listPages(e){const t=this.pathService.join(this.wikiDir,e);return await this.fileSystem.exists(t)?(await this.listMarkdownFiles(t)).map(e=>this.pathService.relative(this.wikiDir,e)):[]}async appendToLog(e){const t=this.pathService.join(this.wikiDir,"log.md"),r=`\n## [${(new Date).toISOString()}] ${e}\n`;if(!await this.fileSystem.exists(t)){const e=this.pathService.dirname(t);await this.fileSystem.exists(e)||await this.fileSystem.mkdir(e,{recursive:!0}),await this.fileSystem.writeFile(t,"# Wiki Operation Log\n\n","utf-8")}const i=await this.fileSystem.readFile(t,"utf-8");await this.fileSystem.writeFile(t,i+r,"utf-8")}async updateIndex(e){await this.writePage("index.md",e)}async updateGlossary(e){await this.writePage("GLOSSARY.md",e)}async exists(e){const t=this.pathService.join(this.wikiDir,e);return await this.fileSystem.exists(t)}async listMarkdownFiles(e){const t=[];try{const r=await this.fileSystem.readdir(e);for(const i of r){const r=this.pathService.join(e,i);if((await this.fileSystem.stat(r)).isDirectory()){const e=await this.listMarkdownFiles(r);t.push(...e)}else i.endsWith(".md")&&t.push(r)}}catch(t){console.warn(`Failed to list files in ${e}:`,t)}return t}}}}),init_node=__esm({"internal/infrastructure/node/index.ts"(){init_node_file_system2(),init_node_path_service(),init_node_crypto_service(),init_node_conversation_repository(),init_node_kb_repository(),init_node_wiki_page_repository()}}),init_infrastructure=__esm({"internal/infrastructure/index.ts"(){init_node_workspace_repository(),init_node_snapshot_repository(),init_node_file_system(),init_node_manifest_repository(),init_node_http_client(),init_netlify_http_client(),init_llm(),init_embedding(),init_node()}}),init_identity3=__esm({"internal/application/identity.ts"(){init_server_config(),init_log(),log84=getDomainLogger("identity-app",{component:"application"}),IdentityAppService=class{userFactory;currentUser=null;cachedServerConfig=null;constructor(e){this.userFactory=e.userFactory}async initialize(){try{this.currentUser=await this.userFactory.load(),this.currentUser?this.cachedServerConfig=this.currentUser.getServerConfig():log84.debug("No existing user session")}catch(e){log84.error("Failed to initialize identity service",e)}}async login(e,t){const r=await this.userFactory.login(e,t,this.cachedServerConfig||void 0);return this.currentUser=r,this.cachedServerConfig=r.getServerConfig(),r}async register(e,t){const r=await this.userFactory.register(e,t,this.cachedServerConfig||void 0);return this.currentUser=r,this.cachedServerConfig=r.getServerConfig(),r}async logout(){await this.userFactory.logout(),this.currentUser=null}getCurrentUser(){return this.currentUser}isAuthenticated(){return this.currentUser?.isAuthenticated()||!1}getToken(){return this.currentUser?.getToken()?.getValue()||null}getStatus(){return this.currentUser?this.currentUser.getStatus():{isAuthenticated:!1,email:"",serverUrl:this.getServerConfig().getApiUrl(),tokenExpired:!0,hasToken:!1,hasLicense:!1,license:void 0,licenseValid:!1,isTrial:!1,licensePlan:void 0,licenseExpires:void 0,licenseDaysRemaining:void 0,hasSyncConfig:!1,syncConfig:void 0}}getServerConfig(){return this.currentUser?this.currentUser.getServerConfig():this.cachedServerConfig||ServerConfig.createDefault()}async updateServerConfig(e){this.currentUser||(this.currentUser=this.userFactory.createAnonymous()),await this.userFactory.updateServerConfig(this.currentUser,e),this.cachedServerConfig=this.currentUser.getServerConfig()}async requestTrial(e){return this.userFactory.requestTrialLicense(e,this.cachedServerConfig||void 0)}async loginWithLicense(e){const t=await this.userFactory.loginWithLicense(e,this.cachedServerConfig||void 0);return this.currentUser=t,this.cachedServerConfig=t.getServerConfig(),t}async activateLicense(e,t){if(!this.currentUser)throw new Error("User must be logged in to activate license");const r=await this.userFactory.activateLicense(this.currentUser,e,t);return this.currentUser=r,r}async requestAndActivateTrial(e){const t=await this.userFactory.requestAndActivateTrial(e,this.cachedServerConfig||void 0);return this.currentUser=t,this.cachedServerConfig=t.getServerConfig(),t}getLicense(){return this.currentUser?.getLicense()||null}hasValidLicense(){return this.currentUser?.hasValidLicense()||!1}isTrialAccount(){return this.currentUser?.isTrialAccount()||!1}getLicenseDisplay(){const e=this.getLicense();return e?{key:e.getMaskedKey(),plan:e.getFormattedPlan(),expires:e.getFormattedExpiresAt(),daysRemaining:e.getDaysRemaining(),isValid:e.isValid(),isExpired:e.isExpired(),isTrial:e.isTrial(),features:e.getFeatures()}:null}async refreshTokenIfNeeded(){if(!this.currentUser)return log84.debug("No current user, cannot refresh token"),!1;const e=this.currentUser.getToken(),t=await this.userFactory.refreshTokenIfNeeded(this.currentUser),r=t.getToken(),i=e?.getValue()!==r?.getValue();return i&&(this.currentUser=t,log84.info("Token was refreshed")),i}async requestWithAutoRefresh(e){if(!this.currentUser)throw new Error("User must be logged in to make authenticated requests");const t=await this.userFactory.requestWithAutoRefresh(this.currentUser,e),r=await this.userFactory.load();return r&&(this.currentUser=r),t}async getLicenseUsage(){if(!this.currentUser)throw new Error("User must be logged in to get license usage");return this.userFactory.getLicenseUsage(this.currentUser)}async getLicenseInfo(e){if(!this.currentUser)throw new Error("User must be logged in to get license info");return this.userFactory.getLicenseInfo(this.currentUser,e)}async resetUsage(){if(!this.currentUser)throw new Error("User must be logged in to reset usage");return this.userFactory.resetUsage(this.currentUser)}async getDomains(){if(!this.currentUser)throw new Error("User must be logged in to get domains");return this.userFactory.getDomains(this.currentUser)}async checkSubdomainAvailability(e){if(!this.currentUser)throw new Error("User must be logged in to check subdomain");return this.userFactory.checkSubdomainAvailability(this.currentUser,e)}async updateSubdomain(e){if(!this.currentUser)throw new Error("User must be logged in to update subdomain");return this.userFactory.updateSubdomain(this.currentUser,e)}async checkCustomDomain(e){if(!this.currentUser)throw new Error("User must be logged in to check custom domain");return this.userFactory.checkCustomDomain(this.currentUser,e)}async addCustomDomain(e){if(!this.currentUser)throw new Error("User must be logged in to add custom domain");return this.userFactory.addCustomDomain(this.currentUser,e)}async checkCustomDomainHttpsStatus(e){if(!this.currentUser)throw new Error("User must be logged in to check HTTPS status");return this.userFactory.checkCustomDomainHttpsStatus(this.currentUser,e)}}}}),container_exports={};function createWorkspaceFactory(e){const t={workspaceRepo:e?.workspaceRepo??new NodeWorkspaceRepository,projectRepo:e?.projectRepo??new NodeProjectRepository,snapshotRepo:e?.snapshotRepo??new NodeSnapshotRepository,fileSystemRepo:e?.fileSystemRepo??new NodeFileSystemRepository};return new WorkspaceFactory(t)}function createWorkspaceAppService(e){const t=createWorkspaceFactory(e);return new WorkspaceAppService({workspaceFactory:t})}async function createIdentityService(e){const t=new NodeHttpClient2,r=createWorkspaceAppService(),i=await r.loadWorkspace(e),s=r.createIdentityStorage(i),n=new UserFactory({httpClient:t,storageProvider:s});return new IdentityAppService({userFactory:n})}async function createIdentityServiceForObsidian(e,t){const r=createWorkspaceAppService(),i=await r.loadWorkspace(e),s=r.createIdentityStorage(i),n=new UserFactory({httpClient:t,storageProvider:s});return new IdentityAppService({userFactory:n})}function createPublishAppService(){const e=new NodeManifestRepository,t=new NetlifyHttpClient,r=new PublisherFactory(e,t),i=createWorkspaceAppService();return new PublishAppService(r,i)}__export(container_exports,{createIdentityService:()=>createIdentityService,createIdentityServiceForObsidian:()=>createIdentityServiceForObsidian,createPublishAppService:()=>createPublishAppService,createWorkspaceAppService:()=>createWorkspaceAppService,createWorkspaceFactory:()=>createWorkspaceFactory});var init_container=__esm({"internal/application/container.ts"(){init_workspace2(),init_workspace3(),init_identity2(),init_publish2(),init_publish(),init_infrastructure(),init_identity3(),init_infrastructure()}});init_ssg(),init_log(),init_log();import*as workerpool from"workerpool";init_log(),init_page_filter();var log58=getDomainLogger("application",{component:"worker-state"}),WorkerState=class{constructor(e,t){this.projDir=e,this.moduleDir=t}initialized=!1;async initialize(){if(this.initialized)return void log58.warn("Worker already initialized, skipping...");const e=performance.now();log58.info("🚀 Initializing worker environment...",{projDir:this.projDir,moduleDir:this.moduleDir}),this.initialized=!0;const t=performance.now()-e;log58.info(`✅ Worker environment initialized in ${t.toFixed(2)}ms`)}async processBatch(e){if(!this.initialized)throw new Error("Worker not initialized. Call initialize() first.");const t=performance.now(),r=[];log58.info(`📦 Processing batch: ${e.length} tasks`);try{i=e,pageFilter.setFilter(i),log58.debug(`Filter set for ${e.length} tasks`);const{generateStaticSite:s}=await Promise.resolve().then(()=>(init_ssg(),ssg_exports));await s(this.projDir,this.moduleDir),log58.debug("✅ Tasks processed (filtered)");const n=performance.now()-t,a={success:!0,processedCount:e.length,totalCount:e.length,duration:n,errors:r};return log58.info(`✅ Batch processed: ${e.length} tasks in ${n.toFixed(2)}ms`),a}catch(i){const s=`Batch processing failed: ${i instanceof Error?i.message:String(i)}`;log58.error(`❌ ${s}`),r.push(s);const n=performance.now()-t;return{success:!1,processedCount:0,totalCount:e.length,duration:n,errors:r}}finally{pageFilter.clearFilter()}var i}async cleanup(){log58.info("🧹 Cleaning up worker resources..."),this.initialized=!1}getStats(){return{initialized:this.initialized,projDir:this.projDir,moduleDir:this.moduleDir}}};init_log();var log59=getDomainLogger("application",{component:"worker-main"}),workerState=null;async function handleWorkerTask(e){try{switch(e.type){case"init":return await async function(e){return e.projDir&&e.moduleDir?(log59.info("🔧 Initializing worker..."),workerState=new WorkerState(e.projDir,e.moduleDir),await workerState.initialize(),{success:!0,data:{message:"Worker initialized successfully"}}):{success:!1,error:"Missing projDir or moduleDir for init task"}}(e);case"process-batch":return await async function(e){if(!workerState)return{success:!1,error:"Worker not initialized. Call init task first."};if(!e.pageTasks||0===e.pageTasks.length)return{success:!1,error:"Missing pageTasks for process-batch task"};const t=await workerState.processBatch(e.pageTasks);return{success:t.success,data:t,error:t.errors.length>0?t.errors.join("; "):void 0}}(e);case"stats":return await async function(){return workerState?{success:!0,data:workerState.getStats()}:{success:!1,error:"Worker not initialized"}}();case"cleanup":return await async function(){return workerState?(await workerState.cleanup(),workerState=null,{success:!0,data:{message:"Worker cleaned up successfully"}}):{success:!0,data:{message:"Worker already cleaned up"}}}();default:return{success:!1,error:`Unknown task type: ${e.type}`}}}catch(e){const t=e instanceof Error?e.message:String(e);return log59.error(`Worker task failed: ${t}`),{success:!1,error:t}}}import*as os from"os";import*as path28 from"path";var log60=getDomainLogger("application",{component:"pool-manager"}),WorkerPoolManager=class{pool=null;environment;workerCount;constructor(e={}){this.environment=this.detectEnvironment(),this.workerCount=e.workerCount||this.calculateOptimalWorkerCount(),log60.info("Worker pool manager created",{environment:this.environment,workerCount:this.workerCount})}detectEnvironment(){if("undefined"!=typeof Worker&&void 0!==globalThis.window)return log60.debug("Detected Web Worker support (browser/Electron environment)"),"browser";if("undefined"!=typeof process&&process.versions&&process.versions.node)try{return __require.resolve("worker_threads"),log60.debug("Detected Node.js Worker Threads support"),"node"}catch{return log60.debug("Node.js detected but worker_threads unavailable, falling back to browser mode"),"browser"}return log60.debug("Using browser mode as default"),"browser"}calculateOptimalWorkerCount(){if("node"===this.environment){const e=os.cpus().length;return Math.max(1,e-1)}{const e="undefined"!=typeof navigator&&navigator.hardwareConcurrency||4;return Math.max(2,Math.min(e-1,4))}}async initialize(){if(this.pool)return void log60.warn("Worker pool already initialized");const e=performance.now();log60.info(`🚀 Initializing ${this.environment} worker pool with ${this.workerCount} workers...`);try{"node"===this.environment?await this.initializeNodePool():await this.initializeBrowserPool();const t=performance.now()-e;log60.info(`✅ Worker pool initialized in ${t.toFixed(2)}ms`)}catch(t){const r=t instanceof Error?t.message:String(t);if("node"===this.environment){log60.warn(`❌ Node worker pool initialization failed: ${r}`),log60.warn("🔄 Attempting fallback to browser workers...");try{this.environment="browser",await this.initializeBrowserPool();const t=performance.now()-e;return void log60.info(`✅ Successfully initialized browser worker pool as fallback in ${t.toFixed(2)}ms`)}catch(e){const t=e instanceof Error?e.message:String(e);throw log60.error(`❌ Fallback to browser workers also failed: ${t}`),new Error(`Worker pool initialization failed. Node: ${r}, Browser: ${t}`)}}throw log60.error(`❌ Failed to initialize worker pool: ${r}`),t}}async initializeNodePool(){const e=path28.join(__dirname,"worker","worker-node.js");log60.debug(`Initializing Node.js worker pool with path: ${e}`),this.pool=workerpool.pool(e,{minWorkers:this.workerCount,maxWorkers:this.workerCount,workerType:"thread"}),log60.debug(`Node.js worker pool created with ${this.workerCount} workers`,{workerPath:e})}async initializeBrowserPool(){this.pool=workerpool.pool({minWorkers:this.workerCount,maxWorkers:this.workerCount,workerType:"web"}),this.pool.proxy().then(e=>{log60.debug(`Browser worker pool created with ${this.workerCount} workers`)})}async exec(e){if(!this.pool)throw new Error("Worker pool not initialized. Call initialize() first.");try{return"node"===this.environment?await this.pool.exec("processTask",[e]):await this.pool.exec(handleWorkerTask,[e])}catch(e){const t=e instanceof Error?e.message:String(e);return log60.error(`Worker task execution failed: ${t}`),{success:!1,error:t}}}getStats(){return this.pool?{environment:this.environment,workerCount:this.workerCount,poolStats:this.pool.stats()}:null}async terminate(){this.pool?(log60.info("🧹 Terminating worker pool..."),await this.pool.terminate(),this.pool=null,log60.info("✅ Worker pool terminated")):log60.warn("Worker pool already terminated")}};init_log();var log61=getDomainLogger("application",{component:"batch-task-queue"}),BatchTaskQueue=class{queue=[];currentIndex=0;totalBatches;constructor(e){this.queue=e,this.totalBatches=e.length,log61.info(`Task queue initialized with ${this.totalBatches} batches`)}nextBatch(){if(this.currentIndex>=this.queue.length)return null;const e=this.queue[this.currentIndex];return this.currentIndex++,e}getProgress(){const e=this.currentIndex,t=this.totalBatches;return{completed:e,total:t,percentage:0===t?100:Math.round(e/t*100)}}hasMore(){return this.currentIndex<this.queue.length}getRemainingCount(){return Math.max(0,this.queue.length-this.currentIndex)}};init_ssg();import*as os2 from"os";var log62=getDomainLogger("ssg",{component:"parallel"});async function runWorkerLoop(e,t,r,i,s,n){const a=[];for(;;){const o=t.nextBatch();if(!o){log62.debug(`Worker ${r} finished - no more tasks`);break}const l=t.getProgress();log62.info(`🔄 Worker ${r} processing batch ${l.completed}/${l.total} (${o.length} tasks)`);const c={type:"process-batch",pageTasks:o},h=await e.exec(c);if(h.success&&h.data){const e=h.data;a.push(e),s.count+=e.processedCount;const t=70+Math.floor(s.count/i*29);n?.({stage:"build",message:`Rendering pages (${s.count}/${i})...`,percentage:t,pageRender:{currentPage:s.count,totalPages:i}}),log62.info(`✅ Worker ${r} completed batch: ${e.processedCount} tasks in ${e.duration.toFixed(2)}ms`)}else log62.error(`❌ Worker ${r} failed: ${h.error}`),a.push({success:!1,processedCount:0,totalCount:o.length,duration:0,errors:[h.error||"Unknown error"]})}return a}async function processSSGParallel(e,t,r,i,s){const n=performance.now(),a=process.cwd();process.chdir(e);try{i?.({stage:"config",message:"Initializing parallel SSG...",percentage:5}),i?.({stage:"pages",message:"Collecting all page tasks...",percentage:10});const r=await collectAllPageTasks(e,t);if(0===r.length)return log62.warn("⚠️ No page tasks found to process"),i?.({stage:"completion",message:"No pages to process",percentage:100}),{totalPages:0,totalBatches:0,workerCount:0,batchSize:0,totalDuration:0,parallelSpeedup:0,pagesPerSecond:0};i?.({stage:"config",message:`Found ${r.length} pages, calculating optimal worker configuration...`,percentage:20});const s=os2.cpus().length,a=Math.max(2,Math.floor(.6*s)),o=function(e,t){const r=4*t,i=Math.ceil(e/r);return Math.max(5,Math.min(50,i))}(r.length,a);log62.info(`⚙️ Using ${a} workers with batch size ${o}`),i?.({stage:"config",message:`Creating worker pool with ${a} workers...`,percentage:30});const l=new WorkerPoolManager({workerCount:a});await l.initialize(),i?.({stage:"config",message:"Initializing workers...",percentage:50}),log62.info("🔧 Initializing workers...");const c=performance.now(),h=[];for(let r=0;r<a;r++){const r={type:"init",projDir:e,moduleDir:t};h.push(l.exec(r))}await Promise.all(h);const u=performance.now()-c;log62.info(`✅ All workers initialized in ${u.toFixed(2)}ms`),i?.({stage:"build",message:`Creating ${Math.ceil(r.length/o)} task batches...`,percentage:65});const g=function(e,t){const r=[];for(let i=0;i<e.length;i+=t)r.push(e.slice(i,i+t));return log62.info(`📦 Created ${r.length} batches (${t} tasks per batch)`),r}(r,o),d=new BatchTaskQueue(g);i?.({stage:"build",message:"Starting parallel page rendering...",percentage:70}),log62.info("🏃 Starting worker loops...");const p=performance.now(),m={count:0},f=[];for(let e=0;e<a;e++)f.push(runWorkerLoop(l,d,e,r.length,m,i));const y=await Promise.all(f),w=performance.now()-p,S=y.flat(),b=S.filter(e=>e.success).length,_=S.reduce((e,t)=>e+t.processedCount,0),k=S.reduce((e,t)=>e+t.errors.length,0);await l.terminate();const v=performance.now()-n,P=_/v*1e3,C=w/_*_/w;return i?.({stage:"completion",message:`Parallel SSG completed! Processed ${_} pages with ${a} workers`,percentage:100}),log62.info("✨ Parallel SSG completed!"),log62.info("📊 Statistics:",{totalTasks:r.length,processedTasks:_,successfulBatches:b,failedBatches:S.length-b,totalErrors:k,totalDuration:`${v.toFixed(2)}ms`,processingDuration:`${w.toFixed(2)}ms`,pagesPerSecond:P.toFixed(2),parallelSpeedup:`${C.toFixed(2)}x`}),{totalPages:r.length,totalBatches:g.length,workerCount:a,batchSize:o,totalDuration:v,parallelSpeedup:C,pagesPerSecond:P}}catch(e){const t=e instanceof Error?e.message:String(e);throw log62.error(`❌ Parallel SSG failed: ${t}`),e}finally{process.chdir(a)}}init_ssg(),init_log(),init_log();import*as chokidar from"chokidar";import*as path29 from"path";import*as fs2 from"fs";var log63=getDomainLogger("web",{component:"content-file-watcher"}),ContentFileWatcher=class{constructor(e){this.config=e,this.batchDelay=e.batchDelay||500,void 0!==e.isSingleFileMode?this.isSingleFileMode=e.isSingleFileMode:this.isSingleFileMode=this.detectSingleFileMode(e.contentDirs),this.isSingleFileMode&&log63.info("Single file mode detected",{contentDirs:e.contentDirs})}watcher=null;eventQueue=[];batchTimer=null;batchDelay;callbacks=[];isSingleFileMode=!1;detectSingleFileMode(e){return 0!==e.length&&e.every(e=>{try{return fs2.statSync(e).isFile()}catch{const t=path29.extname(e).toLowerCase();return".md"===t||".markdown"===t}})}async startWatching(){this.watcher&&await this.stopWatching(),this.watcher=chokidar.watch(this.config.contentDirs,{ignored:[/(^|[\/\\])\../,/\.tmp$/,/\.swp$/,/~$/,/\.DS_Store$/,...this.config.ignorePatterns||[]],persistent:!0,ignoreInitial:!0,followSymlinks:!0,awaitWriteFinish:{stabilityThreshold:100,pollInterval:50}}),this.watcher.on("add",e=>this.queueEvent(e,"created")).on("change",e=>this.queueEvent(e,"modified")).on("unlink",e=>this.queueEvent(e,"deleted")).on("error",e=>{log63.error("File watcher error:",e)})}onFileChange(e){this.callbacks.push(e)}queueEvent(e,t){let r=e;if(this.isSingleFileMode){const t=this.config.contentDirs.findIndex(t=>path29.normalize(e)===path29.normalize(t));if(-1===t)return;{const i=this.config.projContentDirs[t];r=path29.join(i,"index.md"),log63.debug("Single file event mapped",{original:e,mapped:r})}}else{const{projContentDirs:e,contentDirs:t}=this.config;for(let i=0;i<e.length;i++){const s=e[i];for(let e=0;e<t.length;e++){const i=t[e];if(s!==i&&r.startsWith(i)){r=s+r.slice(i.length);break}}}}const i=path29.normalize(r);if(!this.isRelevantFile(i))return;const s={filePath:i,eventType:t,timestamp:Date.now(),isMarkdown:this.isMarkdownFile(i),isImage:this.isImageFile(i)};this.eventQueue.push(s),this.scheduleBatch()}isRelevantFile(e){return this.isMarkdownFile(e)||this.isImageFile(e)}isMarkdownFile(e){const t=path29.extname(e).toLowerCase();return".md"===t||".markdown"===t}isImageFile(e){const t=path29.extname(e).toLowerCase();return[".jpg",".jpeg",".png",".gif",".svg",".webp",".bmp"].includes(t)}scheduleBatch(){this.batchTimer&&clearTimeout(this.batchTimer),this.batchTimer=setTimeout(async()=>{if(this.eventQueue.length>0){const e=this.deduplicateEvents(this.eventQueue);this.eventQueue=[];for(const t of this.callbacks)try{await t(e)}catch(e){log63.error("Error processing file change events:",e)}}},this.batchDelay)}deduplicateEvents(e){const t=new Map;for(const r of e){const e=t.get(r.filePath);(!e||r.timestamp>e.timestamp)&&t.set(r.filePath,r)}return Array.from(t.values())}async stopWatching(){this.batchTimer&&(clearTimeout(this.batchTimer),this.batchTimer=null),this.watcher&&(await this.watcher.close(),this.watcher=null),this.eventQueue=[],this.callbacks=[]}};init_log();import*as http3 from"http";import*as path30 from"path";import*as fs3 from"fs/promises";import{WebSocket,WebSocketServer}from"ws";var log64=getDomainLogger("web",{component:"livereload-server"}),FoundryLiveReloadServer=class{httpServer=null;wsServer=null;clients=new Set;running=!1;config;constructor(e){this.config={port:e.port||8091,host:e.host||"localhost",livereloadPort:e.livereloadPort||35729,enableLiveReload:!1!==e.enableLiveReload,publicDir:e.publicDir}}async start(){if(this.running)log64.warn("LiveReloadServer already running");else try{await this.startHttpServer(),this.config.enableLiveReload&&await this.startLiveReloadServer(),this.running=!0}catch(e){throw log64.error("Failed to start LiveReloadServer:",e),e}}async stop(){if(this.running)try{for(const e of this.clients)e.close();this.clients.clear(),this.wsServer&&(this.wsServer.close(),this.wsServer=null),this.httpServer&&(await new Promise(e=>{this.httpServer.close(()=>e())}),this.httpServer=null),this.running=!1}catch(e){log64.error("Error stopping LiveReloadServer:",e)}}notifyReload(e){if(!this.config.enableLiveReload||0===this.clients.size)return;const t={command:"reload",liveCSS:this.shouldLiveReloadCSS(e),liveImg:this.shouldLiveReloadImages(e)};if(e&&1===e.length){const r=e[0],i=path30.extname(r).toLowerCase();".css"===i?(t.path=r,t.liveCSS=!0):[".jpg",".jpeg",".png",".gif",".svg",".webp"].includes(i)&&(t.path=r,t.liveImg=!0)}const r=JSON.stringify(t);for(const e of this.clients)e.readyState===WebSocket.OPEN&&e.send(r)}getUrl(){return`http://${this.config.host}:${this.config.port}`}isServerRunning(){return this.running}async startHttpServer(){this.httpServer=http3.createServer(async(e,t)=>{try{await this.handleHttpRequest(e,t)}catch(e){log64.error("HTTP request error:",e),t.statusCode=500,t.end("Internal Server Error")}}),await new Promise((e,t)=>{this.httpServer.listen(this.config.port,this.config.host,()=>{e()}),this.httpServer.on("error",e=>{"EADDRINUSE"===e.code?(this.config.port++,this.config.port<8099?this.httpServer.listen(this.config.port,this.config.host):t(new Error("No available ports"))):t(e)})})}async startLiveReloadServer(){this.wsServer=new WebSocketServer({port:this.config.livereloadPort,host:this.config.host}),this.wsServer.on("connection",e=>{this.clients.add(e),e.send(JSON.stringify({command:"hello",protocols:["http://livereload.com/protocols/official-7"],serverName:"foundry-livereload"})),e.on("close",()=>{this.clients.delete(e)}),e.on("message",e=>{try{JSON.parse(e.toString())}catch(t){log64.error("Invalid LiveReload message:",e.toString())}})}),this.wsServer.on("error",e=>{log64.error("LiveReload WebSocket server error:",e)})}async handleHttpRequest(e,t){const r=e.url||"/";let i=this.resolveFilePath(r);try{if((await fs3.stat(i)).isDirectory()){const e=path30.join(i,"index.html");try{await fs3.stat(e),i=e}catch{return t.statusCode=404,void t.end("Not Found")}}let e=await fs3.readFile(i);const r=this.getContentType(i);if(t.setHeader("Content-Type",r),r.includes("text/html")&&this.config.enableLiveReload){const t=e.toString(),r=this.getLiveReloadScript(),i=t.replace(/<\/body>/i,`${r}\n</body>`);e=Buffer.from(i,"utf8")}t.setHeader("Cache-Control","no-cache, no-store, must-revalidate"),t.setHeader("Pragma","no-cache"),t.setHeader("Expires","0"),t.statusCode=200,t.end(e)}catch(e){if("ENOENT"!==e.code)throw e;t.statusCode=404,t.end("Not Found")}}resolveFilePath(e){const t=e.split("?")[0].split("#")[0];let r;try{r=decodeURIComponent(t)}catch(e){log64.warn("Failed to decode URL:",t,e),r=t}const i=path30.normalize(r).replace(/^(\.\.[\/\\])+/,""),s=i.startsWith("/")?i.slice(1):i,n=path30.join(this.config.publicDir,s);return"win32"===process.platform&&n.length>260&&log64.warn("Path too long for Windows filesystem:",n),"win32"===process.platform&&/[<>:"|?*\x00-\x1f]/.test(s)&&log64.warn("Path contains invalid characters for Windows:",s),n}getContentType(e){return{".html":"text/html; charset=utf-8",".css":"text/css; charset=utf-8",".js":"application/javascript; charset=utf-8",".json":"application/json; charset=utf-8",".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".svg":"image/svg+xml",".webp":"image/webp",".ico":"image/x-icon",".woff":"font/woff",".woff2":"font/woff2",".ttf":"font/ttf",".eot":"application/vnd.ms-fontobject",".xml":"application/xml; charset=utf-8",".txt":"text/plain; charset=utf-8"}[path30.extname(e).toLowerCase()]||"application/octet-stream"}getLiveReloadScript(){return`\n<script>\n(function() {\n 'use strict';\n \n var protocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:';\n var address = protocol + '//${this.config.host}:${this.config.livereloadPort}/livereload';\n var socket = new WebSocket(address);\n \n socket.onmessage = function(event) {\n var data = JSON.parse(event.data);\n \n if (data.command === 'reload') {\n if (data.liveCSS) {\n // 热更新 CSS\n reloadCSS();\n } else if (data.liveImg) {\n // 热更新图片\n reloadImages();\n } else {\n // 完整页面刷新\n window.location.reload();\n }\n }\n };\n \n socket.onopen = function() {\n console.log('LiveReload connected');\n };\n \n socket.onclose = function() {\n console.log('LiveReload disconnected');\n // 尝试重连\n setTimeout(function() {\n window.location.reload();\n }, 1000);\n };\n \n function reloadCSS() {\n var links = document.querySelectorAll('link[rel="stylesheet"]');\n for (var i = 0; i < links.length; i++) {\n var link = links[i];\n var href = link.href;\n if (href) {\n var url = new URL(href);\n url.searchParams.set('_t', Date.now().toString());\n link.href = url.toString();\n }\n }\n console.log('CSS reloaded');\n }\n \n function reloadImages() {\n var images = document.querySelectorAll('img');\n for (var i = 0; i < images.length; i++) {\n var img = images[i];\n var src = img.src;\n if (src) {\n var url = new URL(src);\n url.searchParams.set('_t', Date.now().toString());\n img.src = url.toString();\n }\n }\n console.log('Images reloaded');\n }\n})();\n<\/script>`}shouldLiveReloadCSS(e){return!!e&&e.some(e=>".css"===path30.extname(e).toLowerCase())}shouldLiveReloadImages(e){if(!e)return!1;const t=[".jpg",".jpeg",".png",".gif",".svg",".webp"];return e.some(e=>t.includes(path30.extname(e).toLowerCase()))}};init_log();import*as http4 from"http";import*as path31 from"path";import*as fs4 from"fs/promises";var log65=getDomainLogger("web",{component:"electron-livereload-server"}),ElectronLiveReloadServer=class{httpServer=null;running=!1;config;stateFilePath;constructor(e){this.config={port:e.port||8091,host:e.host||"localhost",livereloadPort:e.livereloadPort||35729,enableLiveReload:!1!==e.enableLiveReload,publicDir:e.publicDir},this.stateFilePath=path31.join(this.config.publicDir,".foundry-livereload-state.json")}async start(){if(this.running)log65.warn("ElectronLiveReloadServer already running");else try{await this.startHttpServer(),this.config.enableLiveReload&&await this.initStateFile(),this.running=!0,log65.info(`ElectronLiveReloadServer started at ${this.getUrl()}`)}catch(e){throw log65.error("Failed to start ElectronLiveReloadServer:",e),e}}async stop(){if(this.running)try{this.httpServer&&(await new Promise(e=>{this.httpServer.close(()=>e())}),this.httpServer=null);try{await fs4.unlink(this.stateFilePath)}catch(e){}this.running=!1,log65.info("ElectronLiveReloadServer stopped")}catch(e){log65.error("Error stopping ElectronLiveReloadServer:",e)}}notifyReload(e){if(!this.config.enableLiveReload)return;const t={timestamp:Date.now(),command:"reload",liveCSS:this.shouldLiveReloadCSS(e),liveImg:this.shouldLiveReloadImages(e),...e&&{changedFiles:e}};if(e&&1===e.length){const r=e[0],i=path31.extname(r).toLowerCase();(".css"===i||[".jpg",".jpeg",".png",".gif",".svg",".webp"].includes(i))&&(t.path=r)}this.writeStateFile(t).catch(e=>{log65.error("Failed to write state file:",e)})}getUrl(){return`http://${this.config.host}:${this.config.port}`}isServerRunning(){return this.running}async initStateFile(){const e={timestamp:Date.now(),command:"hello"};await this.writeStateFile(e)}async writeStateFile(e){try{await fs4.writeFile(this.stateFilePath,JSON.stringify(e),"utf8")}catch(e){log65.error("Failed to write LiveReload state file:",e)}}async startHttpServer(){this.httpServer=http4.createServer(async(e,t)=>{try{await this.handleHttpRequest(e,t)}catch(e){log65.error("HTTP request error:",e),t.statusCode=500,t.end("Internal Server Error")}}),await new Promise((e,t)=>{this.httpServer.listen(this.config.port,this.config.host,()=>{e()}),this.httpServer.on("error",e=>{"EADDRINUSE"===e.code?(this.config.port++,this.config.port<8099?this.httpServer.listen(this.config.port,this.config.host):t(new Error("No available ports"))):t(e)})})}async handleHttpRequest(e,t){const r=e.url||"/";if(r.startsWith("/.foundry-livereload-state.json"))try{const e=await fs4.readFile(this.stateFilePath,"utf8");return t.setHeader("Content-Type","application/json; charset=utf-8"),t.setHeader("Cache-Control","no-cache, no-store, must-revalidate"),t.setHeader("Pragma","no-cache"),t.setHeader("Expires","0"),t.statusCode=200,void t.end(e)}catch(e){return void("ENOENT"===e.code?(t.statusCode=404,t.end("State file not found")):(t.statusCode=500,t.end("Internal Server Error")))}let i=this.resolveFilePath(r);try{if((await fs4.stat(i)).isDirectory()){const e=path31.join(i,"index.html");try{await fs4.stat(e),i=e}catch{return t.statusCode=404,void t.end("Not Found")}}let e=await fs4.readFile(i);const r=this.getContentType(i);if(t.setHeader("Content-Type",r),r.includes("text/html")&&this.config.enableLiveReload){const t=e.toString(),r=this.getLiveReloadScript(),i=t.replace(/<\/body>/i,`${r}\n</body>`);e=Buffer.from(i,"utf8")}t.setHeader("Cache-Control","no-cache, no-store, must-revalidate"),t.setHeader("Pragma","no-cache"),t.setHeader("Expires","0"),t.statusCode=200,t.end(e)}catch(e){if("ENOENT"!==e.code)throw e;t.statusCode=404,t.end("Not Found")}}resolveFilePath(e){const t=e.split("?")[0].split("#")[0];let r;try{r=decodeURIComponent(t)}catch(e){log65.warn("Failed to decode URL:",t,e),r=t}const i=path31.normalize(r).replace(/^(\.\.[\/\\])+/,""),s=i.startsWith("/")?i.slice(1):i;return path31.join(this.config.publicDir,s)}getContentType(e){return{".html":"text/html; charset=utf-8",".css":"text/css; charset=utf-8",".js":"application/javascript; charset=utf-8",".json":"application/json; charset=utf-8",".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".svg":"image/svg+xml",".webp":"image/webp",".ico":"image/x-icon",".woff":"font/woff",".woff2":"font/woff2",".ttf":"font/ttf",".eot":"application/vnd.ms-fontobject",".xml":"application/xml; charset=utf-8",".txt":"text/plain; charset=utf-8"}[path31.extname(e).toLowerCase()]||"application/octet-stream"}getLiveReloadScript(){return"\n<script>\n(function() {\n 'use strict';\n \n var stateFilePath = '/.foundry-livereload-state.json';\n var storageKey = 'foundry-livereload-last-timestamp';\n var lastTimestamp = 0;\n var pollInterval = 500; // 500ms 轮询间隔\n \n // 从 localStorage 恢复上次的时间戳,避免页面刷新后重复触发\n try {\n var stored = localStorage.getItem(storageKey);\n if (stored) {\n lastTimestamp = parseInt(stored, 10) || 0;\n }\n } catch (error) {\n // localStorage 可能不可用,使用默认值\n console.warn('LiveReload: localStorage not available, may cause duplicate reloads');\n }\n \n function checkForReload() {\n fetch(stateFilePath + '?_t=' + Date.now(), { cache: 'no-cache' })\n .then(function(response) {\n if (!response.ok) {\n throw new Error('Failed to fetch state file');\n }\n return response.json();\n })\n .then(function(state) {\n if (state.timestamp > lastTimestamp) {\n // 更新时间戳并保存到 localStorage\n lastTimestamp = state.timestamp;\n try {\n localStorage.setItem(storageKey, lastTimestamp.toString());\n } catch (error) {\n // localStorage 写入失败,忽略\n }\n \n if (state.command === 'reload') {\n if (state.liveCSS) {\n // 热更新 CSS\n reloadCSS();\n } else if (state.liveImg) {\n // 热更新图片\n reloadImages();\n } else {\n // 完整页面刷新\n window.location.reload();\n }\n }\n }\n })\n .catch(function(error) {\n // 静默处理错误,避免控制台噪音\n });\n }\n \n function reloadCSS() {\n var links = document.querySelectorAll('link[rel=\"stylesheet\"]');\n for (var i = 0; i < links.length; i++) {\n var link = links[i];\n var href = link.href;\n if (href) {\n var url = new URL(href);\n url.searchParams.set('_t', Date.now().toString());\n link.href = url.toString();\n }\n }\n console.log('CSS reloaded');\n }\n \n function reloadImages() {\n var images = document.querySelectorAll('img');\n for (var i = 0; i < images.length; i++) {\n var img = images[i];\n var src = img.src;\n if (src) {\n var url = new URL(src);\n url.searchParams.set('_t', Date.now().toString());\n img.src = url.toString();\n }\n }\n console.log('Images reloaded');\n }\n \n // 开始轮询\n setInterval(checkForReload, pollInterval);\n \n // 初始检查\n checkForReload();\n})();\n<\/script>"}shouldLiveReloadCSS(e){return!!e&&e.some(e=>".css"===path31.extname(e).toLowerCase())}shouldLiveReloadImages(e){if(!e)return!1;const t=[".jpg",".jpeg",".png",".gif",".svg",".webp"];return e.some(e=>t.includes(path31.extname(e).toLowerCase()))}};var log66=getDomainLogger("build",{component:"incremental-coordinator"}),IncrementalBuildCoordinator=class{constructor(e){if(this.config=e,e.enableWatching){const t={contentDirs:e.contentDirs,projContentDirs:e.projContentDirs||e.contentDirs,batchDelay:e.batchDelay||500};this.fileWatcher=new ContentFileWatcher(t),this.fileWatcher.onFileChange(e=>this.handleFileChanges(e))}if(!1!==e.liveReload?.enabled){const t={port:e.liveReload?.port||8091,host:e.liveReload?.host||"localhost",livereloadPort:e.liveReload?.livereloadPort||35729,publicDir:e.publicDir,enableLiveReload:!0};this.liveReloadServer=function(e){return"undefined"!=typeof globalThis&&globalThis.window&&globalThis.window.process&&globalThis.window.process.type||"undefined"!=typeof process&&process.versions&&process.versions.electron||"undefined"!=typeof process&&process.env&&(process.env.ELECTRON_RUN_AS_NODE||process.env.ELECTRON_NO_ATTACH_CONSOLE)?new ElectronLiveReloadServer(e):new FoundryLiveReloadServer(e)}(t)}}fileWatcher;liveReloadServer;buildInProgress=!1;initialized=!1;domainInstances;async initialize(){this.initialized?log66.warn("IncrementalBuildCoordinator already initialized"):(await this.performFullBuildAndCacheDomains(),this.initialized=!0,this.config.onSuccess&&await this.config.onSuccess())}async performFullBuildAndCacheDomains(){try{this.domainInstances=await serveSSG(this.config.projDir,this.config.modulesDir,this.config.markdown,this.config.progressCallback,this.config.httpClient)}catch(e){throw log66.error("Failed to perform full build and cache domains:",e),e}}async startWatching(){if(!this.initialized)throw new Error("Must call initialize() before startWatching()");this.config.enableWatching&&this.fileWatcher&&await this.fileWatcher.startWatching(),this.liveReloadServer&&await this.liveReloadServer.start()}async stopWatching(){this.fileWatcher&&await this.fileWatcher.stopWatching(),this.liveReloadServer&&await this.liveReloadServer.stop()}async handleFileChanges(e){if(this.buildInProgress)setTimeout(()=>this.handleFileChanges(e),1e3);else try{if(this.buildInProgress=!0,this.needFullRebuild(e))return void await this.performFullRebuild(e);await this.performIncrementalBuild(e)}finally{this.buildInProgress=!1}}needFullRebuild(e){return e.some(e=>"deleted"===e.eventType||"created"===e.eventType)}async performIncrementalBuild(e){if(!this.domainInstances)return log66.error("Domain instances not available, falling back to full rebuild"),void await this.performFullRebuild(e);try{const t=await this.domainInstances.fs.getFileMetaInfos(this.getEventsFilePaths(e));if(await this.domainInstances.content.handleChangeFiles(t),await this.domainInstances.site.renderAllLanguages(),this.liveReloadServer){const t=e.map(e=>e.filePath);this.liveReloadServer.notifyReload(t)}this.config.onSuccess&&await this.config.onSuccess()}catch(t){log66.error("Incremental build failed, falling back to full rebuild:",t),await this.performFullRebuild(e)}}getEventsFilePaths(e){return e.map(e=>e.filePath)}async performFullRebuild(e){if(await processSSGWithProgress(this.config.projDir,this.config.modulesDir,this.config.markdown,e=>{log66.info(`Rebuild progress: ${e.stage} - ${e.percentage}%`)},this.config.httpClient),this.liveReloadServer){const t=e.map(e=>e.filePath);this.liveReloadServer.notifyReload(t)}this.config.onSuccess&&await this.config.onSuccess()}isInitialized(){return this.initialized}isBuildInProgress(){return this.buildInProgress}getConfig(){return{...this.config}}getServerUrl(){return this.liveReloadServer?this.liveReloadServer.getUrl():""}getLiveReloadStatus(){if(!this.liveReloadServer)return{running:!1};const e=this.liveReloadServer.isServerRunning();return{running:e,...e&&{url:this.liveReloadServer.getUrl()}}}};async function startIncrementalBuild(e){const t=new IncrementalBuildCoordinator(e);return await t.initialize(),e.enableWatching&&await t.startWatching(),t}init_log(),getDomainLogger("build",{component:"incremental-ssg"}),init_markdown5(),init_page_filter(),init_container(),init_workspace3(),init_identity3(),init_publish2(),init_log(),init_workspace2(),init_fetch_http_client();var ObsidianAuthService=class{constructor(e,t){this.httpClient=e,this.identityAdapter=t}async getStatus(e){try{const t=await this.identityAdapter.getIdentityService(e,this.httpClient),r=t.getStatus(),i={isAuthenticated:r.isAuthenticated,serverUrl:r.serverUrl,hasSyncConfig:r.hasSyncConfig,...r.license?{license:r.license}:{},...r.email?{email:r.email}:{}};if(r.isAuthenticated){const e=t.getToken();e&&(i.token=e)}return r.syncConfig&&(i.syncConfig={dbEndpoint:r.syncConfig.dbEndpoint,dbName:r.syncConfig.dbName,email:r.syncConfig.email,userDir:r.syncConfig.userDir,status:r.syncConfig.status,isActive:r.syncConfig.isActive}),{success:!0,message:r.isAuthenticated?`Authenticated as ${r.email}`:"Not authenticated",data:i}}catch(e){const t=e.message;return t.includes("No workspace found")?{success:!1,message:"No workspace found. Please initialize workspace first.",error:t}:{success:!1,message:`Failed to get status: ${t}`,error:t}}}async getConfig(e){try{const t=(await this.identityAdapter.getIdentityService(e,this.httpClient)).getServerConfig(),r=t.getWebsiteUrl(),i={apiUrl:t.getApiUrl()};return r&&(i.websiteUrl=r),{success:!0,message:"Server configuration retrieved",data:i}}catch(e){const t=e.message;return t.includes("No workspace found")?{success:!1,message:"No workspace found. Please initialize workspace first.",error:t}:{success:!1,message:`Failed to get config: ${t}`,error:t}}}async updateConfig(e,t){try{const r={};t.apiUrl&&(r.apiUrl=t.apiUrl),t.websiteUrl&&(r.websiteUrl=t.websiteUrl);const i=await this.identityAdapter.getIdentityService(e,this.httpClient);await i.updateServerConfig(r);const s=i.getServerConfig(),n=s.getWebsiteUrl(),a={apiUrl:s.getApiUrl()};return n&&(a.websiteUrl=n),{success:!0,message:"Server configuration updated",data:a}}catch(e){const t=e.message;return t.includes("No workspace found")?{success:!1,message:"No workspace found. Please initialize workspace first.",error:t}:{success:!1,message:`Failed to update config: ${t}`,error:t}}}};init_log();var log85=getDomainLogger("obsidian-license",{component:"interface"}),ObsidianLicenseService=class{constructor(e,t){this.httpClient=e,this.identityAdapter=t}async requestTrial(e,t){try{if(!t)return{success:!1,error:"Email is required"};log85.info("Requesting trial license (without activation)",{email:t});const r=await this.identityAdapter.getIdentityService(e,this.httpClient),i=await r.requestTrial(t);return{success:!0,message:"Trial license requested successfully",data:{email:i.email,licenseKey:i.license_key,password:i.password,validityDays:i.validity_days}}}catch(e){return log85.error("Trial license request failed",e),{success:!1,error:e.message}}}async requestAndActivateTrial(e,t){try{if(!t)return{success:!1,error:"Email is required"};log85.info("Requesting and activating trial license",{email:t});const r=await this.identityAdapter.getIdentityService(e,this.httpClient),i=(await r.requestAndActivateTrial(t)).getLicense();return i?{success:!0,message:"Trial license activated successfully",data:this.buildLicenseInfo(i)}:{success:!1,error:"Trial license request succeeded but license not found"}}catch(e){return log85.error("Trial license request and activation failed",e),{success:!1,error:e.message}}}async loginWithLicense(e,t){try{if(!t)return{success:!1,error:"License key is required"};log85.info("Logging in with license key",{licenseKey:t});const r=await this.identityAdapter.getIdentityService(e,this.httpClient),i=await r.loginWithLicense(t);return log85.info("Login successful",{email:i.getEmail().getValue(),hasToken:!!i.getToken()}),{success:!0,message:"Logged in successfully. Token saved.",data:{}}}catch(e){return log85.error("License login failed",e),{success:!1,error:e.message}}}async activateLicense(e,t){try{if(!t)return{success:!1,error:"License key is required"};log85.info("Activating license",{licenseKey:t});const r=await this.identityAdapter.getIdentityService(e,this.httpClient),i=await r.activateLicense(t),s=i.getLicense(),n=i.getSyncConfig();if(!s)return{success:!1,error:"License activation succeeded but license not found"};const a=this.buildLicenseInfo(s);return a.user={email:i.getEmail().getValue(),userDir:n?.getUserDir()||""},a.activation={activated:s.isActivated(),firstTime:s.isFirstTime()},n&&s.getFeatures().syncEnabled&&(a.sync={enabled:!0,status:n.getStatus(),dbEndpoint:n.getDbEndpoint(),dbName:n.getDbName(),email:n.getEmail(),dbPassword:n.getDbPassword(),userDir:n.getUserDir(),liveSyncConfig:n.toObsidianLiveSyncFormat()},log85.info("Sync configuration included in activation response",{dbName:n.getDbName(),email:n.getEmail(),status:n.getStatus()})),{success:!0,message:"License activated successfully",data:a}}catch(e){return log85.error("License activation failed",e),{success:!1,error:e.message}}}async getLicenseInfo(e){try{const t=await this.identityAdapter.getIdentityService(e,this.httpClient),r=t.getLicense();if(!r)return{success:!0,message:"No active license"};const i=this.buildLicenseInfo(r),s=t.getCurrentUser();if(s){const e=s.getSyncConfig();i.user={email:s.getEmail().getValue(),userDir:e?.getUserDir()||""}}return{success:!0,data:i}}catch(e){return log85.error("Failed to get license info",e),{success:!1,error:e.message}}}async getLicenseUsage(e){try{const t=await this.identityAdapter.getIdentityService(e,this.httpClient),r=await t.getLicenseUsage();return r?{success:!0,data:{licenseKey:r.license_key,plan:r.plan,devices:{count:r.devices.count,max:r.features.max_devices,list:r.devices.devices.map(e=>({id:e.id,name:e.device_name,type:e.device_type,status:e.status,lastSeenAt:e.last_seen_at}))},ips:{count:r.ips.count,max:r.features.max_ips,list:r.ips.ips.map(e=>({ip:e.ip_address,city:e.city,region:e.region,country:e.country,status:e.status,lastSeenAt:e.last_seen_at}))},disk:{syncUsage:Number(r.disks.sync_disk_usage)||0,publishUsage:Number(r.disks.publish_disk_usage)||0,totalUsage:Number(r.disks.total_disk_usage)||0,maxStorage:r.features.max_storage,unit:r.disks.unit}}}:{success:!1,error:"Failed to get license usage information"}}catch(e){return log85.error("Failed to get license usage",e),{success:!1,error:e.message}}}async resetUsage(e,t){try{if(!t)return{success:!1,error:"This will delete all sync and publish data! Set force=true to confirm."};const r=await this.identityAdapter.getIdentityService(e,this.httpClient),i=await r.resetUsage();return i.success?{success:!0,message:"License usage data has been reset successfully",data:i}:{success:!1,error:i.message||"Unknown error"}}catch(e){return log85.error("Failed to reset license usage",e),{success:!1,error:e.message}}}async hasActiveLicense(e){try{const t=await this.getLicenseInfo(e);return t.success&&void 0!==t.data&&!t.data.isExpired}catch{return!1}}buildLicenseInfo(e){const t=e.getFeatures();return{key:e.getKey(),plan:e.getFormattedPlan(),isExpired:e.isExpired(),expires:e.getFormattedExpiresAt(),expiresAt:e.getExpiresAt(),daysRemaining:e.getDaysRemaining(),isTrial:e.isTrial(),features:{maxDevices:t.maxDevices,maxIps:t.maxIps,syncEnabled:t.syncEnabled,syncQuota:t.syncQuota,publishEnabled:t.publishEnabled,maxSites:t.maxSites,maxStorage:t.maxStorage,customDomain:t.customDomain,customSubDomain:t.customSubDomain}}}};init_log();var log86=getDomainLogger("obsidian-workspace",{component:"interface"}),ObsidianWorkspaceService=class{constructor(e){this.workspaceAdapter=e}buildWorkspaceInfo(e){const t=e.getInfo(),r=e.getProjects();return{id:t.id,name:t.name,path:t.path,createdAt:t.createdAt.toISOString(),modulesDir:t.modulesDir,projectsDir:t.projectsDir,projectCount:t.projectCount,projects:r.map(e=>{const t=e.getMetadata(),r=t.buildHistory||[],i=r.length>0?new Date(r[r.length-1].timestamp).toISOString():void 0,s={id:t.id,name:t.name,path:e.getPath(),createdAt:new Date(t.createdAt).toISOString()};return i&&(s.lastBuild=i),s})}}async initWorkspace(e,t={}){try{log86.info("Initializing workspace from Obsidian",{workspacePath:e,options:t});const r=this.workspaceAdapter.getWorkspaceAppService(),i={};t.name&&(i.name=t.name),t.modulesDir&&(i.modulesDir=t.modulesDir),t.projectsDir&&(i.projectsDir=t.projectsDir);const s=await r.createWorkspace(e,i),n=this.buildWorkspaceInfo(s);return log86.info("Workspace initialized successfully",{workspaceId:n.id,name:n.name,projectCount:n.projects.length}),{success:!0,message:`Workspace initialized: ${n.name}`,data:n}}catch(e){return log86.error("Failed to initialize workspace",e),{success:!1,message:"Failed to initialize workspace",error:e.message}}}async getWorkspaceInfo(e){try{log86.info("Getting workspace info from Obsidian",{workspacePath:e});const t=this.workspaceAdapter.getWorkspaceAppService(),r=await t.loadWorkspace(e),i=this.buildWorkspaceInfo(r);return log86.info("Workspace info retrieved",{workspaceId:i.id,name:i.name,projectCount:i.projects.length}),{success:!0,data:i}}catch(e){return log86.error("Failed to get workspace info",e),{success:!1,message:"Failed to get workspace info",error:e.message}}}async workspaceExists(e){try{log86.debug("Checking workspace existence",{workspacePath:e});const t=this.workspaceAdapter.getFileSystemRepository(),r=this.workspaceAdapter.getWorkspaceFactory(),i=await t.resolvePath(e);return{success:!0,data:await r.isWorkspace(i)}}catch(e){return log86.error("Failed to check workspace existence",e),{success:!1,error:e.message,data:!1}}}};init_log();var log87=getDomainLogger("obsidian-config",{component:"interface"}),ObsidianGlobalConfigService=class{constructor(e){this.workspaceAdapter=e}async get(e,t){try{log87.info("Getting global config",{workspacePath:e,key:t});const r=this.workspaceAdapter.getWorkspaceAppService(),i=await r.loadWorkspace(e),s=await i.getConfig(t);return void 0===s?{success:!1,error:`Configuration key not found: ${t}`}:{success:!0,data:{key:t,value:s}}}catch(e){return log87.error("Failed to get global config",e),{success:!1,error:e.message}}}async set(e,t,r){try{log87.info("Setting global config",{workspacePath:e,key:t});const i=this.workspaceAdapter.getWorkspaceAppService(),s=await i.loadWorkspace(e);return await s.setConfig(t,r),await i.saveWorkspace(s),{success:!0,message:`Configuration updated: ${t}`,data:{key:t,value:r}}}catch(e){return log87.error("Failed to set global config",e),{success:!1,error:e.message}}}async list(e){try{log87.info("Listing global config",{workspacePath:e});const t=this.workspaceAdapter.getWorkspaceAppService(),r=await t.loadWorkspace(e);return{success:!0,data:{config:await r.getAllConfig(),scope:"global"}}}catch(e){return log87.error("Failed to list global config",e),{success:!1,error:e.message}}}async unset(e,t){try{log87.info("Unsetting global config",{workspacePath:e,key:t});const r=this.workspaceAdapter.getWorkspaceAppService(),i=await r.loadWorkspace(e);return await i.unsetConfig(t)?(await r.saveWorkspace(i),{success:!0,message:`Configuration deleted: ${t}`,data:{key:t}}):{success:!1,error:`Configuration key not found: ${t}`}}catch(e){return log87.error("Failed to unset global config",e),{success:!1,error:e.message}}}async getConfigPath(e){try{const t=this.workspaceAdapter.getWorkspaceAppService();return{success:!0,data:{path:(await t.loadWorkspace(e)).getConfigPath()}}}catch(e){return log87.error("Failed to get global config path",e),{success:!1,error:e.message}}}},ObsidianProjectConfigService=class{constructor(e){this.workspaceAdapter=e}async get(e,t,r){try{log87.info("Getting project config",{workspacePath:e,projectName:t,key:r});const i=this.workspaceAdapter.getWorkspaceAppService(),{workspace:s,project:n}=await i.loadWorkspaceAndProject(t,e);await n.loadConfig();const a=n.getConfigValue(r);return void 0===a?{success:!1,error:`Configuration key not found: ${r}`}:{success:!0,data:{key:r,value:a,project:n.getName()}}}catch(e){return log87.error("Failed to get project config",e),{success:!1,error:e.message}}}async set(e,t,r,i){try{log87.info("Setting project config",{workspacePath:e,projectName:t,key:r});const s=this.workspaceAdapter.getWorkspaceAppService(),{workspace:n,project:a}=await s.loadWorkspaceAndProject(t,e);return await a.loadConfig(),a.setConfigValue(r,i),await s.saveProject(a),{success:!0,message:`Configuration updated: ${r}`,data:{key:r,value:i,project:a.getName()}}}catch(e){return log87.error("Failed to set project config",e),{success:!1,error:e.message}}}async setAll(e,t,r){try{log87.info("Setting entire project config",{workspacePath:e,projectName:t});const i=this.workspaceAdapter.getWorkspaceAppService(),{workspace:s,project:n}=await i.loadWorkspaceAndProject(t,e);return await n.loadConfig(),n.setConfig(r),await i.saveProject(n),{success:!0,message:"Project configuration fully updated",data:{config:r,scope:"project",project:n.getName()}}}catch(e){return log87.error("Failed to set entire project config",e),{success:!1,error:e.message}}}async list(e,t){try{log87.info("Listing project config",{workspacePath:e,projectName:t});const r=this.workspaceAdapter.getWorkspaceAppService(),{workspace:i,project:s}=await r.loadWorkspaceAndProject(t,e);return await s.loadConfig(),{success:!0,data:{config:s.getConfig()||{},scope:"project",project:s.getName()}}}catch(e){return log87.error("Failed to list project config",e),{success:!1,error:e.message}}}async unset(e,t,r){try{log87.info("Unsetting project config",{workspacePath:e,projectName:t,key:r});const i=this.workspaceAdapter.getWorkspaceAppService(),{workspace:s,project:n}=await i.loadWorkspaceAndProject(t,e);return await n.loadConfig(),n.unsetConfigValue(r)?(await i.saveProject(n),{success:!0,message:`Configuration deleted: ${r}`,data:{key:r,project:n.getName()}}):{success:!1,error:`Configuration key not found: ${r}`}}catch(e){return log87.error("Failed to unset project config",e),{success:!1,error:e.message}}}async getConfigPath(e,t){try{const r=this.workspaceAdapter.getWorkspaceAppService(),{workspace:i,project:s}=await r.loadWorkspaceAndProject(t,e);return{success:!0,data:{path:s.getConfigPath(),project:s.getName()}}}catch(e){return log87.error("Failed to get project config path",e),{success:!1,error:e.message}}}};init_log();var log88=getDomainLogger("obsidian-project",{component:"interface"}),ObsidianProjectService=class{constructor(e){this.workspaceAdapter=e}async createProject(e){try{const{name:t,workspacePath:r,sourceFile:i,sourceFolder:s}=e;if(!t)return{success:!1,error:"Project name is required"};log88.info("Creating project from Obsidian",{name:t,workspacePath:r,hasSourceFile:!!i,hasSourceFolder:!!s});const n=this.workspaceAdapter.getWorkspaceAppService(),a=await n.loadWorkspace(r);return i?await this.createProjectFromFile(a,e):s?await this.createProjectFromFolder(a,e):await this.createEmptyProject(a,e)}catch(e){return log88.error("Failed to create project",e),{success:!1,message:"Failed to create project",error:e.message}}}async createProjectFromFile(e,t){const{name:r,sourceFile:i,theme:s,language:n,type:a="site"}=t;log88.info("Creating project from file",{name:r,sourceFile:i,type:a});const o={type:a,theme:s||"https://gohugo.net/note.zip?version=1.2",language:n||"en"},l=this.workspaceAdapter.getWorkspaceAppService(),c=await l.createProjectFromFile(e,r,i,o),h=await this.buildProjectInfo(c,o);return log88.info("Project created from file",{projectId:h.id,name:h.name,type:a}),{success:!0,message:`Project created from file: ${r}`,data:h}}async createProjectFromFolder(e,t){const{name:r,sourceFolder:i,theme:s,language:n,type:a="site"}=t;log88.info("Creating project from folder",{name:r,sourceFolder:i,type:a});const o={type:a,language:n||"en"};s&&(o.theme=s);const l=this.workspaceAdapter.getWorkspaceAppService(),c=await l.createProjectFromFolder(e,r,i,o),h=await this.buildProjectInfo(c,{...s?{theme:s}:{},language:o.language});return log88.info("Project created from folder",{projectId:h.id,name:h.name,type:a,contentLinks:h.contentLinks?.length||0,hasStaticLink:!!h.staticLink}),{success:!0,message:`Project created from folder: ${r}`,data:h}}async createEmptyProject(e,t){const{name:r,theme:i,language:s,createSampleContent:n=!0,type:a="site"}=t;log88.info("Creating empty project",{name:r,type:a});const o={type:a,language:s||"en",createSampleContent:n};i&&(o.theme=i);const l=this.workspaceAdapter.getWorkspaceAppService(),c=await l.createProject(e,r,o),h=await this.buildProjectInfo(c,{...i?{theme:i}:{},language:o.language});return log88.info("Empty project created",{projectId:h.id,name:h.name,type:a}),{success:!0,message:`Project created: ${r}`,data:h}}async buildProjectInfo(e,t){const r=e.getMetadata(),i=e.getContentLinks(),s=e.getStaticLink(),n=e.getFileLink(),a=e.getSupportedLanguagesFromLinks(),o={id:r.id,name:r.name,type:r.type,path:e.getPath(),createdAt:new Date(r.createdAt).toISOString(),updatedAt:new Date(r.updatedAt).toISOString()};t.theme&&(o.theme=t.theme),t.language&&(o.language=t.language),n&&(o.fileLink={sourcePath:n.sourcePath,targetPath:n.targetPath,isSymlink:n.isSymlink}),i&&i.length>0&&(o.contentLinks=i.map(e=>({sourcePath:e.sourcePath,languageCode:e.languageCode,weight:e.weight}))),s&&(o.staticLink={sourcePath:s.sourcePath}),a&&a.length>0&&(o.languages=a);try{await e.loadConfig();const t=e.getConfigValue("publish.method");t&&(o.publishMethod=t)}catch(e){log88.debug("Failed to get publish method from config",{error:e})}return o}async listProjects(e){try{log88.info("Listing projects from Obsidian",{workspacePath:e});const t=this.workspaceAdapter.getWorkspaceAppService(),r=(await t.loadWorkspace(e)).getProjects(),i=await Promise.all(r.map(async e=>{const t=e.getMetadata(),r=e.getContentLinks(),i=e.getStaticLink(),s=e.getFileLink(),n=e.getSupportedLanguagesFromLinks(),a={id:t.id,name:t.name,type:t.type,path:e.getPath(),createdAt:new Date(t.createdAt).toISOString(),updatedAt:new Date(t.updatedAt).toISOString()};s&&(a.fileLink={sourcePath:s.sourcePath,targetPath:s.targetPath,isSymlink:s.isSymlink}),r&&r.length>0&&(a.contentLinks=r.map(e=>({sourcePath:e.sourcePath,languageCode:e.languageCode,weight:e.weight}))),i&&(a.staticLink={sourcePath:i.sourcePath}),n&&n.length>0&&(a.languages=n);try{await e.loadConfig();const t=e.getConfigValue("publish.method");t&&(a.publishMethod=t)}catch(e){log88.debug("Failed to get publish method from config",{projectName:t.name,error:e})}return a}));return log88.info("Projects listed",{count:i.length}),{success:!0,data:i}}catch(e){return log88.error("Failed to list projects",e),{success:!1,error:e.message}}}async getProjectInfo(e,t){try{log88.info("Getting project info from Obsidian",{workspacePath:e,projectName:t});const r=this.workspaceAdapter.getWorkspaceAppService(),i=(await r.loadWorkspace(e)).findProject(t);return i?{success:!0,data:await this.buildProjectInfo(i,{})}:{success:!1,error:`Project not found: ${t}`}}catch(e){return log88.error("Failed to get project info",e),{success:!1,error:e.message}}}async deleteProject(e,t,r){try{log88.info("Deleting project from Obsidian",{workspacePath:e,projectIdOrName:t,deleteFiles:r?.deleteFiles});const i=this.workspaceAdapter.getWorkspaceAppService(),s=await i.loadWorkspace(e),n=s.findProject(t);if(!n)return{success:!1,error:`Project not found: ${t}`};const a=n.getName();return await i.deleteProject(s,t,r),log88.info("Project deleted successfully",{projectName:a,deleteFiles:r?.deleteFiles}),{success:!0,message:`Project deleted: ${a}`}}catch(e){return log88.error("Failed to delete project",e),{success:!1,error:e.message}}}async scanFolderStructure(e){try{log88.info("Scanning folder structure from Obsidian",{folderPath:e});const t=this.workspaceAdapter.getWorkspaceAppService(),r=await t.scanFolderStructure(e),i=r.getStaticFolder(),s={rootPath:r.getRootPath(),isStructured:r.getIsStructured(),contentFolders:r.getContentFolders(),staticFolder:i?{path:i.path}:void 0,isValid:r.isValid(),isMultilingual:r.isMultilingual(),supportedLanguages:r.getSupportedLanguages(),defaultLanguage:r.getDefaultContentFolder()?.languageCode,summary:r.getSummary()};return log88.info("Folder structure scanned",{isStructured:s.isStructured,contentFolders:s.contentFolders.length,isMultilingual:s.isMultilingual,languages:s.supportedLanguages}),{success:!0,message:"Folder structure scanned successfully",data:s}}catch(e){return log88.error("Failed to scan folder structure",e),{success:!1,error:e.message}}}};init_log(),init_ssg();import path40 from"path";import{promises as fs13}from"fs";var log89=getDomainLogger("obsidian-build",{component:"interface"}),ObsidianBuildService=class{constructor(e){this.workspaceAdapter=e}async buildProject(e){try{const{workspacePath:t,projectNameOrPath:r,destination:i,modulesDir:s,contentDirs:n,clean:a=!1,parallel:o=!1,snapshot:l=!1,snapshotName:c}=e;log89.info("Building project from Obsidian",{projectNameOrPath:r,parallel:o,clean:a});const h=this.workspaceAdapter.getWorkspaceAppService(),{workspace:u,project:g}=await h.loadWorkspaceAndProject(r,t);log89.info(`Building project: ${g.getName()}`),await g.loadConfig();const d=g.getPath(),p=s||u.getModulesDir(),m=i?path40.resolve(d,i):await g.getPublishDir();a&&(await this.cleanOutputDir(m),log89.info(`Cleaned output directory: ${m}`));const f=Date.now();let y=await g.getContentDirs();if(n&&n.length>0){const e=n.map(e=>path40.resolve(d,e));y=[...y,...e],log89.info(`Added extra content directories: ${n.join(", ")}`)}log89.info(`Content directories: ${y.length}`),log89.info(`Modules directory: ${p}`),log89.info(`Output directory: ${m}`),await this.syncFileLinkIfNeeded(g),o?(log89.info("🚀 Using parallel build mode"),await processSSGParallel(d,p)):await processSSG(d,p);const w=Date.now()-f;let S;if(l){const e=await h.createSnapshot(g,c);S=c?`${e.id} (${c})`:e.id,log89.info(`Snapshot created: ${S}`)}const b={timestamp:f,type:"build",success:!0,duration:w};g.addBuildHistory(b),await h.saveProject(g);const _=await h.setupProjectBaseURLStructure(g);log89.debug("baseURL structure setup complete",_),log89.info(`Build completed in ${w}ms`);let k=`Built site in ${(w/1e3).toFixed(1)}s\n`;return k+=`Project: ${g.getName()}\n`,k+=`Output: ${m}`,o&&(k+="\nUsed parallel processing"),a&&(k+="\nCleaned output directory"),S&&(k+=`\nSnapshot: ${S}`),{success:!0,message:k,data:{projectName:g.getName(),duration:w,outputDir:m,contentDirs:y,...S?{snapshot:S}:{}}}}catch(e){return log89.error("Build failed",e),{success:!1,message:"Build failed",error:e.message}}}async syncFileLinkIfNeeded(e){const t=e.getFileLink();if(t&&!t.isSymlink)try{log89.info("Syncing source file for copyFile-mode project",{source:t.sourcePath,target:t.targetPath});const e=this.workspaceAdapter.getFileSystemRepository();if(!await e.exists(t.sourcePath))return void log89.warn("Source file not found, skipping sync",{source:t.sourcePath});await e.copyFile(t.sourcePath,t.targetPath),log89.info("Source file synced successfully",{source:t.sourcePath,target:t.targetPath})}catch(e){log89.error("Failed to sync source file",e),log89.warn("Build will continue with existing file")}}async cleanOutputDir(e){try{await fs13.access(e);const t=await fs13.readdir(e);await Promise.all(t.map(t=>fs13.rm(path40.join(e,t),{recursive:!0,force:!0})))}catch(e){if("ENOENT"!==e.code)throw e}}};init_log();var log90=getDomainLogger("obsidian-serve",{component:"interface"}),ObsidianServeService=class{constructor(e,t){this.workspaceAdapter=e,this.publishAppService=t}publishAppService;coordinator;publishTimer;hasAutoPublish=!1;calculateOverallProgress(e,t){if(!this.hasAutoPublish)return t;switch(e){case"initializing":case"building":return.5*t;case"build-success":return 50;case"publishing":return 50+.5*t;case"publish-success":case"watching":return 100;default:return t}}createProgressCallback(e,t,r,i){const s={phase:e,percentage:t,overallPercentage:this.calculateOverallProgress(e,t),message:r};return i?.currentFile&&(s.currentFile=i.currentFile),i?.data&&(s.data=i.data),s}async startServer(e,t){try{const{workspacePath:r,projectName:i}=e;this.hasAutoPublish=!!e.publishConfig,log90.info("Starting server from Obsidian",{projectName:i,hasAutoPublish:this.hasAutoPublish}),t?.(this.createProgressCallback("initializing",10,"Loading project..."));const s=this.workspaceAdapter.getWorkspaceAppService(),{workspace:n,project:a}=await s.loadWorkspaceAndProject(i,r);log90.info(`Starting server for project: ${a.getName()}`);const o=e.port||8080,l=e.host||"localhost",c=e.livereloadPort||35729,h=!1!==e.livereload;t?.(this.createProgressCallback("initializing",30,"Preparing build configuration..."));const u=await s.ensureProjectBaseURLStructure(a);u.recreated&&log90.info("baseURL structure created/updated");const g=await a.getContentDirs(),d=a.getLinkDirs(),p=n.getModulesDir(),m=await a.getPublishDir(),f=a.getPath();let y=Date.now();const w={projDir:f,modulesDir:p,contentDirs:d,projContentDirs:g,publicDir:m,enableWatching:!0,batchDelay:300,progressCallback:e=>{if(t){const r={};e.currentFile&&(r.currentFile=e.currentFile),t(this.createProgressCallback("building",e.percentage,e.message,r))}},onSuccess:async()=>{const r=(Date.now()-y)/1e3;t?.(this.createProgressCallback("build-success",100,"Build completed successfully",{data:{buildTime:Number(r.toFixed(2)),filesProcessed:0}})),e.publishConfig&&this.publishAppService&&await this.autoPublish(a,e.publishConfig.method,e.publishConfig.config,e.publishConfig.delay,t),y=Date.now()}};if(h&&(w.liveReload={enabled:!0,port:o,host:l,livereloadPort:c}),e.markdown&&(w.markdown=e.markdown),await this.syncFileLinkIfNeeded(a),log90.info("Starting incremental build server..."),this.coordinator=await startIncrementalBuild(w),!this.coordinator.isInitialized())throw new Error("Failed to initialize build coordinator");const S=`http://${l}:${o}${u.baseURL}`;return log90.info(`Server running at ${S}`),{success:!0,message:`Server running at ${S}`,data:{url:S,port:o,host:l,baseURL:u.baseURL,serverRoot:u.serverRoot,...h?{livereloadPort:c}:{},...e.publishConfig?{autoPublish:e.publishConfig.method}:{}}}}catch(e){return log90.error("Failed to start server",e),t?.(this.createProgressCallback("error",0,`Failed to start server: ${e.message}`)),{success:!1,message:"Failed to start server",error:e.message}}}async stopServer(){try{return log90.info("Stopping server from Obsidian"),this.publishTimer&&(clearTimeout(this.publishTimer),this.publishTimer=void 0),this.coordinator&&(await this.coordinator.stopWatching(),this.coordinator=void 0),log90.info("Server stopped successfully"),!0}catch(e){return log90.error("Error stopping server",e),!1}}isRunning(){return this.coordinator?.isInitialized()||!1}async autoPublish(e,t,r,i,s){this.publishTimer&&clearTimeout(this.publishTimer);const n=i||2e3;this.publishTimer=setTimeout(async()=>{try{log90.info(`Auto-publishing to ${t}...`),s?.(this.createProgressCallback("publishing",0,`Publishing to ${t}...`));const i=Date.now(),n=await this.publishAppService.publish(e,r,{incremental:!0},e=>{if(s){const t={};e.currentFile&&(t.currentFile=e.currentFile),s(this.createProgressCallback("publishing",e.percentage,e.message,t))}}),a=(Date.now()-i)/1e3;if(n.success){const e=`Published to ${t.toUpperCase()} successfully`;log90.info(e,{url:n.url,filesUploaded:n.filesUploaded,bytesTransferred:n.bytesTransferred,duration:a}),s?.(this.createProgressCallback("publish-success",100,e,{data:{publishUrl:n.url,filesUploaded:n.filesUploaded,bytesTransferred:n.bytesTransferred,publishTime:Number(a.toFixed(2)),method:t}}))}else log90.error(`Publish to ${t} failed: ${n.error}`),s?.(this.createProgressCallback("error",0,`Publish failed: ${n.error}`))}catch(e){log90.error(`Publish to ${t} failed`,e),s?.(this.createProgressCallback("error",0,`Publish error: ${e.message}`))}},n)}async syncFileLinkIfNeeded(e){const t=e.getFileLink();if(t&&!t.isSymlink)try{log90.info("Syncing source file for copyFile-mode project",{source:t.sourcePath,target:t.targetPath});const e=this.workspaceAdapter.getFileSystemRepository();if(!await e.exists(t.sourcePath))return void log90.warn("Source file not found, skipping sync",{source:t.sourcePath});await e.copyFile(t.sourcePath,t.targetPath),log90.info("Source file synced successfully",{source:t.sourcePath,target:t.targetPath})}catch(e){log90.error("Failed to sync source file",e),log90.warn("Server will start with existing file")}}};init_log();var log91=getDomainLogger("obsidian-publish",{component:"interface"}),ObsidianPublishService=class{constructor(e,t){this.workspaceAdapter=t,this.publishAppService=e}publishAppService;async publish(e,t){const r=Date.now();try{const{workspacePath:i,projectName:s,method:n,config:a,force:o=!1}=e;log91.info("Publishing from Obsidian",{projectName:s,method:n});const l=this.workspaceAdapter.getWorkspaceAppService(),{workspace:c,project:h}=await l.loadWorkspaceAndProject(s,i);log91.info(`Publishing project: ${h.getName()} to ${n}`);const u=await this.publishAppService.publish(h,a,o?{force:!0}:{},t?e=>{const r={phase:e.phase,percentage:e.percentage,message:e.message};void 0!==e.currentFile&&(r.currentFile=e.currentFile),void 0!==e.filesCompleted&&(r.filesCompleted=e.filesCompleted),void 0!==e.filesTotal&&(r.filesTotal=e.filesTotal),void 0!==e.bytesTransferred&&(r.bytesTransferred=e.bytesTransferred),t(r)}:void 0),g=Date.now()-r;return u.success?{success:!0,message:`Published to ${n.toUpperCase()} successfully`,data:{url:u.url,filesUploaded:u.filesUploaded||0,bytesTransferred:u.bytesTransferred||0,duration:g}}:{success:!1,message:"Publish failed",error:u.error}}catch(e){return log91.error("Publish failed",e),{success:!1,message:"Publish failed",error:e.message}}}async testConnection(e,t,r){try{log91.info("Testing connection from Obsidian",{projectName:t,type:r.type});const i=this.workspaceAdapter.getWorkspaceAppService(),{workspace:s,project:n}=await i.loadWorkspaceAndProject(t,e),a=await this.publishAppService.testConnection(n,r);return{success:a.success,...a.error?{error:a.error}:{}}}catch(e){return log91.error("Test connection failed",e),{success:!1,error:e.message}}}},ObsidianDomainService=class{constructor(e,t){this.httpClient=e,this.identityAdapter=t}async getIdentityService(e){return await this.identityAdapter.getIdentityService(e,this.httpClient)}async getDomainInfo(e){try{const t=await this.getIdentityService(e),r=await t.getDomains();if(!r)return{success:!1,message:"No domain information found"};const i={subdomain:r.subdomain,fullDomain:r.full_domain,folder:r.folder,createdAt:"number"==typeof r.created_at?new Date(r.created_at).toISOString():r.created_at};return r.cus_domain&&(i.customDomain=r.cus_domain),{success:!0,message:"Domain information retrieved",data:i}}catch(e){const t=e.message;return t.includes("No workspace found")?{success:!1,message:"No workspace found. Please initialize workspace first.",error:t}:{success:!1,message:`Failed to get domain info: ${t}`,error:t}}}async checkSubdomain(e,t){try{const r=await this.getIdentityService(e),i=await r.checkSubdomainAvailability(t);if(!i)return{success:!1,message:"Failed to check subdomain availability"};const s={available:i.available};i.message&&(s.message=i.message);const n=i.available?`Subdomain "${t}" is available`:`Subdomain "${t}" is not available`;return{success:i.available,message:n,data:s}}catch(e){const t=e.message;return t.includes("No workspace found")?{success:!1,message:"No workspace found. Please initialize workspace first.",error:t}:{success:!1,message:`Failed to check subdomain: ${t}`,error:t}}}async updateSubdomain(e,t){try{const r=await this.getIdentityService(e),i=await r.updateSubdomain(t);return i?{success:!0,message:"Subdomain updated successfully",data:{oldSubdomain:i.old_subdomain,newSubdomain:i.new_subdomain,fullDomain:i.full_domain,message:i.message}}:{success:!1,message:"Failed to update subdomain"}}catch(e){const t=e.message;return t.includes("No workspace found")?{success:!1,message:"No workspace found. Please initialize workspace first.",error:t}:{success:!1,message:`Failed to update subdomain: ${t}`,error:t}}}async checkCustomDomain(e,t){try{const r=await this.getIdentityService(e),i=await r.checkCustomDomain(t);if(!i)return{success:!1,message:"Failed to check custom domain"};const s={ready:i.ready,dnsValid:i.dns_valid,message:i.message};return i.resolved_ips&&i.resolved_ips.length>0&&(s.resolvedIps=i.resolved_ips),{success:i.ready,message:i.ready?"Custom domain is ready":"Custom domain is not ready",data:s}}catch(e){const t=e.message;return t.includes("No workspace found")?{success:!1,message:"No workspace found. Please initialize workspace first.",error:t}:{success:!1,message:`Failed to check custom domain: ${t}`,error:t}}}async addCustomDomain(e,t){try{const r=await this.getIdentityService(e),i=await r.addCustomDomain(t);return i?{success:!0,message:"Custom domain added successfully",data:{domain:i.domain,status:i.status,message:i.message}}:{success:!1,message:"Failed to add custom domain"}}catch(e){const t=e.message;return t.includes("No workspace found")?{success:!1,message:"No workspace found. Please initialize workspace first.",error:t}:{success:!1,message:`Failed to add custom domain: ${t}`,error:t}}}async checkHttpsStatus(e,t){try{const r=await this.getIdentityService(e),i=await r.checkCustomDomainHttpsStatus(t);if(!i)return{success:!1,message:"Failed to check HTTPS status"};const s={tlsReady:i.tls_ready,dnsValid:i.dns_valid,status:i.status,message:i.message};if(i.certificate){const e={};i.certificate.issuer&&(e.issuer=i.certificate.issuer),i.certificate.valid_from&&(e.validFrom=i.certificate.valid_from),i.certificate.valid_to&&(e.validTo=i.certificate.valid_to),s.certificate=e}return{success:i.tls_ready,message:i.tls_ready?"HTTPS is ready":"HTTPS is not ready yet",data:s}}catch(e){const t=e.message;return t.includes("No workspace found")?{success:!1,message:"No workspace found. Please initialize workspace first.",error:t}:{success:!1,message:`Failed to check HTTPS status: ${t}`,error:t}}}};function createProgressEvent(e,t,r){return{type:e,message:t,progress:r?.progress,metadata:r?.metadata,timestamp:Date.now()}}function calculateProgress(e,t){return{current:e,total:t,percentage:t>0?Math.round(e/t*100):0}}init_wiki(),init_log();var log92=getDomainLogger("obsidian-wiki",{component:"interface"}),ObsidianWikiService=class{constructor(e){this.wikiAdapter=e}async ingest(e){try{const{workspacePath:t,projectName:r,filePath:i,temperature:s,onProgress:n}=e;log92.info("Starting wiki ingest",{workspacePath:t,projectName:r,filePath:i}),n?.(createProgressEvent("ingest:start",i?`Starting ingest for file: ${i}`:"Starting folder ingest"));const a=await this.wikiAdapter.createWikiService(t,r);let o;if(await a.loadKB(),i){n?.(createProgressEvent("ingest:file:start",`Processing file: ${i}`));const e={};void 0!==s&&(e.temperature=s),n&&(e.onIngestProgress=e=>{n(createProgressEvent("ingest:llm:token:usage",`Ingest LLM token usage (live) — completion: ~${e}`,{metadata:{tokenUsage:{promptTokens:0,completionTokens:e,totalTokens:e},isEstimate:!0}}))},e.onIngestTokenUsage=e=>{n(createProgressEvent("ingest:llm:token:usage",`Ingest LLM token usage — prompt: ${e.promptTokens}, completion: ${e.completionTokens}, total: ${e.totalTokens}`,{metadata:{tokenUsage:{promptTokens:e.promptTokens,completionTokens:e.completionTokens,totalTokens:e.totalTokens,model:e.model},isEstimate:!1}})),log92.info("Ingest LLM token usage (final)",e)},e.onEmbeddingUsage=e=>{n(createProgressEvent("ingest:embedding:token:usage",`Embedding token usage — prompt: ${e.promptTokens}, total: ${e.totalTokens}`,{metadata:{embeddingTokenUsage:{promptTokens:e.promptTokens,completionTokens:0,totalTokens:e.totalTokens,model:e.model}}}))}),n?.(createProgressEvent("ingest:file:reading","Reading file content"));const t=await a.ingestFile(i,e);n?.(createProgressEvent("ingest:file:complete",`File processed: ${t.extractedEntities} entities, ${t.extractedConcepts} concepts`)),o={success:t.success,sourcePath:t.sourcePath,extractedEntities:t.extractedEntities,extractedConcepts:t.extractedConcepts,extractedConnections:t.extractedConnections,timeMs:t.timeMs,pagesGenerated:0,...t.error&&{error:t.error}}}else{const e=n?e=>{n(createProgressEvent("ingest:llm:token:usage",`Ingest LLM token usage (live) — completion: ~${e}`,{metadata:{tokenUsage:{promptTokens:0,completionTokens:e,totalTokens:e},isEstimate:!0}}))}:void 0,t=n?e=>{n(createProgressEvent("ingest:llm:token:usage",`Ingest LLM token usage — prompt: ${e.promptTokens}, completion: ${e.completionTokens}, total: ${e.totalTokens}`,{metadata:{tokenUsage:{promptTokens:e.promptTokens,completionTokens:e.completionTokens,totalTokens:e.totalTokens,model:e.model},isEstimate:!1}}))}:void 0,r=n?e=>{n(createProgressEvent("ingest:embedding:token:usage",`Embedding token usage — prompt: ${e.promptTokens}, total: ${e.totalTokens}`,{metadata:{embeddingTokenUsage:{promptTokens:e.promptTokens,completionTokens:0,totalTokens:e.totalTokens,model:e.model}}}))}:void 0;o=await this.ingestFolder(a,s,n,r,t,e)}if(o.success){log92.info("Auto-generating wiki pages after ingest"),n?.(createProgressEvent("ingest:pages:generating","Generating wiki pages"));try{await a.generateAllPages();const e=a.kb,t=e?._entities?e._entities.size:0,r=e?._concepts?e._concepts.size:0;o.pagesGenerated=t+r,n?.(createProgressEvent("ingest:pages:complete",`Generated ${o.pagesGenerated} pages`)),log92.info("Wiki pages auto-generated",{pagesGenerated:o.pagesGenerated})}catch(e){log92.error("Failed to auto-generate pages",e),o.pagesGenerated=0}}return await a.saveKB(),n?.(createProgressEvent("ingest:complete","Ingest completed successfully")),log92.info("Wiki ingest completed",{result:o}),{success:!0,message:"Ingest completed",data:o}}catch(e){return log92.error("Failed to ingest",e),{success:!1,error:e.message}}}async*queryStream(e){const{workspacePath:t,projectName:r,question:i,temperature:s,maxResults:n,onProgress:a}=e;log92.info("Starting wiki query stream",{workspacePath:t,projectName:r,question:i}),a?.(createProgressEvent("query:start",`Starting query: ${i}`));const o=await this.wikiAdapter.createWikiService(t,r);await o.loadKB();const l=o.kb;l?.hasEmbeddingIndex?.()&&a?.(createProgressEvent("query:embedding:searching","Searching knowledge base with embeddings"));const c={};void 0!==s&&(c.temperature=s),void 0!==n&&(c.maxResults=n),a&&(c.onTokenUsage=e=>{a(createProgressEvent("query:token:usage",`Token usage — prompt: ${e.promptTokens}, completion: ${e.completionTokens}, total: ${e.totalTokens}`,{metadata:{tokenUsage:{promptTokens:e.promptTokens,completionTokens:e.completionTokens,totalTokens:e.totalTokens,model:e.model},isEstimate:!1}})),log92.info("Token usage (final)",e)},c.onEmbeddingUsage=e=>{a(createProgressEvent("query:embedding:token:usage",`Embedding token usage — prompt: ${e.promptTokens}, total: ${e.totalTokens}`,{metadata:{embeddingTokenUsage:{promptTokens:e.promptTokens,completionTokens:0,totalTokens:e.totalTokens,model:e.model}}})),log92.info("Embedding token usage (query)",e)});let h=0,u=!1;const g=e=>Math.max(1,Math.ceil(e.length/3));for await(const e of o.queryStream(i,c))u||(u=!0,a?.(createProgressEvent("query:llm:generating","Generating answer"))),h+=g(e),a&&a(createProgressEvent("query:token:usage",`Token usage (live) — completion: ~${h}`,{metadata:{tokenUsage:{promptTokens:0,completionTokens:h,totalTokens:h},isEstimate:!0}})),yield e;a?.(createProgressEvent("query:complete","Query completed"))}async saveConversation(e){try{const{workspacePath:t,projectName:r,question:i,answer:s,title:n,topic:a,conversationHistory:o,filename:l,sources:c,autoIngest:h=!0}=e;log92.info("Saving conversation",{workspacePath:t,projectName:r});const u=await this.wikiAdapter.createWikiService(t,r);let g;if(await u.loadKB(),o&&o.length>0){const e=n||o.map((e,t)=>`Q${t+1}: ${e.question}`).join("\n\n"),t=o.map((e,t)=>`A${t+1}: ${e.answer}`).join("\n\n"),r={};c&&(r.sources=c),g=await u.saveConversation(e,t,r)}else{if(!i||!s)throw new Error("Either conversationHistory or (question, answer) must be provided");{const e={};c&&(e.sources=c),g=await u.saveConversation(i,s,e)}}const d=await this.wikiAdapter.getBasename(g);if(h){log92.info("Starting auto-ingest of conversation",{filePath:g});const e=await u.ingestFile(g);log92.info("Auto-ingest result",{success:e.success,entities:e.extractedEntities,concepts:e.extractedConcepts,connections:e.extractedConnections}),e.success&&(log92.info("Auto-generating pages after conversation ingest"),await u.generateAllPages()),await u.saveKB(),log92.info("KB saved after auto-ingest")}return{success:!0,message:"Conversation saved",data:{savedPath:g,filePath:g,filename:d}}}catch(e){return log92.error("Failed to save conversation",e),{success:!1,error:e.message}}}async generatePages(e){try{const{workspacePath:t,projectName:r}=e;log92.info("Starting wiki page generation",{workspacePath:t,projectName:r});const i=Date.now(),s=await this.wikiAdapter.createWikiService(t,r);await s.loadKB(),await s.generateAllPages();const n=Date.now()-i,a=s.config?.paths?.wikiDir||"",o=s.kb,l=(o?.entities?Object.keys(o.entities).length:0)+(o?.concepts?Object.keys(o.concepts).length:0);return log92.info("Wiki page generation completed",{pageCount:l,timeMs:n}),{success:!0,message:"Wiki pages generated",data:{success:!0,pageCount:l,outputDir:a,timeMs:n}}}catch(e){return log92.error("Failed to generate wiki pages",e),{success:!1,error:e.message}}}async ingestFolder(e,t,r,i,s,n){const a=e.config?.paths?.sourcePath||"",o=await this.wikiAdapter.listMarkdownFiles(a),l=(o.length,Date.now()),c={temperature:t};n&&(c.onIngestProgress=n),s&&(c.onIngestTokenUsage=s),i&&(c.onEmbeddingUsage=i);const h=await e.ingestFolderIncremental(o,c,async(e,t,i,s)=>{const n=await this.wikiAdapter.getBasename(i);r?.(s?createProgressEvent("ingest:file:start",`[new] Processing file ${e}/${t}: ${n}`,{progress:calculateProgress(e,t)}):createProgressEvent("ingest:file:skip",`[skip] Already ingested: ${n}`,{progress:calculateProgress(e,t)}))}),{newFiles:u,skippedFiles:g}=h;return u.length>0?r?.(createProgressEvent("ingest:file:complete",`Processed ${u.length} new file(s), skipped ${g.length} already-ingested file(s)`)):r?.(createProgressEvent("ingest:file:complete",`No new files found (${g.length} file(s) already up-to-date)`)),{success:!0,sourcePath:a,extractedEntities:h.extractedEntities,extractedConcepts:h.extractedConcepts,extractedConnections:h.extractedConnections,timeMs:Date.now()-l,pagesGenerated:0,newFilesCount:u.length,skippedFilesCount:g.length}}calculateCost(e){try{const{provider:t,model:r,inputTokens:i,outputTokens:s}=e,n=estimateCost(t,r,i,s);return n?(log92.info("Cost calculated",{provider:t,model:r,inputTokens:i,outputTokens:s,totalCost:n.totalCost}),{success:!0,data:n}):{success:!1,error:`No pricing data found for provider "${t}". Check MODEL_PRICING or use getPricingTable().`}}catch(e){return log92.error("Failed to calculate cost",e),{success:!1,error:e.message}}}getPricingTable(){return MODEL_PRICING}};function createObsidianWorkspaceAppService(){return createWorkspaceAppService()}async function createObsidianIdentityService(e,t){const r=createWorkspaceAppService(),i=await r.loadWorkspace(e),s=r.createIdentityStorage(i),n=new UserFactory({httpClient:t,storageProvider:s}),a=new IdentityAppService({userFactory:n});return await a.initialize(),a}async function getIdentityService(e,t){return await createObsidianIdentityService(e,t)}init_identity2(),init_identity3(),init_container(),init_container();var DesktopIdentityAdapter=class{async getIdentityService(e,t){return await createObsidianIdentityService(e,t)}};init_node_file_system();var DesktopWorkspaceAdapter=class{workspaceAppService;workspaceFactory;fileSystemRepo;getWorkspaceAppService(){return this.workspaceAppService||(this.workspaceAppService=createWorkspaceAppService()),this.workspaceAppService}getWorkspaceFactory(){return this.workspaceFactory||(this.workspaceFactory=createWorkspaceFactory()),this.workspaceFactory}getFileSystemRepository(){return this.fileSystemRepo||(this.fileSystemRepo=new NodeFileSystemRepository),this.fileSystemRepo}};init_wiki();var DEFAULT_WIKI_SERVICE_CONFIG={outputLanguage:"English",ingestTemperature:.1,queryTemperature:.7,maxQueryResults:10},WikiService=class{factory;kb=null;config;constructor(e,t){this.factory=e,this.config=t,this.config.wiki={...DEFAULT_WIKI_SERVICE_CONFIG,...t.wiki}}get llmProvider(){return this.config.llm.provider}get embeddingProvider(){return this.config.embedding?.provider}get fileSystem(){return this.config.infrastructure.fileSystem}get pathService(){return this.config.infrastructure.pathService}get cryptoService(){return this.config.infrastructure.cryptoService}get conversationRepo(){return this.config.infrastructure.conversationRepo}async loadKB(){const e=await this.factory.load();if(e){if(this.kb=e,this.embeddingProvider&&!this.kb.hasEmbeddingIndex())try{await this.buildEmbeddingIndexForKB()}catch(e){console.warn("Failed to build embedding index on load",e)}return!0}return this.kb=this.factory.create(),!1}async saveKB(){if(!this.kb)throw new Error("No KB to save");if(this.kb.hasEmbeddingIndex())try{await this.kb.saveEmbeddingIndex(this.fileSystem,this.pathService)}catch(e){console.warn("Failed to save embedding index",e)}await this.factory.save(this.kb)}getStats(){if(!this.kb)throw new Error("KB not loaded");return this.kb.getStats()}getKnowledgeBase(){if(!this.kb)throw new Error("KB not loaded");return this.kb}async ingestFile(e,t){if(!this.kb)throw new Error("KB not loaded. Call loadKB() first.");try{const r=await this.fileSystem.readFile(e,"utf-8"),i=this.config.llm.defaultModel,s=t?.temperature??this.config.wiki.ingestTemperature,n=this.config.llm.defaultMaxTokens??32768,a=this.config.wiki.outputLanguage,o={llmProvider:this.llmProvider,model:i,temperature:s,maxTokens:n,outputLanguage:a,fileSystem:this.fileSystem,crypto:this.cryptoService,...t?.onIngestTokenUsage?{onIngestTokenUsage:t.onIngestTokenUsage}:{},...t?.onIngestProgress?{onIngestProgress:t.onIngestProgress}:{}},l=await this.kb.ingestFromSource(e,r,o);if(l.success&&this.embeddingProvider)try{await this.buildEmbeddingIndexForKB(t?.onEmbeddingUsage)}catch(e){console.warn("Failed to update embedding index after ingest",e)}return{...l,sourcePath:e}}catch(t){return console.error("❌ Ingest failed:",t.message),{success:!1,sourcePath:e,extractedEntities:0,extractedConcepts:0,extractedConnections:0,timeMs:0,error:t.message||"Unknown error"}}}async ingestFolderIncremental(e,t,r){if(!this.kb)throw new Error("KB not loaded. Call loadKB() first.");const i=[],s=[];let n=0,a=0,o=0;const l=Date.now();for(let l=0;l<e.length;l++){const c=e[l],h=this.kb.isNewSource(c);if(await(r?.(l+1,e.length,c,h)),!h){s.push(c);continue}i.push(c);const u=await this.ingestFile(c,t);u.success&&(n+=u.extractedEntities,a+=u.extractedConcepts,o+=u.extractedConnections)}return{newFiles:i,skippedFiles:s,extractedEntities:n,extractedConcepts:a,extractedConnections:o,timeMs:Date.now()-l}}async query(e,t){if(!this.kb)throw new Error("KB not loaded. Call loadKB() first.");const r={llmProvider:this.llmProvider,model:this.config.llm.defaultModel,temperature:t?.temperature??this.config.wiki.queryTemperature,maxResults:t?.maxResults??this.config.wiki.maxQueryResults};return this.embeddingProvider&&(r.embeddingProvider=this.embeddingProvider,r.embeddingModel=this.config.embedding?.defaultModel),await this.kb.query(e,r)}async*queryStream(e,t){if(!this.kb)throw new Error("KB not loaded. Call loadKB() first.");const r={llmProvider:this.llmProvider,model:this.config.llm.defaultModel,temperature:t?.temperature??this.config.wiki.queryTemperature,maxResults:t?.maxResults??this.config.wiki.maxQueryResults};this.embeddingProvider&&(r.embeddingProvider=this.embeddingProvider,r.embeddingModel=this.config.embedding?.defaultModel),t?.onTokenUsage&&(r.onTokenUsage=t.onTokenUsage),t?.onEmbeddingUsage&&(r.onEmbeddingUsage=t.onEmbeddingUsage),yield*this.kb.queryStream(e,r)}async generateAllPages(){if(!this.kb)throw new Error("KB not loaded. Call loadKB() first.");await this.kb.generateWikiPages({wikiPageRepo:this.factory.getWikiPageRepository(),pathService:this.pathService,fileSystem:this.fileSystem})}async lint(){if(!this.kb)throw new Error("KB not loaded. Call loadKB() first.");return this.kb.lint()}calculateCost(e,t,r,i){return estimateCost(e,t,r,i)}getPricingTable(){return MODEL_PRICING}findModelPricing(e,t){return findPricing(e,t)}async buildEmbeddingIndexForKB(e){if(!this.kb)return void console.warn("[wiki-service] buildEmbeddingIndexForKB: KB is null, skipping");if(!this.embeddingProvider)return void console.warn("[wiki-service] buildEmbeddingIndexForKB: embeddingProvider is null/undefined, skipping");const t=this.config.paths.embeddingsPath;await this.kb.buildEmbeddingIndex({embeddingProvider:this.embeddingProvider,model:this.config.embedding.defaultModel,cachePath:t,fileSystem:this.fileSystem,...e?{onEmbeddingUsage:e}:{}})}async buildEmbeddingIndex(){await this.buildEmbeddingIndexForKB()}async saveConversation(e,t,r){const i=Conversation.create(e,t,{sources:r?.sources||[],retrieval:r?.retrieval||{entityCount:0,conceptCount:0,totalResults:0}});return await this.conversationRepo.save(i)}async listConversations(){return(await this.conversationRepo.list()).map(e=>e.getMetadata())}};init_wiki(),init_wiki_config(),init_node(),init_ollama_embedding_provider(),init_ollama_provider(),init_provider2(),init_fetch_http_client();var OpenAICompatibleProvider=class{name;baseURL;apiKey;defaultModel;customHeaders;httpClient;constructor(e){this.baseURL=e.baseURL.replace(/\/$/,""),this.name=e.providerName||"OpenAI-Compatible",e.apiKey&&(this.apiKey=e.apiKey),e.defaultModel&&(this.defaultModel=e.defaultModel),this.customHeaders=e.customHeaders||{},this.httpClient=e.httpClient||createDefaultLLMHttpClient()}async*complete(e,t,r){const i=`${this.baseURL}/chat/completions`,s=[];t.systemMessage&&s.push({role:"system",content:t.systemMessage}),s.push({role:"user",content:e});const n={model:t.model||this.defaultModel||"gpt-3.5-turbo",messages:s,stream:!0,temperature:t.temperature??.7,max_tokens:t.maxTokens??4096,stream_options:{include_usage:!0}},a={"Content-Type":"application/json",...this.customHeaders};let o;(this.apiKey||t.apiKey)&&(a.Authorization=`Bearer ${t.apiKey||this.apiKey}`);try{const e={url:i,method:"POST",headers:a,body:JSON.stringify(n)};r&&(e.signal=r),o=await this.httpClient.fetch(e)}catch(e){if("AbortError"===e.name)throw new LLMAbortError(this.name);throw new LLMConnectError(this.name,e)}if(!o.ok){const e=await o.text().catch(()=>"Unknown error");throw new LLMHttpError(this.name,o.status,`${o.statusText}: ${e}`)}if(!o.body)throw new LLMConnectError(this.name,new Error("No response body"));const l=o.body.getReader(),c=new TextDecoder;try{let e,r="",i=!1;for(;;){const{done:s,value:n}=await l.read();if(s)break;r+=c.decode(n,{stream:!0});const a=r.split("\n");r=a.pop()||"";for(const r of a){const s=r.trim();if(s&&"data: [DONE]"!==s&&s.startsWith("data: ")){const r=s.slice(6);try{const s=JSON.parse(r),n=s.choices?.[0]?.delta?.content||"",a=s.choices?.[0]?.finish_reason;if(s.usage){const r=s.model||t.model||this.defaultModel;e={promptTokens:s.usage.prompt_tokens,completionTokens:s.usage.completion_tokens,totalTokens:s.usage.total_tokens,...r?{model:r}:{}}}n&&(yield{text:n,done:!1}),a&&(i=!0)}catch(e){console.warn("Failed to parse chunk:",r)}}}}yield{text:"",done:!0,...e?{usage:e}:{}}}finally{l.releaseLock()}}async completeSync(e,t,r,i){let s="";for await(const n of this.complete(e,t,r))n.done?n.usage&&i&&i(n.usage):s+=n.text;return s.trim()}async healthCheck(){try{const e=`${this.baseURL}/models`,t={};return this.apiKey&&(t.Authorization=`Bearer ${this.apiKey}`),(await this.httpClient.fetch({url:e,method:"GET",headers:t})).ok}catch{return!1}}};init_lmstudio_provider(),init_log();var log93=getDomainLogger("desktop-wiki-adapter",{component:"interface"}),DesktopWikiAdapter=class{constructor(e,t){this.workspaceAdapter=e,this.httpClient=t}fileSystem=new NodeFileSystem;pathService=new NodePathService;cryptoService=new NodeCryptoService;async createWikiService(e,t){log93.info("Creating WikiService",{workspacePath:e,projectName:t});const r=this.workspaceAdapter.getWorkspaceAppService(),{workspace:i,project:s}=await r.loadWorkspaceAndProject(t,e),n=await i.getConfig("llm")||{},a=await i.getConfig("wiki.outputLanguage")||"en";await s.loadConfig();const o=s.getConfigValue("outputDir"),l=s.getPath();if(!o)throw new Error(`Project ${t} does not have 'outputDir' configured`);const c=createWikiConfig(o),h=s.getFilePath(c.kbPath),u=s.getFilePath(c.embeddingsPath),g=function(e,t){switch(e.type){case"lmstudio":return function(e="http://localhost:1234/v1",t,r){const i={baseURL:e,providerName:"LM Studio"};return t&&(i.defaultModel=t),r&&(i.httpClient=r),new OpenAICompatibleProvider(i)}(e.baseURL,e.defaultModel,t);case"ollama":return new OllamaProvider(e.baseURL);case"openai":if(!e.apiKey)throw new Error("OpenAI requires an API key");return function(e,t,r){const i={baseURL:"https://api.openai.com/v1",apiKey:e,providerName:"OpenAI",defaultModel:t||"gpt-4-turbo-preview"};return r&&(i.httpClient=r),new OpenAICompatibleProvider(i)}(e.apiKey,e.defaultModel,t);case"glm":if(!e.apiKey)throw new Error("GLM requires an API key");return function(e,t,r){const i={baseURL:"https://open.bigmodel.cn/api/paas/v4",apiKey:e,providerName:"GLM (智谱AI)",defaultModel:t||"glm-4"};return r&&(i.httpClient=r),new OpenAICompatibleProvider(i)}(e.apiKey,e.defaultModel,t);case"deepseek":if(!e.apiKey)throw new Error("DeepSeek requires an API key");return function(e,t,r){const i={baseURL:"https://api.deepseek.com/v1",apiKey:e,providerName:"DeepSeek",defaultModel:t||"deepseek-chat"};return r&&(i.httpClient=r),new OpenAICompatibleProvider(i)}(e.apiKey,e.defaultModel,t);case"moonshot":if(!e.apiKey)throw new Error("Moonshot requires an API key");return function(e,t,r){const i={baseURL:"https://api.moonshot.cn/v1",apiKey:e,providerName:"Moonshot (Kimi)",defaultModel:t||"moonshot-v1-8k"};return r&&(i.httpClient=r),new OpenAICompatibleProvider(i)}(e.apiKey,e.defaultModel,t);case"custom":{const r={baseURL:e.baseURL,providerName:"Custom",...e.apiKey&&{apiKey:e.apiKey},...e.defaultModel&&{defaultModel:e.defaultModel},...e.customHeaders&&{customHeaders:e.customHeaders},...t&&{httpClient:t}};return new OpenAICompatibleProvider(r)}default:throw new Error(`Unknown LLM service type: ${e.type}`)}}(n,this.httpClient);let d;if(n.embeddingModel){const e=n.embeddingType||n.type||"lmstudio",t=n.embeddingBaseUrl||n.embeddingBaseURL||n.baseUrl||n.baseURL,r=n.embeddingApiKey||n.apiKey;d=function(e,t){if(!e||"none"===e.type)return null;switch(e.type){case"lmstudio":return new OpenAICompatibleEmbeddingProvider(e.baseURL||"http://localhost:1234/v1",e.model||"text-embedding-nomic-embed-text-v2-moe",t,e.apiKey,"LMStudio");case"ollama":return new OllamaEmbeddingProvider({baseUrl:e.baseURL||"http://localhost:11434",model:e.model||"nomic-embed-text"});case"openai":if(!e.apiKey)throw new Error("OpenAI embedding requires an API key");return new OpenAICompatibleEmbeddingProvider(e.baseURL||"https://api.openai.com/v1",e.model||"text-embedding-3-small",t,e.apiKey,"OpenAI");case"glm":if(!e.apiKey)throw new Error("GLM embedding requires an API key");return new OpenAICompatibleEmbeddingProvider(e.baseURL||"https://open.bigmodel.cn/api/paas/v4",e.model||"embedding-3",t,e.apiKey,"GLM");case"deepseek":if(!e.apiKey)throw new Error("DeepSeek embedding requires an API key");return new OpenAICompatibleEmbeddingProvider(e.baseURL||"https://api.deepseek.com/v1",e.model||"deepseek-embedding",t,e.apiKey,"DeepSeek");case"moonshot":if(!e.apiKey)throw new Error("Moonshot embedding requires an API key");return new OpenAICompatibleEmbeddingProvider(e.baseURL||"https://api.moonshot.cn/v1",e.model||"moonshot-v1-embedding",t,e.apiKey,"Moonshot");case"custom":return new OpenAICompatibleEmbeddingProvider(e.baseURL||"",e.model||"",t,e.apiKey,"Custom");default:throw new Error(`Unknown embedding service type: ${e.type}`)}}({type:e,baseURL:t,model:n.embeddingModel,apiKey:r},this.httpClient),log93.info("Embedding provider created",{type:e,model:n.embeddingModel,baseURL:t})}else log93.info("Embedding provider not configured (no embeddingModel in llm config)");const p=new NodeKBRepository(h,this.fileSystem,this.pathService),m=new NodeWikiPageRepository(o,this.fileSystem,this.pathService),f=new NodeConversationRepository(c.conversationsDir,this.fileSystem,this.pathService),y=new WikiFactory({kbRepo:p,wikiPageRepo:m}),w={llm:{provider:g,defaultModel:n.model||g.defaultModel||"default",defaultMaxTokens:n.maxTokens||32768},wiki:{outputLanguage:a,ingestTemperature:.3,queryTemperature:.7,maxQueryResults:10},infrastructure:{fileSystem:this.fileSystem,pathService:this.pathService,cryptoService:this.cryptoService,conversationRepo:f},paths:{kbPath:h,embeddingsPath:u,wikiDir:o,conversationsDir:c.conversationsDir,sourcePath:l}};return d?(w.embedding={provider:d,defaultModel:n.embeddingModel,cacheEnabled:!0},log93.info("Embedding configured in WikiService",{model:n.embeddingModel,embeddingsPath:u})):console.warn(`[wiki-adapter] No embedding provider (llmConfig.embeddingModel=${n.embeddingModel})`),log93.info("WikiService created successfully",{kbPath:h,embeddingsPath:u,wikiDir:o,conversationsDir:c.conversationsDir}),new WikiService(y,w)}async listMarkdownFiles(e){const t=[],r=await this.fileSystem.readdir(e);for(const i of r){const r=this.pathService.join(e,i);if((await this.fileSystem.stat(r)).isDirectory()){const e=await this.listMarkdownFiles(r);t.push(...e)}else i.endsWith(".md")&&t.push(r)}return t}async getBasename(e){return this.pathService.basename(e)}};function createObsidianWorkspaceService(){const e=new DesktopWorkspaceAdapter;return new ObsidianWorkspaceService(e)}function createObsidianAuthService(e){const t=new DesktopIdentityAdapter;return new ObsidianAuthService(e,t)}function createObsidianLicenseService(e){const t=new DesktopIdentityAdapter;return new ObsidianLicenseService(e,t)}function createObsidianGlobalConfigService(){const e=new DesktopWorkspaceAdapter;return new ObsidianGlobalConfigService(e)}function createObsidianProjectConfigService(){const e=new DesktopWorkspaceAdapter;return new ObsidianProjectConfigService(e)}function createObsidianProjectService(){const e=new DesktopWorkspaceAdapter;return new ObsidianProjectService(e)}function createObsidianBuildService(){const e=new DesktopWorkspaceAdapter;return new ObsidianBuildService(e)}function createObsidianServeService(e){const t=new DesktopWorkspaceAdapter;let r;if(e){const i=new NodeManifestRepository,s=new PublisherFactory(i,e),n=t.getWorkspaceAppService();r=new PublishAppService(s,n)}return new ObsidianServeService(t,r)}function createObsidianPublishService(e){const t=new DesktopWorkspaceAdapter,r=new NodeManifestRepository,i=new PublisherFactory(r,e),s=t.getWorkspaceAppService(),n=new PublishAppService(i,s);return new ObsidianPublishService(n,t)}function createObsidianDomainService(e){const t=new DesktopIdentityAdapter;return new ObsidianDomainService(e,t)}function createObsidianWikiService(e){const t=new DesktopWorkspaceAdapter,r=new DesktopWikiAdapter(t,e);return new ObsidianWikiService(r)}init_publish2(),init_publish(),init_infrastructure(),init_wiki();export{AutoIDGenerator,FetchHttpClient,IdentityAppService,IncrementalBuildCoordinator,LogLevel,Logger,ObsidianBuildService,ObsidianDomainService,ObsidianProjectService,ObsidianPublishService,ObsidianServeService,Project,PublishAppService,Workspace,WorkspaceAppService,calculateProgress,createDefaultLLMHttpClient,createIdentityService,createObsidianAuthService,createObsidianBuildService,createObsidianDomainService,createObsidianGlobalConfigService,createObsidianIdentityService,createObsidianLicenseService,createObsidianProjectConfigService,createObsidianProjectService,createObsidianPublishService,createObsidianServeService,createObsidianWikiService,createObsidianWorkspaceAppService,createObsidianWorkspaceService,createProgressEvent,createPublishAppService,createWorkspaceAppService,createWorkspaceFactory,generateStaticSite,getComponentLogger,getDomainLogger,getIdentityService,initLogger,processSSG,processSSGParallel,processSSGWithProgress,setGlobalLogLevel,startIncrementalBuild};
2
+ var ConfigError,Config,DefaultRootConfig,Root,__defProp=Object.defineProperty,__getOwnPropNames=Object.getOwnPropertyNames,__require=(e=>"undefined"!=typeof require?require:"undefined"!=typeof Proxy?new Proxy(e,{get:(e,t)=>("undefined"!=typeof require?require:e)[t]}):e)(function(e){if("undefined"!=typeof require)return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')}),__esm=(e,t)=>function(){return e&&(t=(0,e[__getOwnPropNames(e)[0]])(e=0)),t},__export=(e,t)=>{for(var r in t)__defProp(e,r,{get:t[r],enumerable:!0})},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,r,i,s,n,a,o,l,c){this.configSourceFs=e,this.provider=t,this.root=r,this.dir=i,this.module=s,this.service=n,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,lang,languages,DefaultLanguageConfig,Language,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),{})}}),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}}),init_lang=__esm({"pkg/lang/index.ts"(){init_data(),init_service3(),init_service3(),serviceInstance||(serviceInstance=new DefaultLanguageService),lang=serviceInstance,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[r,i]of Object.entries(this.configs))i.weight<t&&(t=i.weight,e=r);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 r=this.configs[t];if(!r)throw new Error(`Language "${t}" not found`);return r.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[r,i]of Object.entries(e.taxonomies))"string"==typeof i&&(t[r]=i);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,r]of Object.entries(this.taxonomies))if(r===e)return t}getSingularForms(){return Object.keys(this.taxonomies)}getPluralForms(){return Object.values(this.taxonomies)}setupViews(){this.views=function(e){const t=[];for(const[r,i]of Object.entries(e))t.push({singular:r,plural:i,pluralTreeKey:cleanTreeKey(i)});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,r]of Object.entries(this.socialConfig.userConfig)){const i=this.getPlatformTemplate(t);i?e.push({id:t,title:i.title,url:r.link}):e.push({id:t,title:t.charAt(0).toUpperCase()+t.slice(1),url:r.link})}return e}getSocialLink(e){const t=this.socialConfig.userConfig[e];if(!t)return;const r=this.getPlatformTemplate(e);return r?{id:e,title:r.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 DEFAULT_PUBLISH_DIR,Dir,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()}}}});import path from"path";var DefaultConfigProvider,ConfigLoader,init_dir=__esm({"internal/domain/config/entity/dir.ts"(){DEFAULT_PUBLISH_DIR="public",Dir=class{workingDir;themesDir;publishDir;constructor(e,t,r=DEFAULT_PUBLISH_DIR){this.workingDir=e,this.themesDir=t,this.publishDir=r}getWorkingDir(){return path.resolve(this.workingDir)}getThemesDir(){return path.resolve(this.themesDir)}getThemesCacheDir(){return path.resolve(this.themesDir,".cache")}getPublishDir(){return path.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[r,i]of Object.entries(e))t[r.toLowerCase()]=i;return t}getNestedKeyAndMap(e,t){let r;this.keyCache.has(e)?r=this.keyCache.get(e):(r=e.split("."),this.keyCache.set(e,r));let i=this.root;for(let e=0;e<r.length-1;e++){const s=r[e];if(!(s in i)){if(!t)return["",null];i[s]={}}const n=i[s];if("object"!=typeof n||null===n)return["",null];i=n}return[r[r.length-1],i]}getString(e){const t=this.get(e);return String(t||"")}getInt(e){const t=this.get(e),r=Number(t);return isNaN(r)?0:Math.floor(r)}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[r,i]of Object.entries(t))e[r]=String(i);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,r]=this.getNestedKeyAndMap(e.toLowerCase(),!1);return null!==r?r[t]:void 0}set(e,t){const r=e.toLowerCase();if(""===r)return void(t&&"object"==typeof t?Object.assign(this.root,this.prepareParams(t)):this.root[r]=t);const[i,s]=this.getNestedKeyAndMap(r,!0);null!==s&&(i in s&&"object"==typeof s[i]&&"object"==typeof t&&null!==t?Object.assign(s[i],t):s[i]=t)}keys(){return Object.keys(this.root)}merge(e,t){const r=e.toLowerCase();if(""===r)return void(t&&"object"==typeof t&&Object.assign(this.root,this.prepareParams(t)));const[i,s]=this.getNestedKeyAndMap(r,!0);null!==s&&(i in s&&"object"==typeof s[i]&&"object"==typeof t&&null!==t?Object.assign(s[i],t):s[i]=t)}setDefaults(e){const t=this.prepareParams(e);for(const[e,r]of Object.entries(t))e in this.root||(this.root[e]=r)}setDefaultMergeStrategy(){}walkParams(e){const t=r=>{if(r&&"object"==typeof r&&!Array.isArray(r)){if(e(r))return!0;for(const e of Object.values(r))if(t(e))return!0}return!1};t(this.root)}isSet(e){const[t,r]=this.getNestedKeyAndMap(e.toLowerCase(),!1);return null!==r&&t in r}}}});import*as path2 from"path";var ConfigSourceDescriptor,init_loader=__esm({"internal/domain/config/factory/loader.ts"(){init_provider(),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 r;r=path2.isAbsolute(e)?e:path2.join(t,e);let i="";if(""!==path2.extname(e)&&await this.fileExists(r)&&(i=r),""===i)throw new Error("Unable to locate config file or config directory.");const s=await this.loadConfigFromFile(i);this.cfg.set("",s)}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(),r=await t.open(e);try{const e=new Uint8Array(1048576),{bytesRead:t}=await r.read(e),i=(new TextDecoder).decode(e.slice(0,t));try{return JSON.parse(i)}catch{return{}}}finally{await r.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}}}});import*as path3 from"path";async function loadConfigWithParams(e,t,r,i,s={}){const n={workingDir:path3.resolve(r),modulesDir:path3.resolve(i),publishDir:path3.resolve(DEFAULT_PUBLISH_DIR),cacheDir:""};n.cacheDir=await async function(e,t){if(""!==t)return t;const r=process.env.HOME||process.env.USERPROFILE||"",i=path3.join(r,".cache","mdf");try{return await e.mkdirAll(i,493),i}catch{return path3.join("/tmp","hugo-cache")}}(e,n.cacheDir);const a=new ConfigLoader(function(e,t){return new ConfigSourceDescriptor(e,t)}(e,t),n);try{const t=await a.loadConfigByDefault();for(const[e,r]of Object.entries(s))t.set(e,r);const r=path3.resolve(t.get("publishDir")||DEFAULT_PUBLISH_DIR);return await e.mkdirAll(r,511),function(e,t,r,i,s,n,a,o,l,c){return new Config(e,t,r,i,s,n,a,o,l,c)}(e,t,function(e,t={}){const r=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(r,t)}(t.get(""),t.getParams("params")),function(e,t,r){return new Dir(e,t,r)}(n.workingDir,n.modulesDir,r),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[r,i]of Object.entries(e))if(i&&"object"==typeof i){const e=i;e.link&&(t.userConfig[r]={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[r,i]of Object.entries(e)){const s=i,n=languages.getNameByCode(r)||r;t[r]={languageCode:r,languageName:n,title:s.title||e.title||"",weight:void 0!==s.weight?s.weight:0,contentDir:s.contentDir||"content",disabled:void 0!==s.disabled&&s.disabled,params:s.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,Mount,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()}}),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")}});import*as path4 from"path";var LogLevel,Logger,init_mount=__esm({"internal/domain/module/vo/mount.ts"(){Mount=class e{constructor(e,t,r=""){this.sourcePath=e,this.targetPath=t,this.language=r}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"(){LogLevel=(e=>(e.DEBUG="debug",e.INFO="info",e.WARN="warn",e.ERROR="error",e.FATAL="fatal",e))(LogLevel||{})}});import*as util from"util";var globalLoggerManager,init_logger=__esm({"pkg/log/logger.ts"(){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"],r=t.indexOf(this.config.level);return t.indexOf(e)>=r}getCaller(){if(!this.config.enableCaller)return;const e=(new Error).stack;if(!e)return;const t=e.split("\n")[4];if(!t)return;const r=t.match(/at .* \((.+):(\d+):(\d+)\)/);if(r){const[,e,t]=r;return`${e.split("/").pop()}:${t}`}const i=t.match(/at (.+):(\d+):(\d+)/);if(i){const[,e,t]=i;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 r={level:e,timestamp:(new Date).toISOString(),message:t,...this.fields},i=this.getCaller();i&&(r.caller=i);const s=this.config.jsonFormat?JSON.stringify(r):this.formatPlainText(r);"error"===e||"fatal"===e?process.stderr.write(s+"\n"):process.stdout.write(s+"\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 r=Object.keys(e).filter(e=>!["level","timestamp","message","caller"].includes(e)).map(t=>`${t}=${JSON.stringify(e[t])}`).join(" ");return r&&t.push(r),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 r=new e(this.config);return r.fields={...this.fields,...t},r}}}}),init_http=__esm({"pkg/log/http.ts"(){}});function initLogger(e){globalLoggerManager.setGlobalConfig(e)}function getDomainLogger(e,t){return globalLoggerManager.getLogger(e,t)}function getComponentLogger(e,t,r){return globalLoggerManager.getComponentLogger(e,t,r)}function setGlobalLogLevel(e){globalLoggerManager.setLogLevel(e)}var 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 r=e+(t?JSON.stringify(t):"");if(!this.loggers.has(r)){const s=(i=this.globalConfig,new Logger(i)),n={domain:e,...t},a=s.with(n);this.loggers.set(r,a)}var i;return this.loggers.get(r)}getComponentLogger(e,t,r){const i={component:t,...r};return this.getLogger(e,i)}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")}});import*as path5 from"path";import*as http from"http";import*as https from"https";function newHttpClient(e,t,r,i){return i||new NodeHttpClient(e,t,r)}var log2,JsZipExtractor,WebZipExtractor,init_httpclient=__esm({"internal/domain/module/vo/httpclient.ts"(){init_type2(),init_log(),log=getDomainLogger("module",{component:"httpclient"}),NodeHttpClient=class{constructor(e,t=3e4,r={}){this.fs=e,this.timeout=t,this.headers=r}defaultTimeout=3e4;defaultHeaders={"User-Agent":"MDFriday-CLI/1.0.0"};async download(e,t,r){return new Promise((i,s)=>{try{const n=new URL(e),a="https:"===n.protocol,o=a?https:http,l={...this.defaultHeaders,...this.headers,...r?.headers},c={hostname:n.hostname,port:n.port||(a?443:80),path:n.pathname+n.search,method:"GET",headers:l,timeout:r?.timeout||this.timeout},h=o.request(c,async e=>{if(!e.statusCode||e.statusCode<200||e.statusCode>=300)return void s(new ModuleError(`HTTP ${e.statusCode}: ${e.statusMessage}`,"HTTP_ERROR"));const n=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 h=await this.fs.create(t),u=[];e.on("data",e=>{if(u.push(e),a+=e.length,r?.onProgress&&n>0){const e=Date.now(),t=Math.round(a/n*100);if(e-o>=100&&t!==l||t-l>=5){const i={loaded:a,total:n,percentage:t};try{r.onProgress(i),l=t}catch(e){log.error(`Progress callback error: ${e}`)}o=e}}}),e.on("end",async()=>{try{const e=Buffer.concat(u),t=new Uint8Array(e);if(await h.write(t),await h.sync(),await h.close(),r?.onProgress&&n>0){const e={loaded:n,total:n,percentage:100};try{r.onProgress(e)}catch(e){log.warn(`Progress callback error: ${e}`)}}i()}catch(e){const t=e instanceof Error?e.message:String(e);s(new ModuleError(`File write failed: ${t}`,"WRITE_FAILED"))}}),e.on("error",e=>{log.error(`Response error: ${e.message}`),s(new ModuleError(`Download failed: ${e.message}`,"DOWNLOAD_FAILED"))})}catch(e){const t=e instanceof Error?e.message:String(e);s(new ModuleError(`File system error: ${t}`,"FS_ERROR"))}});h.on("error",e=>{log.error("Request error:",e),s(new ModuleError(`Request failed: ${e.message}`,"REQUEST_FAILED"))}),h.on("timeout",()=>{h.destroy(),log.error(`Request timeout for ${e}`),s(new ModuleError("Request timeout","TIMEOUT"))}),h.end()}catch(e){const t=e instanceof Error?e.message:String(e);s(new ModuleError(`Download failed: ${t}`,"DOWNLOAD_FAILED"))}})}async get(e,t){return new Promise((r,i)=>{try{const s=new URL(e),n="https:"===s.protocol,a=n?https:http,o={...this.defaultHeaders,...this.headers,...t?.headers},l={hostname:s.hostname,port:s.port||(n?443:80),path:s.pathname+s.search,method:"GET",headers:o,timeout:t?.timeout||this.timeout},c=a.request(l,e=>{const t=[],s={};Object.entries(e.headers).forEach(([e,t])=>{s[e]=Array.isArray(t)?t.join(", "):t||""}),e.on("data",e=>{t.push(e)}),e.on("end",()=>{const i=Buffer.concat(t),n=i.buffer.slice(i.byteOffset,i.byteOffset+i.byteLength);r({data:n,headers:s,status:e.statusCode||0})}),e.on("error",e=>{i(new ModuleError(`Response error: ${e.message}`,"RESPONSE_ERROR"))})});c.on("error",e=>{i(new ModuleError(`GET request failed: ${e.message}`,"REQUEST_FAILED"))}),c.on("timeout",()=>{c.destroy(),i(new ModuleError("GET request timeout","TIMEOUT"))}),c.end()}catch(e){const t=e instanceof Error?e.message:String(e);i(new ModuleError(`GET request failed: ${t}`,"REQUEST_FAILED"))}})}}}});import JSZip from"jszip";import*as path6 from"path";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 log3,FsModuleCache,init_zipextractor=__esm({"internal/domain/module/vo/zipextractor.ts"(){init_type2(),init_log(),log2=getDomainLogger("module",{component:"zipextractor"}),JsZipExtractor=class{constructor(e){this.fs=e}async extract(e,t){try{const r=await this.fs.open(e),i=(await r.stat()).size(),s=new Uint8Array(i),n=await r.read(s);await r.close(),await this.extractZipData(n.buffer,t)}catch(t){const r=t instanceof Error?t.message:String(t);throw log2.error(`ZIP extraction failed for ${e}: ${r}`),new ModuleError(`ZIP extraction failed: ${r}`,"EXTRACTION_FAILED")}}async list(e){try{const t=await this.fs.open(e),r=await t.stat(),i=new Uint8Array(r.size()),s=await t.read(i);return await t.close(),await this.listZipContents(s.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 r=new JSZip,i=await r.loadAsync(e),s=[];i.forEach((e,t)=>{t.dir||s.push(e)});const n=[];let a=0;i.forEach((e,r)=>{n.push(this.extractSingleEntry(e,r,t).then(()=>{a++}))}),await Promise.all(n)}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,r){const i=path6.join(r,e);if(t.dir)await this.fs.mkdirAll(i,493);else{const e=path6.dirname(i);e!==r&&await this.fs.mkdirAll(e,493);const s=await t.async("uint8array"),n=await this.fs.create(i);await n.write(s),await n.close()}}async listZipContents(e){try{const t=new JSZip,r=await t.loadAsync(e),i=[];return r.forEach(e=>{i.push(e)}),i}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")}}}}});import*as path7 from"path";function newModuleCache(e,t){return new FsModuleCache(e,t)}var Module2,ProjectModule,init_cache=__esm({"internal/domain/module/vo/cache.ts"(){init_type2(),init_log(),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),r=await this.fs.open(t),i=await r.stat(),s=new Uint8Array(i.size());await r.read(s),await r.close();const n=(new TextDecoder).decode(s);return JSON.parse(n)}catch(t){if(t.message?.includes("ENOENT")||t.message?.includes("no such file"))return log3.info(`Cache miss: ${e}`,t),null;const r=t instanceof Error?t.message:String(t);throw log3.error(`Cache read error for ${e}: ${r}`),new ModuleError(`Failed to read cache: ${r}`,"CACHE_READ_FAILED")}}async set(e,t){try{await this.fs.mkdirAll(this.cacheDir,493);const r=this.getCacheFilePath(e),i=JSON.stringify(t,null,2),s=(new TextEncoder).encode(i),n=await this.fs.create(r);await n.write(s),await n.sync(),await n.close()}catch(t){const r=t instanceof Error?t.message:String(t);throw log3.error(`Cache write error for ${e}: ${r}`),new ModuleError(`Failed to write cache: ${r}`,"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 r=t instanceof Error?t.message:String(t);throw log3.error(`Cache delete error for ${e}: ${r}`),new ModuleError(`Failed to delete cache: ${r}`,"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 r of e)try{const e=path7.join(this.cacheDir,r);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[]}}}}});import*as path8 from"path";function newModule2(e,t,r,i){return new Module2(e,t,r,i||null,!1)}var Lang,init_module3=__esm({"internal/domain/module/vo/module.ts"(){init_type2(),init_mount(),Module2=class e{constructor(e,t,r,i=null,s=!1){this.fs=e,this.absoluteDir=t,this.modulePath=r,this.parentModule=i,this.mountDirs=[],this.metadata=null,this.isProject=s}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 r=path8.join(this.absoluteDir,e);try{(await this.fs.stat(r)).isDir()&&t.push({sourcePath:e,targetPath:e})}catch(e){}}this.mountDirs=t.map(e=>{return t=e.sourcePath,r=e.targetPath,new Mount(t,r);var t,r})}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 r of t)r instanceof Mount&&r.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()}}}});import path9 from"path";var Themes,log4,Modules,init_lang2=__esm({"internal/domain/module/entity/lang.ts"(){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(path9.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 r=e.indexOf("?");if(-1===r)return e;const i=e.substring(0,r),s=new URLSearchParams(e.substring(r+1));s.delete("version");const n=s.toString();return n?`${i}?${n}`:i}}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()))}}}});import{parse as parseToml}from"smol-toml";import*as path10 from"path";function newModules(e,t,r,i){return new Modules(e,t,r,i)}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(),log4=getDomainLogger("module",{component:"modules"}),Modules=class{constructor(e,t,r,i){var s;this.info=e,this.httpClient=t,this.zipExtractor=r,this.moduleCache=i,this.projectModule=function(e){const t=e.osFs(),r=e.projDir(),i=e.defaultLanguageKey(),s=new Module2(t,r,"project-root",null,!0),n=new ProjectModule(s);n.applyDefaultMounts(),i&&n.setDefaultLanguage(i);const a=e.otherLanguageKeys();for(const t of a)try{const r=e.getRelDir(ComponentFolderContent,t);if(r&&""!==r){const e=new Mount(r,ComponentFolderContent,t);n.appendMount(e)}}catch(e){console.warn(`Failed to get relative directory for language ${t}:`,e)}return n}(this.info),this.lang=(s=this.all(),new Lang(s))}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 r=0;r<t.length;r++){const i=t[r],{cleanUrl:s,version:n}=this.parseVersionFromImportPath(i);let a=i;"latest"===n&&(a=await this.resolveLatestVersion(i)),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),r=t.searchParams.get("version")||"latest";return t.searchParams.delete("version"),{cleanUrl:t.toString(),version:r}}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 r=this.themesCache.get(t);if(!r){const e=await this.httpClient.get(t),i=(new TextDecoder).decode(e.data),s=JSON.parse(i);r=Themes.fromJson(s),this.themesCache.set(t,r)}const i=r.resolveLatestVersion(e);return i!==e?log4.info(`Resolved latest version: ${e} -> ${i}`):log4.warn(`Could not resolve latest version for ${e}, using original path`),i}catch(t){return log4.error(`Failed to resolve latest version for ${e}:`,t),e}}async downloadModule(e,t){try{let r=e.version;if("latest"===e.version){const t=await this.resolveLatestVersion(e.path),{version:i}=this.parseVersionFromImportPath(t);r=i}const i=await this.moduleCache.get(e.path);if(i&&"completed"===i.downloadStatus&&this.isCacheValidForVersion(i.version,r)){const t=await this.createModuleFromCache(e,i);if(await t.exists())return log4.info(`Using cached module ${e.path} version ${i.version}`),t}i&&"completed"===i.downloadStatus&&!this.isCacheValidForVersion(i.version,r)&&log4.info(`Cache version mismatch for ${e.path}: cached=${i.version}, requested=${r||"latest"}`);const s=this.getModuleDir(e.path),n=path10.join(s,"module.zip"),a={path:e.path,version:e.version||"latest",url:e.url,dir:s,downloadStatus:"downloading",downloadedAt:new Date};await this.moduleCache.set(e.path,a);try{const r=this.addTimestampToUrl(e.url);await this.httpClient.download(r,n,{onProgress:e=>{t?.({percentage:e.percentage})}}),await this.zipExtractor.extract(n,s),a.downloadStatus="completed",a.downloadedAt=new Date;try{const e=await this.info.osFs().stat(n);a.size=e.size()}catch(e){}try{await this.info.osFs().remove(n)}catch(e){}await this.moduleCache.set(e.path,a);const i=newModule2(this.info.osFs(),s,e.path);return i.setMetadata(a),await i.applyMounts(e),i}catch(t){a.downloadStatus="failed",await this.moduleCache.set(e.path,a);const r=t instanceof Error?t.message:String(t);throw new ModuleError(`Failed to download module ${e.path}: ${r}`,"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,r){try{if(this.downloadedModules.has(t))return;const{cleanUrl:e,version:i}=this.parseVersionFromImportPath(t),s={path:t,url:this.getDownloadUrl(e),...i&&{version:i}},n=await this.downloadModule(s,r);this.modules.push(n),this.downloadedModules.add(t);try{const e=await this.parseThemeToml(n);for(const t of e){if(this.downloadedModules.has(t)){log4.info(`Module ${t} already downloaded, skipping`);continue}log4.info(`Recursively downloading module dependency: ${t}`);const e=t,{cleanUrl:i,version:s}=this.parseVersionFromImportPath(e);let a=e;"latest"===s&&(a=await this.resolveLatestVersion(e)),await this.addModule(n,a,e=>{r?.({percentage:.5*e.percentage})})}}catch(e){const r=e instanceof Error?e.message:String(e);log4.warn(`Failed to process recursive imports for module ${t}: ${r}`)}}catch(e){const r=e instanceof Error?e.message:String(e);throw new ModuleError(`Failed to add module ${t}: ${r}`,"ADD_MODULE_FAILED")}}async createModuleFromCache(e,t){const r=newModule2(this.info.osFs(),t.dir,e.path);return r.setMetadata(t),await r.applyMounts(e),r}getModuleDir(e){const t=e.replace(/[/\\:*?"<>|]/g,"_").replace(/^_+|_+$/g,"");return path10.join(this.info.moduleDir(),t)}getDownloadUrl(e){return e}isCacheValidForVersion(e,t){return!t||e===t}addTimestampToUrl(e){try{const t=new URL(e),r=Date.now().toString();return t.searchParams.set("_t",r),t.toString()}catch(t){const r=e.includes("?")?"&":"?";return`${e}${r}_t=${Date.now()}`}}getModuleByPath(e){return this.modules.find(t=>t.path()===e)||null}isModuleDownloaded(e){return this.downloadedModules.has(e)}async getModuleStatus(e){const t=await this.moduleCache.get(e);return t?.downloadStatus||"pending"}async removeModule(e){try{const t=this.modules.findIndex(t=>t.path()===e);if(t>=0){const r=this.modules[t];try{await this.info.osFs().removeAll(r.dir())}catch(e){}this.modules.splice(t,1),this.downloadedModules.delete(e),await this.moduleCache.delete(e)}}catch(t){const r=t instanceof Error?t.message:String(t);throw new ModuleError(`Failed to remove module ${e}: ${r}`,"REMOVE_MODULE_FAILED")}}async clearAll(){try{for(const e of this.modules)try{await this.info.osFs().removeAll(e.dir())}catch(e){}this.modules=[],this.downloadedModules.clear(),await this.moduleCache.clear()}catch(e){const t=e instanceof Error?e.message:String(e);throw new ModuleError(`Failed to clear modules: ${t}`,"CLEAR_MODULES_FAILED")}}getSourceLang(e){return this.lang.getSourceLang(e)}async parseThemeToml(e){try{const t=path10.join(e.dir(),"theme.toml");try{if((await this.info.osFs().stat(t)).isDir())return[]}catch(e){return[]}let r;try{const e=await this.info.osFs().open(t);try{const t=[],i=new Uint8Array(4096);for(;;){const r=await e.read(i);if(0===r.bytesRead)break;t.push(i.slice(0,r.bytesRead))}const s=t.reduce((e,t)=>e+t.length,0),n=new Uint8Array(s);let a=0;for(const e of t)n.set(e,a),a+=e.length;r=new TextDecoder("utf-8").decode(n)}finally{await e.close()}}catch(t){const r=t instanceof Error?t.message:String(t);return log4.warn(`Failed to read theme.toml for module ${e.path()}: ${r}`),[]}const i=parseToml(r);return i.module?.imports?(log4.info(`Found ${i.module.imports.length} module imports in ${e.path()}/theme.toml`),i.module.imports.map(e=>e.path)):[]}catch(t){const r=t instanceof Error?t.message:String(t);return log4.warn(`Failed to parse theme.toml for module ${e.path()}: ${r}`),[]}}}}}),init_module5=__esm({"internal/domain/module/factory/module.ts"(){init_module4(),init_type2(),init_httpclient(),init_zipextractor(),init_cache(),init_log(),log5=getDomainLogger("module",{component:"factory"})}}),init_module6=__esm({"internal/domain/module/index.ts"(){init_type2(),init_type2(),init_mount(),init_httpclient(),init_zipextractor(),init_cache(),init_module3(),init_module4(),init_module5()}}),init_type3=__esm({"internal/domain/fs/type.ts"(){FsError=class extends Error{constructor(e,t){super(e),this.code=t,this.name="FsError"}},ErrFileClosed=new FsError("File is closed","FILE_CLOSED"),new FsError("out of range","OUT_OF_RANGE"),new FsError("too large","TOO_LARGE"),ErrFileNotFound=new FsError("file not found","FILE_NOT_FOUND"),new FsError("file exists","FILE_EXISTS"),new FsError("destination exists","DESTINATION_EXISTS"),ErrSkipDir=new Error("skip directory"),new FsError("walkway already walked","ALREADY_WALKED"),ErrNoFilesystems=new(OverlayFsError=class extends FsError{constructor(e,t){super(e,t),this.name="OverlayFsError"}})("no filesystems to write to","NO_FILESYSTEMS"),new OverlayFsError("operation not supported","OPERATION_NOT_SUPPORTED")}}),init_originfs=__esm({"internal/domain/fs/entity/originfs.ts"(){OriginFs=class{source;origin;publishDir;constructor(e,t,r){this.source=e,this.origin=t,this.publishDir=r}getSource(){return this.source}getOrigin(){return this.origin}publish(){return this.publishDir}}}});function newFileMeta(e,t){return new FileMeta(e,t)}var FileInfo,init_filemeta=__esm({"internal/domain/fs/vo/filemeta.ts"(){init_log(),getDomainLogger("fs",{component:"filemeta"}),FileMeta=class{filename;componentRoot;componentDir;openFunc;constructor(e="",t=null){this.filename=e,this.componentRoot="",this.componentDir="",this.openFunc=t}fileName(){return this.filename}relativeFilename(){if(""===this.componentRoot)return this.filename;const e=this.filename.indexOf(this.componentRoot);if(-1===e)throw new Error(`filename ${this.filename} has no root ${this.componentRoot}`);let t=this.filename.substring(e+this.componentRoot.length);return t.startsWith("/")||(t="/"+t),t}component(){return this.componentDir}root(){return this.componentRoot}async open(){if(null===this.openFunc)throw new Error("OpenFunc not set");return await this.openFunc()}setFileName(e){this.filename=e}setComponentRoot(e){this.componentRoot=e}setComponentDir(e){this.componentDir=e}setOpenFunc(e){this.openFunc=e}merge(e){e&&(e.filename&&!this.filename&&(this.filename=e.filename),e.componentRoot&&!this.componentRoot&&(this.componentRoot=e.componentRoot),e.componentDir&&!this.componentDir&&(this.componentDir=e.componentDir),e.openFunc&&!this.openFunc&&(this.openFunc=e.openFunc))}}}});function newFileInfo(e,t){const r=newFileMeta(t),i=new FileInfo(e,r);return isMetaProvider(e)&&i.meta().merge(e.meta()),i}function newFileInfoWithMeta(e,t){const r=new FileInfo(e,t);return isMetaProvider(e)&&r.meta().merge(e.meta()),r}function isMetaProvider(e){return e&&"function"==typeof e.meta}var File,init_fileinfo=__esm({"internal/domain/fs/vo/fileinfo.ts"(){init_filemeta(),FileInfo=class{fileInfo;_fileMeta;constructor(e,t){this.fileInfo=e,this._fileMeta=t}meta(){return this._fileMeta}type(){return this.fileInfo.mode()}info(){return this.fileInfo}setMeta(e){this._fileMeta=e}name(){return this.fileInfo.name()}size(){return this.fileInfo.size()}mode(){return this.fileInfo.mode()}modTime(){return this.fileInfo.modTime()}isDir(){return this.fileInfo.isDir()}sys(){return this.fileInfo.sys()}fileName(){return this._fileMeta.fileName()}relativeFilename(){return this._fileMeta.relativeFilename()}component(){return this._fileMeta.component()}root(){return this._fileMeta.root()}async open(){return await this._fileMeta.open()}}}});import*as path11 from"path";var DirFile,BaseFs,init_file=__esm({"internal/domain/fs/vo/file.ts"(){init_filemeta(),init_fileinfo(),File=class{file;fileMeta;fs;_isDir;constructor(e,t,r,i=!1){this.file=e,this.fileMeta=t,this.fs=r,this._isDir=i}isNop(){return null===this.file}async close(){if(null!==this.file)return await this.file.close()}async readDir(e){const t=[];if(this._isDir&&this.file){const r=await this.file.readdir(e);for(const e of r){const r=this.joinPath(this.fileMeta.fileName(),e.name()),i=newFileMeta(r,async()=>await this.fs.open(r));i.merge(this.fileMeta);const s=newFileInfo(e,r);s.setMeta(i),t.push(s)}}return t}meta(){return this.fileMeta}joinPath(e,t){return e.endsWith("/")?e+t:e+"/"+t}async read(e){if(null===this.file)throw new Error("File is null");return await this.file.read(e)}async readAt(e,t){if(null===this.file)throw new Error("File is null");return await this.file.readAt(e,t)}async seek(e,t){if(null===this.file)throw new Error("File is null");return await this.file.seek(e,t)}async write(e){if(null===this.file)throw new Error("File is null");return await this.file.write(e)}async writeAt(e,t){if(null===this.file)throw new Error("File is null");return await this.file.writeAt(e,t)}name(){return path11.basename(this.fileMeta.fileName())}async readdir(e){if(null===this.file)throw new Error("File is null");return await this.readDir(e)}async readdirnames(e){if(null===this.file)throw new Error("File is null");return await this.file.readdirnames(e)}async stat(){if(null===this.file)throw new Error("File is null");return await this.file.stat()}async sync(){if(null!==this.file)return await this.file.sync()}async truncate(e){if(null===this.file)throw new Error("File is null");return await this.file.truncate(e)}async writeString(e){if(null===this.file)throw new Error("File is null");return await this.file.writeString(e)}}}}),init_dir2=__esm({"internal/domain/fs/vo/dir.ts"(){init_file(),DirFile=class extends File{virtualOpener;filter;constructor(e,t=null,r=null){super(e.isNop()?null:e,e.meta(),e.fs,!0),this.virtualOpener=t,this.filter=r}async readDir(e){if(!this.isNop()){let t=await super.readDir(e);return null!==this.filter&&(t=await this.filter(t)),t}return await this.readVirtualDir()}async readVirtualDir(){if(null!==this.virtualOpener)return await this.virtualOpener();throw new Error("virtual dir opener not found")}setFilter(e){this.filter=e}setVirtualOpener(e){this.virtualOpener=e}getFilter(){return this.filter}getVirtualOpener(){return this.virtualOpener}}}});import*as path12 from"path";function newBaseFs(e,t){return new BaseFs(e,t)}var log8,Walkway,init_basefs=__esm({"internal/domain/fs/entity/basefs.ts"(){init_filemeta(),init_fileinfo(),init_file(),init_dir2(),init_log(),getDomainLogger("fs",{component:"basefs"}),BaseFs=class{fs;roots;constructor(e,t){this.fs=e,this.roots=t}toAbsolutePath(e){if(0===this.roots.length)return e;const t=this.roots[0];return""===e?t:path12.isAbsolute(e)?e.startsWith(t)?e:path12.join(t,e.substring(1)):path12.join(t,e)}isSameRootedPath(e){const t=this.roots[0];return e.startsWith(path12.join(t,path12.sep))||e===t}async stat(e){const t=this.toAbsolutePath(e);if(!this.isSameRootedPath(t))throw new Error(`path ${e} is outside of the BaseFs root`);try{const r=await this.fs.stat(t);if(r.isDir()){const i=newFileInfo(r,t);return i.meta().setOpenFunc(async()=>await this.openDir(e)),i}const i=newFileInfo(r,t),s=this.getRoot(t);return i.meta().setComponentRoot(s),i.meta().setOpenFunc(async()=>await this.openInternal(e)),i}catch(e){throw e}}async open(e){const t=this.toAbsolutePath(e);return(await this.fs.stat(t)).isDir()?await this.openDir(e):await this.openInternal(e)}async openInternal(e,t=!1){const r=this.toAbsolutePath(e),i=await this.fs.open(r),s=this.getRoot(r),n=newFileMeta(r);return n.setComponentRoot(s),t?function(e,t,r){return new File(e,t,r,!0)}(i,n,this.fs):function(e,t,r){return new File(e,t,r)}(i,n,this.fs)}getRoot(e){for(const t of this.roots)if(e.startsWith(t))return t;return""}async openDir(e){const t=await this.openInternal(e,!0),r=this.toAbsolutePath(e),i=this.getRoot(r),s=newFileMeta(r);return s.setComponentRoot(i),function(e,t,r){const i=new File(e,t,r,!0);return new DirFile(i)}(t,s,this.fs)}async create(e){const t=this.toAbsolutePath(e);return await this.fs.create(t)}async mkdir(e,t){const r=this.toAbsolutePath(e);return await this.fs.mkdir(r,t)}async mkdirAll(e,t){const r=this.toAbsolutePath(e);return await this.fs.mkdirAll(r,t)}async openFile(e,t,r){const i=this.toAbsolutePath(e);return await this.fs.openFile(i,t,r)}async remove(e){const t=this.toAbsolutePath(e);return await this.fs.remove(t)}async removeAll(e){const t=this.toAbsolutePath(e);return await this.fs.removeAll(t)}async rename(e,t){const r=this.toAbsolutePath(e),i=this.toAbsolutePath(t);return await this.fs.rename(r,i)}name(){return`BaseFs(${this.fs.name()})`}async chmod(e,t){const r=this.toAbsolutePath(e);return await this.fs.chmod(r,t)}async chown(e,t,r){const i=this.toAbsolutePath(e);return await this.fs.chown(i,t,r)}async chtimes(e,t,r){const i=this.toAbsolutePath(e);return await this.fs.chtimes(i,t,r)}}}});import*as path13 from"path";var log9,StaticCopier,log10,init_walkway=__esm({"internal/domain/fs/vo/walkway.ts"(){init_type3(),init_fileinfo(),init_filemeta(),init_log(),log8=getDomainLogger("fs",{component:"walkway"}),Walkway=class{fs;root;cb;cfg;walked=!1;constructor(e,t){if(!e)throw new Error("fs must be set");if(!t.walkFn)throw new Error("walkFn must be set");this.fs=e,this.cb=t,this.root="",this.cfg={}}async walkWith(e,t){return this.cfg=t,this.root=e,await this.walk()}async walk(){if(this.walked)throw new Error("this walkway is already walked");return this.walked=!0,await this.walkRecursive(this.root,this.cfg.info,this.cfg.dirEntries)}checkErr(e,t){return!(!this.isNotExistError(t)||this.cfg.failOnNotExist||(log8.warn(`File "${e}" not found, skipping.`),0))}isNotExistError(e){return e.message.includes("ENOENT")||e.message.includes("no such file")||"ENOENT"===e.code}async walkRecursive(e,t,r){if(!t)try{const r=await this.fs.stat(e),i=newFileMeta(e);i.setOpenFunc(async()=>await this.fs.open(e)),t=newFileInfoWithMeta(r,i)}catch(t){if(e===this.root&&this.isNotExistError(t)){if(this.cfg.failOnNotExist)throw new FsError(`walk: root not found: ${t.message}`,"WALK_ROOT_NOT_FOUND");return}if(this.checkErr(e,t))return;throw new FsError(`walk: stat: ${t.message}`,"WALK_STAT_FAILED")}try{const r=await this.cb.walkFn(e,t);if(r instanceof Error)throw r}catch(e){if(t.isDir()&&e===ErrSkipDir)return;throw e}if(t.isDir()){if(!r)try{const t=await this.fs.open(e),i=await t.readdir(-1);await t.close(),r=i.map(e=>e),this.cfg.sortDirEntries&&r.sort((e,t)=>e.name().localeCompare(t.name()))}catch(t){if(this.checkErr(e,t))return;throw new FsError(`walk: readdir: ${t.message}`,"WALK_READDIR_FAILED")}if(this.cfg.ignoreFile&&(r=r.filter(e=>!this.cfg.ignoreFile(e.fileName()))),this.cb.hookPre)try{r=await this.cb.hookPre(t,e,r)}catch(e){if(e===ErrSkipDir)return;throw e}for(const t of r){const r=path13.join(e,t.name());try{await this.walkRecursive(r,t)}catch(e){if(!t.isDir()||e!==ErrSkipDir)throw e}}if(this.cb.hookPost)try{await this.cb.hookPost(t,e,r)}catch(e){if(e===ErrSkipDir)return;throw e}}}}}}),init_static_copier=__esm({"internal/domain/fs/vo/static-copier.ts"(){init_log(),log9=getDomainLogger("fs",{component:"static-copier"}),StaticCopier=class{fromFss;toFs;constructor(e,t){this.fromFss=e,this.toFs=t}async copy(){this.fromFss&&0!==this.fromFss.length?this.toFs?await this.doWithPublishDirs(this.toFs,async e=>{for(const t of this.fromFss)await this.copyStaticTo(t,e)}):log9.error("No publish filesystem found"):log9.error("No static filesystems found")}async doWithPublishDirs(e,t){try{await t("/")}catch(e){throw log9.error("Error in doWithPublishDirs:",e),e}}async copyStaticTo(e,t){try{return await this.walkSourceFiles(e,t)}catch(e){throw log9.error(`Error copying static files to ${t}:`,e),e}}async walkSourceFiles(e,t){let r=0;try{await this.walkFileSystem(e,"/",async(i,s)=>{s||(await this.copyFile(e,i,this.toFs,t),r++)})}catch(e){throw log9.error("Error walking source files:",e),e}return r}async walkFileSystem(e,t,r){try{const i=await e.open(t);if(!(await i.stat()).isDir())return await i.close(),void await r(t,!1);const s=await i.readdir(-1);await i.close();for(const i of s){const s=this.joinPath(t,i.name());i.isDir()?(await r(s,!0),await this.walkFileSystem(e,s,r)):await r(s,!1)}}catch(e){log9.error(`Could not read directory ${t}:`,e)}}async copyFile(e,t,r,i){let s=null,n=null;try{const a=t.startsWith("/")?t.slice(1):t,o=this.joinPath(i,a),l=this.dirname(o);"/"!==l&&await r.mkdirAll(l,493),s=await e.open(t);const c=await s.stat(),h=new Uint8Array(c.size());await s.read(h),n=await r.create(o),await n.write(h)}catch(e){log9.warn(`Failed to copy static file ${t}:`,e)}finally{if(n)try{await n.close()}catch(e){log9.warn(`Failed to close target file: ${e}`)}if(s)try{await s.close()}catch(e){log9.warn(`Failed to close source file: ${e}`)}}}joinPath(...e){return e.map(e=>e.replace(/^\/+|\/+$/g,"")).filter(e=>e.length>0).join("/").replace(/^/,"/")}dirname(e){const t=e.split("/").filter(e=>e.length>0);return t.length<=1?"/":"/"+t.slice(0,-1).join("/")}}}});async function createFileMetaInfo(e,t){try{const r=await t.stat(e),i=newFileMeta(e);return i.setOpenFunc(async()=>await t.open(e)),newFileInfoWithMeta(r,i)}catch(t){throw new Error(`Failed to stat file ${e}: ${t.message}`)}}var Fs2,defaultDirMerger,OverlayOptions,init_incremental_file_collector=__esm({"internal/domain/fs/vo/incremental-file-collector.ts"(){init_fileinfo(),init_filemeta(),init_log(),log10=getDomainLogger("fs",{component:"incremental-file-collector"})}}),init_fs=__esm({"internal/domain/fs/entity/fs.ts"(){init_basefs(),init_walkway(),init_static_copier(),init_incremental_file_collector(),init_fs3(),Fs2=class{originFs;prompts;workflows;content;layouts;statics;assets;i18n;work;service;constructor(e,t,r,i,s,n,a,o,l){this.originFs=e,this.prompts=t,this.workflows=r,this.content=i,this.layouts=s,this.statics=n,this.assets=a,this.i18n=o,this.work=l,this.service=new Service3}os(){return this.originFs.getOrigin()}workFs(){return this.work}workflowFs(){return this.workflows}promptFs(){return this.prompts}contentFs(){return this.content}layoutsFs(){return this.layouts}staticFs(){return this.statics}assetsFs(){return this.assets}publishFs(){return this.originFs.publish()}copyStatic(e,t){return new StaticCopier(e,t).copy()}newFileMetaInfo(e){return this.service.newFileMetaInfo(e)}newFileMetaInfoWithContent(e){return this.service.newFileMetaInfoWithContent(e)}async getFileMetaInfos(e){return async function(e,t){const r=new Map;let i=!1;for(const s of e)for(const e of t)try{const t=await createFileMetaInfo(s,e);if(r.set(s,t),i=!0,i)break}catch(t){log10.error(`Failed to create FileMetaInfo for ${s} with fs=${e}:`,t)}return r}(e,this.content)}newBasePathFs(e,t){return newBaseFs(e,[t])}async walkPrompts(e,t,r){return await this.walk(this.prompts,e,t,r)}async walkWorkflows(e,t,r){return await this.walk(this.workflows,e,t,r)}async walkLayouts(e,t,r){return await this.walk(this.layouts,e,t,r)}async walkContent(e,t,r,i){await this.walk(e,t,r,i)}async walkStatics(e,t,r){return await this.walk(this.statics,e,t,r)}async walkI18n(e,t,r){return await this.walk(this.i18n,e,t,r)}async walk(e,t,r,i){const s=function(e,t){return new Walkway(e,t)}(e,r);return""===t&&(t="/"),await s.walkWith(t,i)}}}});function newOverlayOptions(e,t=!1,r){const i={fss:e,firstWritable:t};return void 0!==r&&(i.dirsMerger=r),new OverlayOptions(i)}function createDefaultOverlayOptions(e){return newOverlayOptions(e,!1,defaultDirMerger)}var OverlayDir,dirPool,init_overlayoptions=__esm({"internal/domain/fs/vo/overlayoptions.ts"(){defaultDirMerger=(e,t)=>{const r=[...e];for(const i of t){let t=!1;for(const r of e)if(i.name()===r.name()){t=!0;break}t||r.push(i)}return r},OverlayOptions=class e{fss;firstWritable;dirsMerger;constructor(e){this.fss=[...e.fss],this.firstWritable=e.firstWritable??!1,this.dirsMerger=e.dirsMerger??defaultDirMerger}withFilesystems(...t){return new e({fss:[...this.fss,...t],firstWritable:this.firstWritable,dirsMerger:this.dirsMerger})}withFirstWritable(t){return new e({fss:this.fss,firstWritable:t,dirsMerger:this.dirsMerger})}withDirsMerger(t){return new e({fss:this.fss,firstWritable:this.firstWritable,dirsMerger:t})}getWritableFs(){return this.firstWritable&&0!==this.fss.length?this.fss[0]:null}isValid(){return void 0!==this.dirsMerger}getFilesystemCount(){return this.fss.length}getFilesystem(e){return e<0||e>=this.fss.length?null:this.fss[e]}hasFilesystem(e){return this.fss.includes(e)}getFilesystems(){return this.fss}}}});var OverlayFs,init_overlaydir=__esm({"internal/domain/fs/entity/overlaydir.ts"(){init_type3(),init_overlayoptions(),OverlayDir=class{_name;fss;dirOpeners;info;merge;err;offset;fis;closed;constructor(e={}){this._name=e.name||"",this.fss=e.fss?[...e.fss]:[],this.dirOpeners=e.dirOpeners?[...e.dirOpeners]:[],void 0!==e.info&&(this.info=e.info),this.merge=e.merge||defaultDirMerger,this.offset=0,this.fis=[],this.closed=!1}name(){return this._name}isClosed(){return this.closed||0===this.fss.length&&0===this.dirOpeners.length}async readdir(e){if(this.isClosed())throw ErrFileClosed;if(this.err)throw this.err;0===this.offset&&await this.loadDirectoryEntries();const t=this.fis.slice(this.offset);if(e<=0){if(this.err=new Error("EOF"),this.offset>0&&0===t.length)throw this.err;return[...t]}if(0===t.length)throw this.err=new Error("EOF"),this.err;const r=t.slice(0,e);return this.offset+=r.length,r}async readdirnames(e){if(this.isClosed())throw ErrFileClosed;return(await this.readdir(e)).map(e=>e.name())}async loadDirectoryEntries(){for(let e=0;e<this.fss.length;e++){const t=this.fss[e];await this.readFromFilesystem(t,null)}for(let e=0;e<this.dirOpeners.length;e++){const t=await this.dirOpeners[e]();await this.readFromFilesystem(null,t)}}async readFromFilesystem(e,t){let r=t;try{if(!r&&e){const t="/"===this._name?"":this._name;r=await e.open(t)}if(!r)return;const t=await r.readdir(-1);this.fis=this.merge(this.fis,t)}catch(e){}finally{r&&!t&&await r.close()}}async stat(){if(this.isClosed())throw ErrFileClosed;if(this.info)return await this.info();if(this.fss.length>0)return await this.fss[0].stat(this._name);throw new OverlayFsError("no filesystem available for stat","NO_FILESYSTEM")}async close(){this.closed=!0,this.fss=[],this.dirOpeners=[],this.fis=[],delete this.info,this.offset=0,delete this.err}notSupported(e){throw new OverlayFsError(`operation ${e} not supported on directory "${this._name}"`,"OPERATION_NOT_SUPPORTED")}async read(e){this.notSupported("read")}async readAt(e,t){this.notSupported("readAt")}async seek(e,t){this.notSupported("seek")}async write(e){this.notSupported("write")}async writeAt(e,t){this.notSupported("writeAt")}async sync(){this.notSupported("sync")}async truncate(e){this.notSupported("truncate")}async writeString(e){this.notSupported("writeString")}},dirPool=new class{pool=[];get(){return this.pool.length>0?this.pool.pop():new OverlayDir}release(e){e.fss=[],e.dirOpeners=[],e.fis=[],delete e.info,e.offset=0,e._name="",delete e.err,e.closed=!1,this.pool.push(e)}}}});function newOverlayFs(e){return new OverlayFs(e)}var VirtualFileInfo,VirtualFile,globalVirtualFile,init_overlayfs=__esm({"internal/domain/fs/entity/overlayfs.ts"(){init_type3(),init_overlayoptions(),init_overlaydir(),init_log(),getDomainLogger("fs",{component:"overlayfs"}),OverlayFs=class e{fss;mergeDirs;firstWritable;constructor(e){this.fss=[...e.fss],this.mergeDirs=e.dirsMerger,this.firstWritable=e.firstWritable}name(){return"overlayfs"}filesystem(e){return e<0||e>=this.fss.length?null:this.fss[e]}numFilesystems(){return this.fss.length}append(...t){const r=new OverlayOptions({fss:[...this.fss,...t],firstWritable:this.firstWritable,dirsMerger:this.mergeDirs});return new e(r)}withDirsMerger(t){const r=new OverlayOptions({fss:this.fss,firstWritable:this.firstWritable,dirsMerger:t});return new e(r)}writeFs(){if(0===this.fss.length)throw ErrNoFilesystems;return this.fss[0]}async collectDirs(e,t){for(const r of this.fss)await this.collectDirsRecursive(r,e,t)}async collectDirsRecursive(e,t,r){try{(await e.stat(t)).isDir()&&r(e)}catch(e){}const i=e;if(i.filesystem&&i.numFilesystems)for(let e=0;e<i.numFilesystems();e++){const s=i.filesystem(e);s&&await this.collectDirsRecursive(s,t,r)}}async statInternal(e,t){for(let r=0;r<this.fss.length;r++){const i=this.fss[r],[s,n,a,o]=await this.statRecursive(i,e,t);if(null===o||!this.isNotExistError(o))return[s,n,a,o]}return[null,null,!1,ErrFileNotFound]}async statRecursive(e,t,r){try{const r=await e.stat(t);return[e,r,!1,null]}catch(t){if(!this.isNotExistError(t))return[e,null,!1,t]}const i=e;if(i.filesystem&&i.numFilesystems)for(let e=0;e<i.numFilesystems();e++){const s=i.filesystem(e);if(s){const[e,i,n,a]=await this.statRecursive(s,t,r);if(null===a||!this.isNotExistError(a))return[e,i,n,a]}}return[null,null,!1,ErrFileNotFound]}isNotExistError(e){return e.message.includes("ENOENT")||e.message.includes("no such file")||e===ErrFileNotFound}async create(e){if(!this.firstWritable)throw new OverlayFsError("filesystem is read-only","READ_ONLY");return await this.writeFs().create(e)}async mkdir(e,t){if(!this.firstWritable)throw new OverlayFsError("filesystem is read-only","READ_ONLY");return await this.writeFs().mkdir(e,t)}async mkdirAll(e,t){if(!this.firstWritable)throw new OverlayFsError("filesystem is read-only","READ_ONLY");return await this.writeFs().mkdirAll(e,t)}async open(e){if(0===this.fss.length)throw ErrFileNotFound;const[t,r,,i]=await this.statInternal(e,!1);if(i)throw i;if(r.isDir()){const t=[];if(await this.collectDirs(e,e=>{t.push(e)}),0===t.length)throw ErrFileNotFound;return 1===t.length?await t[0].open(e):await async function(e,t,r,i){if(!r)throw new OverlayFsError("info function must not be null","INFO_REQUIRED");const s=dirPool.get(),n={name:e,fss:[...i],info:r,merge:t||defaultDirMerger};return Object.assign(s,new OverlayDir(n)),s}(e,this.mergeDirs,async()=>r,t)}return await t.open(e)}async openFile(e,t,r){const i=!!(1&t)||!!(2&t);if(i&&!this.firstWritable)throw new OverlayFsError("filesystem is read-only","READ_ONLY");return i?await this.writeFs().openFile(e,t,r):await this.open(e)}async remove(e){if(!this.firstWritable)throw new OverlayFsError("filesystem is read-only","READ_ONLY");return await this.writeFs().remove(e)}async removeAll(e){if(!this.firstWritable)throw new OverlayFsError("filesystem is read-only","READ_ONLY");return await this.writeFs().removeAll(e)}async rename(e,t){if(!this.firstWritable)throw new OverlayFsError("filesystem is read-only","READ_ONLY");return await this.writeFs().rename(e,t)}async stat(e){const t="/"===e?"":e,[,r,,i]=await this.statInternal(t,!1);if(i)throw i;return r}async chmod(e,t){if(!this.firstWritable)throw new OverlayFsError("filesystem is read-only","READ_ONLY");return await this.writeFs().chmod(e,t)}async chown(e,t,r){if(!this.firstWritable)throw new OverlayFsError("filesystem is read-only","READ_ONLY");return await this.writeFs().chown(e,t,r)}async chtimes(e,t,r){if(!this.firstWritable)throw new OverlayFsError("filesystem is read-only","READ_ONLY");return await this.writeFs().chtimes(e,t,r)}}}});var Service3,Factory,init_filevitural=__esm({"internal/domain/fs/vo/filevitural.ts"(){init_fs3(),init_fileinfo(),VirtualFileInfo=class{_name;_content;_modTime;constructor(e,t="This is a virtual file."){this._name=e,this._content=t,this._modTime=new Date}name(){return this._name}size(){return Buffer.byteLength(this._content,"utf8")}mode(){return 420}modTime(){return this._modTime}isDir(){return!1}sys(){return null}getContent(){return this._content}},VirtualFile=class{_fileName;_fileContent;_fileInfo=null;constructor(e,t){this._fileName=e,this._fileContent=t}fullName(){return this._fileName}async open(){return{name:()=>this._fileName,close:async()=>{},read:async e=>{const t=Buffer.from(this._fileContent,"utf8"),r=Math.min(e.length,t.length);return t.copy(e,0,0,r),{bytesRead:r,buffer:e}},readAt:async(e,t)=>{const r=Buffer.from(this._fileContent,"utf8"),i=Math.min(t,r.length),s=Math.min(e.length,r.length-i);return s>0&&r.copy(e,0,i,i+s),{bytesRead:s,buffer:e}},seek:async(e,t)=>e,write:async e=>({bytesWritten:e.length,buffer:e}),writeAt:async(e,t)=>({bytesWritten:e.length,buffer:e}),readdir:async e=>[],readdirnames:async e=>[],stat:async()=>this.getFileInfo(),sync:async()=>{},truncate:async e=>{},writeString:async e=>({bytesWritten:Buffer.byteLength(e,"utf8")})}}getFileInfo(){return this._fileInfo||(this._fileInfo=new VirtualFileInfo(this._fileName,this._fileContent)),this._fileInfo}},globalVirtualFile=null}}),init_service4=__esm({"internal/domain/fs/entity/service.ts"(){init_filevitural(),Service3=class{newFileMetaInfo(e){return function(e){const t=(globalVirtualFile||(globalVirtualFile=new VirtualFile("/content/file.txt","This is a virtual file.")),globalVirtualFile.getFileInfo()),r=newFileMeta(e);return new FileInfo(t,r)}(e)}newFileMetaInfoWithContent(e){return function(e){const t=function(e){const t=Math.floor(1e6*Math.random()).toString().padStart(6,"0");return new VirtualFile(`/content/file_${t}.md`,e)}(e),r=t.getFileInfo(),i=newFileMeta(t.fullName(),()=>t.open());return i.setComponentRoot("content"),i.setComponentDir("content"),new FileInfo(r,i)}(e)}}}});function createReadOnlyOverlayFs(e){return(new Factory).createReadOnly(e)}var RootMapping,FilesystemsCollector,init_overlayfs_factory=__esm({"internal/domain/fs/vo/overlayfs-factory.ts"(){init_overlayoptions(),init_overlayfs(),Factory=class{create(e){return newOverlayFs(createDefaultOverlayOptions(e))}createWithOptions(e){return function(e){const t=new OverlayOptions(e);return new OverlayFs(t)}(e)}createReadOnly(e){return newOverlayFs(createDefaultOverlayOptions(e))}createWritable(e){const t=function(e){return newOverlayOptions(e,!0,void 0)}(e);return newOverlayFs(t)}createWithMerger(e,t){return newOverlayFs(createDefaultOverlayOptions(e).withDirsMerger(t))}}}});import*as path14 from"path";var log13,OsFileInfo,OsFile,OsFs,init_filesystemscollector=__esm({"internal/domain/fs/vo/filesystemscollector.ts"(){init_overlayfs_factory(),init_basefs(),init_log(),getDomainLogger("fs",{component:"filesystemscollector"}),RootMapping=class{from;to;toBase;constructor(e,t,r=""){this.from=e,this.to=t,this.toBase=r}fs(e){return newBaseFs(e,[this.to])}},FilesystemsCollector=class{sourceProject;overlayMountsPrompt;overlayMountsWorkflow;overlayMountsContent;overlayMountsLayouts;overlayMountsStatics;overlayMountsAssets;overlayMountsI18n;constructor(e){this.sourceProject=e,this.overlayMountsPrompt=createReadOnlyOverlayFs([]),this.overlayMountsWorkflow=createReadOnlyOverlayFs([]),this.overlayMountsContent=[],this.overlayMountsLayouts=createReadOnlyOverlayFs([]),this.overlayMountsStatics=createReadOnlyOverlayFs([]),this.overlayMountsAssets=createReadOnlyOverlayFs([]),this.overlayMountsI18n=createReadOnlyOverlayFs([])}async collect(e){const t=e.all();for(const e of t){const t=[],r=[],i=[],s=[],n=[],a=[],o=[],l=t=>path14.isAbsolute(t)?["",t]:[e.dir(),this.absPathify(e.dir(),t)],c=e.mounts();for(const e of c){const[c,h]=l(e.source()),u=new RootMapping(e.target(),h,c).fs(this.sourceProject);this.isPrompts(e.target())?r.push(u):this.isWorkflows(e.target())?t.push(u):this.isContent(e.target())?i.push(u):this.isLayouts(e.target())?s.push(u):this.isStatics(e.target())?n.push(u):this.isAssets(e.target())?a.push(u):this.isI18n(e.target())&&o.push(u)}if(t.length>0&&(this.overlayMountsWorkflow=this.overlayMountsWorkflow.append(...t)),r.length>0&&(this.overlayMountsPrompt=this.overlayMountsPrompt.append(...r)),e.isProjectModule())for(const e of i){let t=createReadOnlyOverlayFs([]);t=t.append(e),this.overlayMountsContent.push(t)}s.length>0&&(this.overlayMountsLayouts=this.overlayMountsLayouts.append(...s)),n.length>0&&(this.overlayMountsStatics=this.overlayMountsStatics.append(...n)),a.length>0&&(this.overlayMountsAssets=this.overlayMountsAssets.append(...a)),o.length>0&&(this.overlayMountsI18n=this.overlayMountsI18n.append(...o))}}isPrompts(e){return"prompts"===e||e.startsWith("prompts/")||e.startsWith("/prompts/")}isWorkflows(e){return"workflows"===e||e.startsWith("workflows/")||e.startsWith("/workflows/")}isContent(e){return"content"===e||e.startsWith("content/")||e.startsWith("/content/")}isLayouts(e){return"layouts"===e||e.startsWith("layouts/")||e.startsWith("/layouts/")}isStatics(e){return"static"===e||e.startsWith("static/")||e.startsWith("/static/")}isAssets(e){return"assets"===e||e.startsWith("assets/")||e.startsWith("/assets/")}isI18n(e){return"i18n"===e||e.startsWith("i18n/")||e.startsWith("/i18n/")}absPathify(e,t){return path14.resolve(e,t)}}}});import*as fs from"fs/promises";import*as path15 from"path";var init_osfs=__esm({"internal/domain/fs/vo/osfs.ts"(){init_log(),log13=getDomainLogger("fs",{component:"osfs"}),OsFileInfo=class{constructor(e,t){this.stats=e,this._name=t}name(){return this._name}size(){return this.stats.size}mode(){return this.stats.mode}modTime(){return this.stats.mtime}isDir(){return this.stats.isDirectory()}sys(){return this.stats}},OsFile=class{constructor(e,t="r"){this.filePath=e,this.flags=t}handle=null;closed=!1;position=0;async ensureOpen(){this.handle||this.closed||(this.handle=await fs.open(this.filePath,this.flags))}async close(){if(this.handle){try{await this.handle.close()}catch(e){throw log13.error(`❌ Error closing file handle for ${this.filePath}:`,e),e}this.handle=null}this.closed=!0}async read(e){if(this.closed)throw new Error("File is closed");if(await this.ensureOpen(),!this.handle)throw new Error("Failed to open file");const t=await this.handle.read(e,0,e.length,this.position);return this.position+=t.bytesRead,{bytesRead:t.bytesRead,buffer:e}}async readAt(e,t){if(this.closed)throw new Error("File is closed");if(await this.ensureOpen(),!this.handle)throw new Error("Failed to open file");return{bytesRead:(await this.handle.read(e,0,e.length,t)).bytesRead,buffer:e}}async seek(e,t){if(this.closed)throw new Error("File is closed");switch(t){case 0:default:this.position=e;break;case 1:this.position+=e;break;case 2:if(await this.ensureOpen(),this.handle){const t=await this.handle.stat();this.position=t.size+e}}return this.position}async write(e){if(this.closed)throw new Error("File is closed");if(await this.ensureOpen(),!this.handle)throw new Error("Failed to open file");const t=await this.handle.write(e,0,e.length,this.position);return this.position+=t.bytesWritten,{bytesWritten:t.bytesWritten,buffer:e}}async writeAt(e,t){if(this.closed)throw new Error("File is closed");if(await this.ensureOpen(),!this.handle)throw new Error("Failed to open file");return{bytesWritten:(await this.handle.write(e,0,e.length,t)).bytesWritten,buffer:e}}name(){return this.filePath}async readdir(e){if(this.closed)throw new Error("File is closed");const t=await fs.readdir(this.filePath,{withFileTypes:!0}),r=[],i=e>0?Math.min(e,t.length):t.length;for(let e=0;e<i;e++){const i=t[e],s=path15.join(this.filePath,i.name),n=await fs.stat(s);r.push(new OsFileInfo(n,i.name))}return r}async readdirnames(e){if(this.closed)throw new Error("File is closed");const t=await fs.readdir(this.filePath);return e>0?t.slice(0,e):t}async stat(){if(this.closed)throw new Error("File is closed");const e=await fs.stat(this.filePath);return new OsFileInfo(e,path15.basename(this.filePath))}async sync(){if(this.closed)throw new Error("File is closed");await this.ensureOpen(),this.handle&&await this.handle.sync()}async truncate(e){if(this.closed)throw new Error("File is closed");await this.ensureOpen(),this.handle&&(await this.handle.truncate(e),this.position>e&&(this.position=e))}async writeString(e){const t=Buffer.from(e,"utf8");return{bytesWritten:(await this.write(t)).bytesWritten}}},OsFs=class{async create(e){return await fs.writeFile(e,""),new OsFile(e,"w+")}async mkdir(e,t){await fs.mkdir(e,{mode:t})}async mkdirAll(e,t){await fs.mkdir(e,{mode:t,recursive:!0})}async open(e){return await fs.access(e),(await fs.stat(e)).isDirectory(),new OsFile(e,"r")}async openFile(e,t,r){let i="r";return 1&t&&(i="w"),2&t&&(i="r+"),64&t&&(i="w"),512&t&&(i="w"),1024&t&&(i="a"),new OsFile(e,i)}async remove(e){(await fs.stat(e)).isDirectory()?await fs.rmdir(e):await fs.unlink(e)}async removeAll(e){await fs.rm(e,{recursive:!0,force:!0})}async rename(e,t){await fs.rename(e,t)}async stat(e){const t=await fs.stat(e);return new OsFileInfo(t,path15.basename(e))}name(){return"OsFs"}async chmod(e,t){await fs.chmod(e,t)}async chown(e,t,r){await fs.chown(e,t,r)}async chtimes(e,t,r){await fs.utimes(e,t,r)}}}});var init_overlay_factory=__esm({"internal/domain/fs/vo/overlay-factory.ts"(){init_originfs(),init_fs3(),init_basefs()}});async function createFs(e,t){const r=function(e){const t=e.osFs,r=e.osFs,i=newBaseFs(e.osFs,[e.publish]);return new OriginFs(t,r,i)}(e),i=await async function(e,t){const r=(i=e.getSource(),new FilesystemsCollector(i));var i;return await r.collect(t),r}(r,t),s=newBaseFs(e.osFs,[e.path]);return new Fs2(r,i.overlayMountsPrompt,i.overlayMountsWorkflow,i.overlayMountsContent,i.overlayMountsLayouts,i.overlayMountsStatics,i.overlayMountsAssets,i.overlayMountsI18n,s)}var PageKind,BufWriter,TableOfContentsImpl,HeaderImpl,TOCBuilder,AutoIDGenerator,HighlightResultImpl,DefaultHighlighter,Item,boolRe,intRe,floatRe,_ItemType_name,_ItemType_index,eof,summaryDivider,summaryDividerOrg,delimTOML,delimYAML,delimOrg,leftDelimSc,leftDelimScNoMarkup,rightDelimScNoMarkup,leftDelimScWithMarkup,rightDelimScWithMarkup,leftComment,rightComment,inlineIdentifier,sectionHandlers,sectionHandler,Iterator,pageLexer,init_fs2=__esm({"internal/domain/fs/factory/fs.ts"(){init_fs(),init_overlay_factory(),init_basefs()}}),init_fs3=__esm({"internal/domain/fs/index.ts"(){init_type3(),init_type3(),init_originfs(),init_fs(),init_basefs(),init_overlayfs(),init_overlaydir(),init_service4(),init_filemeta(),init_fileinfo(),init_filevitural(),init_file(),init_dir2(),init_walkway(),init_filesystemscollector(),init_static_copier(),init_overlayoptions(),init_overlayfs_factory(),init_osfs(),init_fs2(),init_overlay_factory()}}),init_type4=__esm({"internal/domain/content/type.ts"(){PageKind={PAGE:"page",HOME:"home",SECTION:"section",TAXONOMY:"taxonomy",TERM:"term",RSS:"rss",SITEMAP:"sitemap",SITEMAP_INDEX:"sitemapindex",ROBOTS_TXT:"robotstxt",STATUS_404:"404"}}}),init_type5=__esm({"internal/domain/markdown/type.ts"(){}}),init_config4=__esm({"internal/domain/markdown/vo/config.ts"(){}}),init_context=__esm({"internal/domain/markdown/vo/context.ts"(){BufWriter=class{buffer;position;capacity;constructor(e=1024){this.capacity=e,this.buffer=new Uint8Array(this.capacity),this.position=0}async write(e){this.ensureCapacity(e.length),this.buffer.set(e,this.position),this.position+=e.length}async writeString(e){const t=(new TextEncoder).encode(e);await this.write(t)}async writeByte(e){this.ensureCapacity(1),this.buffer[this.position]=e,this.position++}bytes(){return this.buffer.slice(0,this.position)}length(){return this.position}truncate(e){if(e<0||e>this.position)throw new Error("Invalid truncate size");this.position=e}ensureCapacity(e){const t=this.position+e;if(t<=this.capacity)return;const r=Math.max(2*this.capacity,t),i=new Uint8Array(r);i.set(this.buffer),this.buffer=i,this.capacity=r}}}}),init_tableofcontents=__esm({"internal/domain/markdown/vo/tableofcontents.ts"(){TableOfContentsImpl=class{constructor(e=[]){this.fragments=e}toHTML(e,t,r){if(0===this.fragments.length)return"";const i=this.filterByLevel(this.fragments,e,t);if(0===i.length)return"";const s=r?"ol":"ul";return`<${s}>\n${this.renderFragments(i,r)}</${s}>\n`}filterByLevel(e,t,r){return e.filter(e=>e.level>=t&&e.level<=r).map(e=>{const i={id:e.id,text:e.text,level:e.level};return e.children&&(i.children=this.filterByLevel(e.children,t,r)),i})}renderFragments(e,t){const r=t?"ol":"ul";return e.map(e=>{let i=` <li><a href="#${e.id}">${this.escapeHTML(e.text)}</a>`;return e.children&&e.children.length>0&&(i+=`\n <${r}>\n${this.renderFragments(e.children,t)} </${r}>`),i+="</li>",i}).join("\n")}escapeHTML(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#x27;")}addFragment(e){this.fragments.push(e)}getFragments(){return[...this.fragments]}},HeaderImpl=class{constructor(e,t,r=[],i=[],s=[]){this._name=e,this._level=t,this._links=r,this._paragraphs=i,this._listParagraphs=s}name(){return this._name}level(){return this._level}links(){return[...this._links]}paragraphs(){return[...this._paragraphs]}listParagraphs(){return[...this._listParagraphs]}addLink(e){this._links.push(e)}addParagraph(e){this._paragraphs.push(e)}addListParagraph(e){this._listParagraphs.push(e)}},TOCBuilder=class{fragments=[];stack=[];addHeading(e,t,r){for(;this.stack.length>0&&this.stack[this.stack.length-1].level>=t;)this.stack.pop();const i={id:r,text:e,level:t,children:[]};if(0===this.stack.length)this.fragments.push(i);else{const e=this.stack[this.stack.length-1];e.children||(e.children=[]),e.children.push(i)}this.stack.push(i)}build(){return new TableOfContentsImpl(this.fragments)}reset(){this.fragments=[],this.stack=[]}},AutoIDGenerator=class{usedIds=new Set;generateID(e,t="github"){let r;switch(t){case"github":default:r=this.githubStyle(e);break;case"github-ascii":r=this.githubAsciiStyle(e);break;case"blackfriday":r=this.blackfridayStyle(e)}if(this.usedIds.has(r)){let e=1,t=`${r}-${e}`;for(;this.usedIds.has(t);)e++,t=`${r}-${e}`;r=t}return this.usedIds.add(r),r}githubStyle(e){return e.toLowerCase().replace(/[^\w\u4e00-\u9fff\s-]/g,"").replace(/\s+/g,"-").replace(/^-+|-+$/g,"")}githubAsciiStyle(e){return e.toLowerCase().replace(/[^\w\s-]/g,"").replace(/\s+/g,"-").replace(/^-+|-+$/g,"")}blackfridayStyle(e){return e.toLowerCase().replace(/[^a-z0-9\s-]/g,"").replace(/\s+/g,"-").replace(/^-+|-+$/g,"")}reset(){this.usedIds.clear()}}}}),init_highlight=__esm({"internal/domain/markdown/vo/highlight.ts"(){HighlightResultImpl=class{constructor(e,t){this.wrappedContent=e,this.innerContent=t}wrapped(){return this.wrappedContent}inner(){return this.innerContent}},DefaultHighlighter=class{constructor(e){this.config=e}async highlight(e,t,r){if(!t||"text"===t||"plain"===t)return this.escapeHTML(e);const i=this.escapeHTML(e),s=`language-${t}`;return this.config.lineNos?this.addLineNumbers(i,s):`<code class="${s}">${i}</code>`}async highlightCodeBlock(e,t){const r=e.type(),i=e.inner(),s=await this.highlight(i,r,t);return new HighlightResultImpl(`<pre>${s}</pre>`,s)}async renderCodeblock(e,t,r){const i=await this.highlightCodeBlock(r);await t.writeString(i.wrapped())}isDefaultCodeBlockRenderer(){return!0}escapeHTML(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#x27;")}addLineNumbers(e,t){const r=e.split("\n").map((e,r)=>{const i=r+this.config.lineNoStart;return this.config.lineNumbersInTable?`<tr><td class="line-number">${i}</td><td class="line-code"><code class="${t}">${e}</code></td></tr>`:`<span class="line-number">${i}</span><code class="${t}">${e}</code>`});return this.config.lineNumbersInTable?`<table class="code-table"><tbody>${r.join("")}</tbody></table>`:r.join("\n")}}}}),init_item=__esm({"pkg/md/parser/item.ts"(){Item=class{Type;Err;low;high;segments;firstByte;isString;content;bytes;constructor(){this.Type=0,this.Err=null,this.low=0,this.high=0,this.segments=[],this.firstByte=0,this.isString=!1,this.content="",this.bytes=[]}Pos(){return this.segments.length>0?this.segments[0].Low:this.low}Val(e){if(0===this.segments.length)return e.slice(this.low,this.high);if(1===this.segments.length)return e.slice(this.segments[0].Low,this.segments[0].High);const t=[];for(const r of this.segments)t.push(e.slice(r.Low,r.High));const r=t.reduce((e,t)=>e+t.length,0),i=new Uint8Array(r);let s=0;for(const e of t)i.set(e,s),s+=e.length;return i}ValStr(e){return(new TextDecoder).decode(this.Val(e))}ValTyped(e){const t=this.ValStr(e);if(this.isString)return t;if(boolRe.test(t))return"true"===t;if(intRe.test(t)){const e=parseInt(t,10);return isNaN(e)?t:e}if(floatRe.test(t)){const e=parseFloat(t);return isNaN(e)?t:e}return t}IsText(){return 18===this.Type||17===this.Type}IsIndentation(){return 17===this.Type}IsNonWhitespace(e){return this.ValStr(e).trim().length>0}IsShortcodeName(){return 13===this.Type}IsInlineShortcodeName(){return 14===this.Type}IsLeftShortcodeDelim(){return 10===this.Type||8===this.Type}IsRightShortcodeDelim(){return 11===this.Type||9===this.Type}IsShortcodeClose(){return 12===this.Type}IsShortcodeParam(){return 15===this.Type}IsShortcodeParamVal(){return 16===this.Type}IsShortcodeMarkupDelimiter(){return 10===this.Type||11===this.Type}IsFrontMatter(){return this.Type>=3&&this.Type<=6}IsDone(){return 0===this.Type||1===this.Type}IsEOF(){return 1===this.Type}IsError(){return 0===this.Type}ToString(e){const t=this.Val(e),r=this.ValStr(e),i=function(e){const t=e;return t<0||t>=_ItemType_index.length-1?`ItemType(${t})`:_ItemType_name.slice(_ItemType_index[t],_ItemType_index[t+1])}(this.Type);switch(!0){case 1===this.Type:return"EOF";case 0===this.Type:return r;case 17===this.Type:return`${i}:[${s=r,s.replace(/ /g,"␣").replace(/\t/g,"→")}]`;case this.Type>19:return`<${r}>`;case t.length>50:return`${i}:${r.substring(0,20)}...`;default:return`${i}:[${r}]`}var s}},boolRe=/^(true|false)$/,intRe=/^[-+]?\d+$/,floatRe=/^[-+]?\d*\.\d+$/,_ItemType_name="tErrortEOFTypeLeadSummaryDividerTypeFrontMatterYAMLTypeFrontMatterTOMLTypeFrontMatterJSONTypeFrontMatterORGTypeIgnoretLeftDelimScNoMarkuptRightDelimScNoMarkuptLeftDelimScWithMarkuptRightDelimScWithMarkuptScClosetScNametScNameInlinetScParamtScParamValtIndentationtTexttKeywordMarker",_ItemType_index=[0,6,10,32,51,70,89,107,117,137,158,180,203,211,218,231,239,250,262,267,281]}});function isSpace(e){return 32===e||9===e}function isAlphaNumericOrHyphen(e){return isAlphaNumeric(e)||45===e}function isEndOfLine(e){return 13===e||10===e}function isAlphaNumeric(e){return 95===e||e>=65&&e<=90||e>=97&&e<=122||e>=48&&e<=57}function lexFrontMatterJSON(e){e.backup();let t=!1,r=0;for(;;){const i=e.next();switch(!0){case i===eof:return e.errorf("unexpected EOF parsing JSON front matter");case 123===i:t||r++;break;case 125===i:t||r--;break;case 34===i:t=!t;break;case 92===i:e.next()}if(0===r)break}return e.consumeCRLF(),e.emit(5),()=>e.lexMainSection()}function lexFrontMatterOrgMode(e){if(e.summaryDivider=summaryDividerOrg,e.backup(),!e.hasPrefix(delimOrg))return()=>e.lexMainSection();e:for(;;){const t=e.next();switch(!0){case 10===t:if(!e.hasPrefix(delimOrg))break e;break;case t===eof:break e}}return e.emit(6),()=>e.lexMainSection()}function lexIntroSection(e){return e.lexIntroSection()}var init_pagelexer=__esm({"pkg/md/parser/pagelexer.ts"(){init_item(),eof=-1,new Uint8Array([239,187,191]),summaryDivider=(new TextEncoder).encode("\x3c!--more--\x3e"),summaryDividerOrg=(new TextEncoder).encode("# more"),delimTOML=(new TextEncoder).encode("+++"),delimYAML=(new TextEncoder).encode("---"),delimOrg=(new TextEncoder).encode("#+"),leftDelimSc=(new TextEncoder).encode("{{"),leftDelimScNoMarkup=(new TextEncoder).encode("{{<"),rightDelimScNoMarkup=(new TextEncoder).encode(">}}"),leftDelimScWithMarkup=(new TextEncoder).encode("{{%"),rightDelimScWithMarkup=(new TextEncoder).encode("%}}"),leftComment=(new TextEncoder).encode("/*"),rightComment=(new TextEncoder).encode("*/"),inlineIdentifier=(new TextEncoder).encode("inline "),sectionHandlers=class{l;skipAll;handlers;skipIndexes;constructor(e){this.l=e,this.skipAll=!1,this.handlers=[],this.skipIndexes=[]}skip(){if(this.skipAll)return-1;this.skipIndexes=[];let e=!1;for(const t of this.handlers){if(t.skipAll)continue;const r=t.skip();-1!==r&&(e=!0,this.skipIndexes.push(r))}return e?function(...e){let t=-1;for(const r of e)r<0||(-1===t||r<t)&&(t=r);return t}(...this.skipIndexes):(this.skipAll=!0,-1)}lex(e){if(this.skipAll)return null;this.l.pos>this.l.start&&this.l.emit(18);for(const t of this.handlers){if(t.skipAll)continue;const[r,i]=t.lexFunc(e,t.l);if(null===r||i)return r}return this.l.pos++,e}},sectionHandler=class{l;skipAll;skipFunc;lexFunc;constructor(e,t,r){this.l=e,this.skipAll=!1,this.skipFunc=t,this.lexFunc=r}skip(){if(this.skipAll)return-1;const e=this.skipFunc(this.l);return-1===e&&(this.skipAll=!0),e}},Iterator=class{items;lastPos;constructor(e){this.items=e,this.lastPos=-1}Next(){return this.lastPos++,this.Current()}Current(){if(this.lastPos>=this.items.length){const e=new Item;return e.Type=0,e.Err=new Error("no more tokens"),e}return this.items[this.lastPos]}Backup(){if(this.lastPos<0)throw new Error("need to go forward before going back");this.lastPos--}Pos(){return this.lastPos}IsValueNext(){const e=this.Peek();return 0!==e.Type&&1!==e.Type}Peek(){return this.items[this.lastPos+1]}PeekWalk(e){for(let t=this.lastPos+1;t<this.items.length&&e(this.items[t]);t++);}Consume(e){for(let t=0;t<e;t++){const e=this.Next();if(0===e.Type||1===e.Type){this.Backup();break}}}LineNumber(e){const t=new Uint8Array([10]),r=e.slice(0,this.Current().low);let i=0;for(let e=0;e<r.length;e++)r[e]===t[0]&&i++;return i+1}},pageLexer=class{input;stateStart;state;pos;start;width;sectionHandlers;cfg;summaryDivider;summaryDividerChecked;lexerShortcodeState;items;err;inFrontMatter;parenDepth;constructor(e,t,r){this.input=e,this.stateStart=t,this.state=null,this.pos=0,this.start=0,this.width=0,this.cfg=r,this.summaryDivider=null,this.summaryDividerChecked=!1,this.err=null,this.items=[],this.inFrontMatter=!1,this.parenDepth=0,this.lexerShortcodeState={currLeftDelimItem:8,currRightDelimItem:9,isInline:!1,currShortcodeName:"",closingState:0,elementStepNum:0,paramElements:0,paramState:0,openShortcodes:{}},this.lexSummaryDivider=this.lexSummaryDivider.bind(this),this.lexMainSection=this.lexMainSection.bind(this),this.lexIdentifierInShortcode=this.lexIdentifierInShortcode.bind(this),this.lexEndOfShortcode=this.lexEndOfShortcode.bind(this),this.lexShortcodeLeftDelim=this.lexShortcodeLeftDelim.bind(this),this.lexShortcodeRightDelim=this.lexShortcodeRightDelim.bind(this),this.lexShortcodeParam=this.lexShortcodeParam.bind(this),this.lexShortcodeValue=this.lexShortcodeValue.bind(this),this.lexShortcodeValueQuoted=this.lexShortcodeValueQuoted.bind(this),this.lexShortcodeValueUnquoted=this.lexShortcodeValueUnquoted.bind(this),this.lexInsideShortcode=this.lexInsideShortcode.bind(this),this.lexDone=this.lexDone.bind(this),this.sectionHandlers=function(e){const t=new sectionHandlers(e),r=new sectionHandler(e,e=>e.index(leftDelimSc),(e,t)=>{if(!t.isShortCodeStart())return[e,!1];if(t.lexerShortcodeState.isInline){const e=t.input.slice(t.pos+3),r=function(e){for(let t=0;t<e.length;t++)if(!isSpace(e[t])){if(47===e[t])return t;break}return-1}(e);if(r!==t.input.length-1){const i=(new TextDecoder).decode(e.slice(r+1)).trim();if(-1===r||!i.startsWith(t.lexerShortcodeState.currShortcodeName+" "))return[t.errorf("inline shortcodes do not support nesting"),!0]}}return t.hasPrefix(leftDelimScWithMarkup)?(t.lexerShortcodeState.currLeftDelimItem=10,t.lexerShortcodeState.currRightDelimItem=11):(t.lexerShortcodeState.currLeftDelimItem=8,t.lexerShortcodeState.currRightDelimItem=9),[t.lexShortcodeLeftDelim,!0]}),i=new sectionHandler(e,e=>e.summaryDividerChecked||!e.summaryDivider?-1:e.index(e.summaryDivider),(e,t)=>t.summaryDivider&&t.hasPrefix(t.summaryDivider)?(t.summaryDividerChecked=!0,t.pos+=t.summaryDivider.length,t.consumeSpace(),t.emit(2),[e,!0]):[e,!1]);return t.handlers=[r,i],t.skipIndexes=new Array(t.handlers.length),t}(this)}Iterator(){return e=this.items,new Iterator(e);var e}Input(){return this.input}run(){for(this.state=this.stateStart;null!==this.state;)this.state=this.state(this);return this}next(){if(this.pos>=this.input.length)return this.width=0,eof;const e=this.input[this.pos];return this.width=1,this.pos+=this.width,e}peek(){const e=this.next();return this.backup(),e}backup(){this.pos-=this.width}append(e){e.Pos()<this.input.length&&(7===e.Type&&239===this.input[e.Pos()]?e.firstByte=239:e.firstByte=this.input[e.Pos()]),this.items.push(e)}emit(e){const t=()=>{this.start=this.pos};if(18===e)for(let r=this.pos-1;r>=this.start;r--){const i=this.input[r];if(32!==i&&9!==i&&13!==i&&10!==i)break;if(r===this.start&&10!==i){const e=new Item;return e.Type=17,e.low=this.start,e.high=this.pos,this.append(e),void t()}if(10===i&&r<this.pos-1){const i=new Item;i.Type=e,i.low=this.start,i.high=r+1,this.append(i);const s=new Item;return s.Type=17,s.low=r+1,s.high=this.pos,this.append(s),void t()}if(10===i&&r===this.pos-1)break}const r=new Item;r.Type=e,r.low=this.start,r.high=this.pos,r.low<this.input.length&&(7===e&&239===this.input[r.low]?r.firstByte=239:r.firstByte=this.input[r.low]),this.append(r),t()}emitString(e){const t=new Item;t.Type=e,t.low=this.start,t.high=this.pos,t.isString=!0,this.pos>this.start&&(t.firstByte=this.input[this.start]),this.items.push(t),this.start=this.pos}isEOF(){return this.pos>=this.input.length}ignoreEscapesAndEmit(e,t){let r=this.start,i=r;const s=[];for(;r<this.pos;){const e=1;92===this.input[r]&&(r>i&&s.push({Low:i,High:r}),i=r+e),r+=e}if(i<this.pos&&s.push({Low:i,High:this.pos}),s.length>0){const t=new Item;t.Type=e,t.segments=s,s[0].High>s[0].Low&&(t.firstByte=this.input[s[0].Low]),this.items.push(t),this.start=this.pos}this.start=this.pos}current(){return this.input.slice(this.start,this.pos)}ignore(){this.start=this.pos}errorf(e,...t){const r=new Error(e.replace(/%[a-z]/g,()=>String(t.shift()))),i=new Item;return i.Type=0,i.Err=r,i.low=this.start,i.high=this.pos,this.append(i),null}consumeCRLF(){let e=!1;const t=this.peek();return 13===t?(this.next(),10===this.peek()&&(this.next(),e=!0)):10===t&&(this.next(),e=!0),e}consumeToSpace(){for(;;){const e=this.next();if(e===eof||isSpace(e))return void this.backup()}}consumeSpace(){for(;;){const e=this.next();if(e===eof||!this.isUnicodeSpace(e))return void this.backup()}}isUnicodeSpace(e){return 32===e||9===e||10===e||12===e||13===e||133===e||160===e||8192===e||8193===e||8194===e||8195===e||8196===e||8197===e||8198===e||8199===e||8200===e||8201===e||8202===e||8232===e||8233===e||8239===e||8287===e||12288===e}index(e){const t=this.input.slice(this.pos),r=e.length,i=t.length;if(r>i)return-1;e:for(let s=0;s<=i-r;s++){for(let i=0;i<r;i++)if(t[s+i]!==e[i])continue e;return s}return-1}hasPrefix(e){if(this.pos+e.length>this.input.length)return!1;for(let t=0;t<e.length;t++)if(this.input[this.pos+t]!==e[t])return!1;return!0}isShortCodeStart(){return this.hasPrefix(leftDelimScWithMarkup)||this.hasPrefix(leftDelimScNoMarkup)}lexFrontMatterSection(e,t,r,i){for(let e=0;e<2;e++)if(this.next()!==t)return this.errorf(`invalid ${r} delimiter`);let s,n=this.consumeCRLF();for(this.ignore();;){if(!n&&(s=this.next(),s===eof))return this.errorf(`EOF looking for end ${r} front matter delimiter`);if((n||isEndOfLine(s))&&this.hasPrefix(i)){this.emit(e),this.pos+=3,this.consumeCRLF(),this.ignore();break}n=!1}return()=>this.lexMainSection()}currentLeftShortcodeDelimItem(){return this.lexerShortcodeState.currLeftDelimItem}currentRightShortcodeDelimItem(){return this.lexerShortcodeState.currRightDelimItem}currentLeftShortcodeDelim(){return 10===this.lexerShortcodeState.currLeftDelimItem?leftDelimScWithMarkup:leftDelimScNoMarkup}currentRightShortcodeDelim(){return 11===this.lexerShortcodeState.currRightDelimItem?rightDelimScWithMarkup:rightDelimScNoMarkup}lexIdentifier(){for(;;)if(!isAlphaNumericOrHyphen(this.next()))return this.backup(),0===(new TextDecoder).decode(this.input.slice(this.start,this.pos)).length||this.emit(15),null}lexMainSection(){if(this.isEOF())return()=>this.lexDone();const e=this.sectionHandlers.skip();if(-1===e)return this.pos=this.input.length,()=>this.lexDone();e>0&&(this.pos+=e);const t=this.sectionHandlers.lex(this.lexMainSection);return null!==t?t:(this.pos=this.input.length,this.lexDone)}lexInlineShortcodeContent(){for(;;){if(this.pos>=this.input.length)return this.errorf("unclosed inline shortcode");if(this.hasPrefix(leftDelimScWithMarkup)||this.hasPrefix(leftDelimScNoMarkup))return this.errorf("inline shortcodes do not support nesting");if(this.hasPrefix(this.currentRightShortcodeDelim()))return this.backup(),this.pos>this.start&&this.emit(18),()=>this.lexShortcodeRightDelim();this.next()}}lexIdentifierInShortcode(){let e=!1;for(;;){const t=this.next();switch(!0){case isAlphaNumericOrHyphen(t):case 47===t:break;case 46===t:if(this.lexerShortcodeState.isInline=this.hasPrefix(inlineIdentifier),!this.lexerShortcodeState.isInline)return this.errorf("period in shortcode name only allowed for inline identifiers");break;default:this.backup();const r=(new TextDecoder).decode(this.input.slice(this.start,this.pos));return this.lexerShortcodeState.closingState>0&&!this.lexerShortcodeState.openShortcodes[r]?this.errorf(`closing tag for shortcode '${r}' does not match start tag`):(this.lexerShortcodeState.closingState>0&&(this.lexerShortcodeState.openShortcodes[r]=!1,e=!0),this.lexerShortcodeState.closingState=0,this.lexerShortcodeState.currShortcodeName=r,this.lexerShortcodeState.openShortcodes[r]=!0,this.lexerShortcodeState.elementStepNum++,this.lexerShortcodeState.isInline?this.emit(14):this.emit(13),e?()=>this.lexEndOfShortcode():this.lexInsideShortcode)}}}lexEndOfShortcode(){return this.lexerShortcodeState.isInline=!1,this.hasPrefix(this.currentRightShortcodeDelim())?()=>this.lexShortcodeRightDelim():!0!==isSpace(this.next())?this.errorf("unclosed shortcode"):(this.ignore(),()=>this.lexEndOfShortcode())}lexShortcodeLeftDelim(){return this.pos+=this.currentLeftShortcodeDelim().length,this.isComment()?()=>this.lexComment():(this.emit(this.lexerShortcodeState.currLeftDelimItem),this.lexerShortcodeState.elementStepNum=0,this.lexerShortcodeState.paramElements=0,this.lexerShortcodeState.paramState=0,this.start=this.pos,this.lexInsideShortcode)}peekString(e){const t=(Uint8Array,e.length);if(this.pos+t>this.input.length)return null;const r=this.input.slice(this.pos,this.pos+t);if(e instanceof Uint8Array){for(let i=0;i<t;i++)if(r[i]!==e[i])return null;return(new TextDecoder).decode(r)}{const t=(new TextDecoder).decode(r);return t===e?t:null}}lexSummaryDivider(){if(!this.hasPrefix(summaryDivider))return null;if(this.start<this.pos){const e=new Item;e.Type=18,e.low=this.start,e.high=this.pos,e.low<this.input.length&&(e.firstByte=this.input[e.low]),this.append(e)}const e=new Item;return e.Type=2,e.low=this.pos,e.high=this.pos+summaryDivider.length,e.low<this.input.length&&(e.firstByte=this.input[e.low]),this.append(e),this.pos+=summaryDivider.length,this.start=this.pos,()=>this.lexMainSection()}handleBOM(){if(this.pos+3<=this.input.length){const e=this.input.slice(this.pos,this.pos+3);if(239===e[0]&&187===e[1]&&191===e[2]){const e=new Item;return e.Type=7,e.low=this.pos,e.high=this.pos+3,e.firstByte=239,this.append(e),this.pos+=3,this.start=this.pos,!0}}return!1}lexIntroSection(){this.summaryDivider=summaryDivider,0===this.pos&&this.handleBOM();e:for(;;){const e=this.next();if(e===eof)break;switch(!0){case 43===e:if(this.hasPrefix(delimTOML.slice(1)))return()=>this.lexFrontMatterSection(4,e,"TOML",delimTOML);this.backup();break e;case 45===e:if(this.hasPrefix(delimYAML.slice(1)))return()=>this.lexFrontMatterSection(3,e,"YAML",delimYAML);this.backup();break e;case 123===e:return lexFrontMatterJSON;case 35===e:return lexFrontMatterOrgMode;case 65279===e:this.emit(7);break;case!isSpace(e)&&!isEndOfLine(e):break e}}return()=>this.lexMainSection()}lexInsideShortcode(){if(this.hasPrefix(this.currentRightShortcodeDelim()))return this.lexShortcodeRightDelim;const e=this.next();if(e===eof)return this.errorf("unclosed shortcode action");if(isSpace(e)||isEndOfLine(e))this.ignore();else{if(61===e){this.consumeSpace(),this.ignore();const e=this.peek();return 34===e||92===e?this.lexShortcodeQuotedParamVal(92!==e,16):96===e?this.lexShortCodeParamRawStringVal(16):this.lexShortcodeParamVal}if(47===e){if(""===this.lexerShortcodeState.currShortcodeName)return this.errorf("got closing shortcode, but none is open");this.lexerShortcodeState.closingState++,this.lexerShortcodeState.isInline=!1,this.emit(12)}else{if(92!==e)return this.lexerShortcodeState.elementStepNum>0&&(isAlphaNumericOrHyphen(e)||34===e||96===e)?(this.backup(),this.lexShortcodeParam(!1)):isAlphaNumeric(e)?(this.backup(),this.lexIdentifierInShortcode):this.errorf(`unrecognized character in shortcode action: U+${e.toString(16).toUpperCase()} '${String.fromCharCode(e)}'. Note: Parameters with non-alphanumeric args must be quoted`);if(this.ignore(),34===this.peek()||96===this.peek())return this.lexShortcodeParam(!0)}}return this.lexInsideShortcode}lexShortcodeParam(e){let t,r=!0,i=!1;for(;;){if(t=this.next(),r){if(34===t||96===t&&!e)return 2===this.lexerShortcodeState.paramElements?this.errorf("got quoted positional parameter. Cannot mix named and positional parameters"):(this.lexerShortcodeState.paramElements=1,this.backup(),34===t?()=>this.lexShortcodeQuotedParamVal(!e,15):()=>this.lexShortCodeParamRawStringVal(15));if(96===t&&e)return this.errorf("unrecognized escape character");r=!1}else if(61===t){this.backup(),i=!0;break}if(!isAlphaNumericOrHyphen(t)&&46!==t){this.backup();break}}if(0===this.lexerShortcodeState.paramElements)this.lexerShortcodeState.paramElements++,i&&this.lexerShortcodeState.paramElements++;else{if(i&&1===this.lexerShortcodeState.paramElements)return this.errorf(`got named parameter '${(new TextDecoder).decode(this.current())}'. Cannot mix named and positional parameters`);if(!i&&2===this.lexerShortcodeState.paramElements)return this.errorf(`got positional parameter '${(new TextDecoder).decode(this.current())}'. Cannot mix named and positional parameters`)}return this.emit(15),this.lexInsideShortcode}lexShortcodeParamVal(){const e=this.next();if(isSpace(e))return this.ignore(),()=>this.lexShortcodeParamVal();switch(this.backup(),e){case 34:return this.next(),this.ignore(),()=>this.lexShortcodeQuotedParamVal(!1,16);case 96:return this.next(),this.ignore(),()=>this.lexShortCodeParamRawStringVal(16);default:return()=>this.lexShortcodeValueUnquoted()}}lexShortcodeValueUnquoted(){for(;;){const e=this.next();if(e===eof||isSpace(e)||this.isRightShortcodeDelim())return this.backup(),this.pos>this.start&&this.emit(16),this.lexInsideShortcode}}lexShortcodeQuotedParamVal(e,t){let r=!1,i=!1,s=0;e:for(;;){const t=this.next();switch(!0){case 92===t:if(34===this.peek()){if(r&&!e){this.backup();break e}r&&(i=!0,s=1)}else if(96===this.peek())return this.errorf("unrecognized escape character");break;case t===eof:case 10===t:return this.errorf(`unterminated quoted string in shortcode parameter-argument: '${(new TextDecoder).decode(this.current())}'`);case 34===t:if(0===s){if(r){this.backup();break e}r=!0,this.ignore()}else s=0}}i?this.ignoreEscapesAndEmit(t,!0):this.emitString(t);const n=this.next();return 92===n?34===this.peek()&&(this.ignore(),this.next(),this.ignore()):34===n?this.ignore():this.backup(),this.lexInsideShortcode}lexShortCodeParamRawStringVal(e){let t=!1;e:for(;;)switch(this.next()){case 96:if(t){this.backup();break e}t=!0,this.ignore();break;case eof:return this.errorf(`unterminated raw string in shortcode parameter-argument: '${(new TextDecoder).decode(this.input.slice(this.start,this.pos))}'`)}return this.emitString(e),this.next(),this.ignore(),this.lexInsideShortcode}lexDone(){return this.pos>this.start&&this.emit(18),this.emit(1),null}lexShortcodeRightDelim(){return this.pos+=this.currentRightShortcodeDelim().length,this.emit(this.lexerShortcodeState.currRightDelimItem),this.lexerShortcodeState.closingState=0,()=>this.lexMainSection()}lexShortcodeValue(){switch(this.next()){case eof:return this.errorf("unterminated quoted string in shortcode parameter");case 32:case 9:return this.ignore(),()=>this.lexShortcodeValue();case 34:return this.ignore(),()=>this.lexShortcodeValueQuoted();default:return this.backup(),()=>this.lexShortcodeValueUnquoted()}}lexShortcodeValueQuoted(){for(;;)switch(this.next()){case eof:return this.errorf("unterminated quoted string in shortcode parameter");case 92:34===this.peek()&&this.next();break;case 34:return this.backup(),this.emitString(16),this.next(),this.ignore(),this.lexInsideShortcode}}isRightShortcodeDelim(){return this.hasPrefix(this.currentRightShortcodeDelim())}lexComment(){const e=this.index(new Uint8Array([...rightComment,...this.currentRightShortcodeDelim()]));return e<=1?this.errorf("comment must be closed"):(this.emit(18),this.pos+=leftComment.length,this.ignore(),this.pos+=e-leftComment.length,this.emit(18),this.pos+=rightComment.length,this.ignore(),this.pos+=this.currentRightShortcodeDelim().length,this.emit(18),this.lexMainSection)}isComment(){return!(this.pos+2>this.input.length)&&47===this.input[this.pos]&&42===this.input[this.pos+1]}}}});var log14,init_pageparser=__esm({"pkg/md/parser/pageparser.ts"(){init_item(),init_pagelexer(),init_pagelexer()}});var log15,SourceParseInfo,log16,ShortcodeImpl,ShortcodeParser,SHORTCODE_PLACEHOLDER_PREFIX,init_pageparser2=__esm({"internal/domain/markdown/vo/pageparser.ts"(){init_log(),init_pageparser(),log14=getDomainLogger("markdown",{component:"pageparser"})}}),init_parseinfo=__esm({"internal/domain/markdown/vo/parseinfo.ts"(){init_pageparser2(),init_item(),init_pagelexer(),init_log(),log15=getDomainLogger("markdown",{component:"parseinfo"}),SourceParseInfo=class{source;posMainContent=-1;itemsStep1=[];handlers;constructor(e,t){this.source=e,this.handlers=t,this.validateHandlers()}validateHandlers(){if(!this.handlers.frontMatterHandler())throw new Error("no front matter handler");if(!this.handlers.summaryHandler())throw new Error("no summary handler");if(!this.handlers.shortcodeHandler())throw new Error("no shortcode handler");if(!this.handlers.bytesHandler())throw new Error("no bytes handler")}isEmpty(){return 0===this.itemsStep1.length}async parse(){const e=function(e,t={}){const[r,i]=function(e,t){const[r,i]=function(e,t){const r=function(e,t,r){return new pageLexer(e,lexIntroSection,r)}(e,0,t);return r.run(),[r,null]}(e,t);return i?[[],i]:[r.items,r.err]}(e,t);if(i)throw log14.error("Error parsing bytes:",i),i;return r}(this.source,{});this.itemsStep1=e}async handle(){if(this.isEmpty())return;const e=new Iterator(this.itemsStep1);for(;;){const t=e.Next();try{if(7===t.Type)log15.info(`Ignoring item at position ${t.Pos()}: ${t.ValStr(this.source)}`);else if(t.IsFrontMatter()){await this.handlers.frontMatterHandler()(t);const r=e.Peek();r.IsDone()||(this.posMainContent=r.Pos())}else if(2===t.Type)await this.handlers.summaryHandler()(t,e);else if(t.IsLeftShortcodeDelim()){e.Backup();const t=e.Current();await this.handlers.shortcodeHandler()(t,e)}else{if(t.IsEOF())break;if(t.IsError())throw log15.error(`Error parsing item at position ${t.Pos()}: ${t.Err}`),this.createError(t.Err||new Error("Unknown parsing error"),t);await this.handlers.bytesHandler()(t)}}catch(e){throw this.createError(e,t)}}}getMainContentPosition(){return this.posMainContent}getItems(){return this.itemsStep1}getSource(){return this.source}createError(e,t){const r=function(e,t,r){const i="string"==typeof t?(s=t,(new TextEncoder).encode(s)):t;var s;if(r<0)return{filename:e,line:1,column:1,offset:0};let n=1,a=1;for(let e=0;e<Math.min(r,i.length);e++)10===i[e]?(n++,a=1):a++;return{filename:e,line:n,column:a,offset:r}}("",this.source,t.Pos()),i=new Error(`${e.message} at line ${r.line}, column ${r.column}`);return i.position=r,i}}}});function createShortcodePlaceholder(e,t,r){return`${SHORTCODE_PLACEHOLDER_PREFIX}${e}${t}${r}HBHB`}function indexNonWhiteSpace2(e,t){const r=t.charCodeAt(0);for(let t=0;t<e.length;t++)if(!isSpace2(e[t])&&e[t]===r)return t;return-1}function isSpace2(e){return 32===e||9===e||13===e||10===e}var MediaType,INTERNAL_SUMMARY_DIVIDER_PRE,Content,RenderingResultImpl,ResultImpl,log18,MarkdownImpl,init_shortcode=__esm({"internal/domain/markdown/vo/shortcode.ts"(){init_log(),log16=getDomainLogger("markdown",{component:"vo/shortcode"}),ShortcodeImpl=class{name;params;pos;length;rawContent;placeholder;inline;closed;inner;ordinal;indentation;doMarkup;isClosing;info;templs;constructor(e=0,t="",r=null,i=0,s=0,n=!1,a=!1){this.ordinal=e,this.name=t,this.params=r,this.pos=i,this.length=s,this.rawContent="",this.inline=n,this.closed=a,this.doMarkup=!1,this.isClosing=!1,this.placeholder="",this.inner=[]}needsInner(){return!this.inline}},ShortcodeParser=class{shortcodes=[];nameSet=new Set;source;ordinal=0;pid;openShortcodes=new Map;paramElements=0;constructor(e,t=Date.now()){this.source=e,this.pid=t}parseItem(e,t){const r=this.extractShortcode(this.ordinal,0,t);if(!r)throw new Error("Failed to extract shortcode");r.pos=e.Pos()+e.ValStr(this.source).length,r.length=t.Current().Pos()+t.Current().ValStr(this.source).length-r.pos;const i=this.source.slice(r.pos,r.pos+r.length);return r.rawContent=(new TextDecoder).decode(i),r.name&&this.nameSet.add(r.name),r.params??=[],r.placeholder=createShortcodePlaceholder("s",this.pid,this.ordinal),this.ordinal++,this.shortcodes.push(r),r}extractShortcode(e,t,r){const i=new ShortcodeImpl(e);if(r.Pos()>0){r.Backup();const e=r.Next();e.IsIndentation()&&(i.indentation=e.ValStr(this.source))}let s=0,n=0;const a=t+1;let o=!1;const l="failed to extract shortcode";let c=0;for(;;){const e=r.Next();if(e.IsLeftShortcodeDelim()){const t=r.Peek();if(t.IsRightShortcodeDelim())throw new Error("shortcode has no name");if(t.IsShortcodeClose())continue;if(s>0){r.Backup();const e=this.extractShortcode(n,a,r);n++,e&&e.name&&(this.nameSet.add(e.name),Array.isArray(i.inner)||(i.inner=[]),i.inner.push(e))}else i.doMarkup=e.IsShortcodeMarkupDelimiter();s++}else if(e.IsRightShortcodeDelim()){if(!i.inline&&!i.needsInner())return this.openShortcodes.set(i.name,!1),i}else{if(e.IsShortcodeClose()){o=!0;const e=r.Peek();if(!i.inline&&!i.needsInner()){if(e.IsError())continue;throw new Error(`${l}: shortcode "${i.name}" does not evaluate .Inner or .InnerDeindent, yet a closing tag was provided`)}return e.IsRightShortcodeDelim()?r.Consume(1):(i.isClosing=!0,r.Consume(2)),i.inline||this.openShortcodes.set(i.name,!1),i}if(e.IsText()){Array.isArray(i.inner)||(i.inner=[]);const t=e.ValStr(this.source);i.inner.push(t)}else if(e.IsShortcodeName()||e.IsInlineShortcodeName()){if(i.name=e.ValStr(this.source).trim(),i.inline=e.IsInlineShortcodeName(),this.openShortcodes.has(i.name)&&this.openShortcodes.get(i.name))throw new Error(`shortcode ${i.name} nested in itself`);if(i.inline||this.openShortcodes.set(i.name,!0),i.inline){const e=this.source.slice(r.Pos()+3),t=indexNonWhiteSpace2(e,"/");if(t!==this.source.length-1){const r=(new TextDecoder).decode(e.slice(t+1));if(-1===t||!r.startsWith(i.name+" "))throw new Error("inline shortcodes do not support nesting")}}}else if(e.IsShortcodeParam()){if(!r.IsValueNext()){log16.warn(`${l}: shortcode "${i.name}" has a parameter without a value`);continue}if(r.Peek().IsShortcodeParamVal())if(null===i.params||void 0===i.params){const t={},s=e.ValStr(this.source);r.Next(),t[s]=r.Current().ValTyped(this.source),i.params=t}else{if(Array.isArray(i.params))throw new Error(`${l}: invalid state: invalid param type Array for shortcode "${i.name}", expected a map`);{const t=e.ValStr(this.source);r.Next(),i.params[t]=r.Current().ValTyped(this.source)}}else if(null===i.params||void 0===i.params){const t=[];t.push(e.ValTyped(this.source)),i.params=t}else{if(!Array.isArray(i.params))throw new Error(`${l}: invalid state: invalid param type Object for shortcode "${i.name}", expected an array`);i.params.push(e.ValTyped(this.source))}}else if(e.IsShortcodeParamVal()){if(0===c&&(c=1),Array.isArray(i.params))i.params.push(e.ValTyped(this.source));else if(null===i.params||void 0===i.params){const t=[];t.push(e.ValTyped(this.source)),i.params=t}}else if(e.IsDone()){if(!e.IsError()&&!o&&i.needsInner())throw new Error(`${l}: shortcode "${i.name}" must be closed or self-closed`);r.Backup();break}}}return i.inline||this.openShortcodes.set(i.name,!1),i}getShortcodes(){return this.shortcodes}getNames(){return Array.from(this.nameSet)}},SHORTCODE_PLACEHOLDER_PREFIX="HAHAHUGOSHORTCODE",createShortcodePlaceholder("TOC",0,0)}}),init_type6=__esm({"pkg/media/type.ts"(){MediaType=class{type;mainType;subType;delimiter;firstSuffix;mimeSuffix;suffixesCSV;constructor(e){this.type=e.type,this.mainType=e.mainType,this.subType=e.subType,this.delimiter=e.delimiter,this.firstSuffix=e.firstSuffix,this.mimeSuffix=e.mimeSuffix,this.suffixesCSV=e.suffixesCSV}sub(){if(this.subType)return this.subType;const e=this.type.split("/");return 2===e.length?e[1].split("+")[0]:""}getMimeSuffix(){if(this.mimeSuffix)return this.mimeSuffix;const e=this.type.indexOf("+");return-1!==e?this.type.substring(e+1):void 0}getSuffixList(){return this.suffixesCSV?this.suffixesCSV.split(","):[]}}}}),init_content=__esm({"internal/domain/markdown/vo/content.ts"(){init_type6(),init_log(),getDomainLogger("markdown",{component:"content"}),INTERNAL_SUMMARY_DIVIDER_PRE=(new TextEncoder).encode("\n\nHUGOMORE42\n\n"),Content=class{hasSummaryDivider=!1;summaryTruncated=!1;rawSource;items=[];renderer;constructor(e,t){this.rawSource=e,this.renderer=t}isEmpty(){return!this.rawSource||0===this.rawSource.length}setSummaryDivider(){this.hasSummaryDivider=!0}getHasSummaryDivider(){return this.hasSummaryDivider}setSummaryTruncated(){this.summaryTruncated=!0}getTruncated(){return this.summaryTruncated}addReplacement(e,t){const r={val:e,source:t};this.items.push(r)}addShortcode(e){this.items.push(e)}addItem(e){this.items.push(e)}addItems(...e){this.items.push(...e)}rawContent(){return(new TextDecoder).decode(this.rawSource)}pureContent(){const e=[],t=new TextDecoder,r=new TextEncoder;for(const t of this.items)if(this.isItem(t)){const r=this.rawSource.slice(t.Pos(),t.Pos()+t.Val(this.rawSource).length);e.push(r)}else this.isContentReplacement(t)?e.push(t.val):this.isShortcode(t)&&e.push(r.encode(t.placeholder));const i=e.reduce((e,t)=>e+t.length,0),s=new Uint8Array(i);let n=0;for(const t of e)s.set(t,n),n+=t.length;return t.decode(s)}pureContentWithoutPlaceholder(){const e=[],t=new TextDecoder;for(const t of this.items)if(this.isItem(t)){const r=this.rawSource.slice(t.Pos(),t.Pos()+t.Val(this.rawSource).length);e.push(r)}else this.isContentReplacement(t)?e.push(t.val):this.isShortcode(t);const r=e.reduce((e,t)=>e+t.length,0),i=new Uint8Array(r);let s=0;for(const t of e)i.set(t,s),s+=t.length;return t.decode(i)}renderedContent(e){let t=this.pureContent();if(e)for(const r of this.items)if(this.isShortcode(r)){const i=e(r);t=t.replace(r.placeholder,i)}return t}async renderedContentAsync(e){let t=await this.renderer.render(this.pureContent());if(e)for(const r of this.items)if(this.isShortcode(r))try{const i=await e(r);t=t.replace(r.placeholder,i)}catch(e){}return t}getItems(){return[...this.items]}getShortcodes(){return this.items.filter(this.isShortcode)}getTextItems(){return this.items.filter(this.isItem)}getReplacements(){return this.items.filter(this.isContentReplacement)}extractSummary(e,t){const r=(new TextDecoder).decode(e),i=this.extractSummaryFromHTML(t,r,70,this.containsCJK(r)),s=i.summaryLowHigh.high>i.summaryLowHigh.low?r.substring(i.summaryLowHigh.low,i.summaryLowHigh.high).trim():"";if(s)return this.summaryTruncated=i.truncated,{summary:s,truncated:i.truncated};const n=this.trimShortHTML(e);return this.summaryTruncated=n.length<e.length,{summary:(new TextDecoder).decode(e),truncated:this.summaryTruncated}}extractSummaryFromHTML(e,t,r,i){const s={source:t,summaryLowHigh:{low:0,high:t.length},truncated:!1};if(r<=0)return s;let n=0;const a=t.split(/\s+/);for(let e=0;e<a.length&&n<r;e++){const o=a[e].trim();if(0!==o.length&&!this.isProbablyHTMLToken(o)){if(i){const e=this.stripHTML(o),t=[...e].length;n+=e.length===e.replace(/[^\u0000-\u007F]/g,"").length?1:t}else n+=1;if(n>=r){const r=a.slice(0,e+1).join(" "),i=t.indexOf(r)+r.length;s.summaryLowHigh={low:0,high:Math.min(i,t.length)},s.truncated=!0;break}}}return s}containsCJK(e){return/[\u4e00-\u9fff\u3400-\u4dbf\u3040-\u309f\u30a0-\u30ff\uac00-\ud7af]/.test(e)}isProbablyHTMLToken(e){return">"===e||/^<\/?[A-Za-z]+>?$/.test(e)||/^[A-Za-z]+=["']/.test(e)}stripHTML(e){return e.replace(/<[^>]*>/g,"").replace(/\s+/g," ").trim()}trimShortHTML(e){const t=new TextDecoder,r=new TextEncoder;let i=t.decode(e);return 1===(i.match(/<p>/g)||[]).length&&(i=i.trim(),i.startsWith("<p>")&&i.endsWith("</p>")&&(i=i.slice(3,-4).trim())),r.encode(i)}cleanDividerPlaceholders(e){return this.hasSummaryDivider?e.replace(new RegExp("HUGOMORE42","g"),""):e}getDividedSummary(e){const t=e;if(this.hasSummaryDivider){const e=t.indexOf("HUGOMORE42");if(-1!==e)return t.substring(0,e).trim()}return""}async getRenderedSummary(e,t){if(this.hasSummaryDivider&&e)return this.getDividedSummary(e);const r=this.pureContentWithoutPlaceholder(),i=(new TextEncoder).encode(r),s=new MediaType({type:"text/html",mainType:"text",subType:"html",delimiter:".",firstSuffix:{suffix:"html",fullSuffix:".html"},mimeSuffix:"",suffixesCSV:"html"}),n=this.extractSummary(i,s);let a=n.summary;return n.truncated&&(a+="..."),t&&a.length>t&&(a=a.substring(0,t).trim()+"..."),await this.renderer.render(a)}getWordCount(){return this.pureContent().trim().split(/\s+/).filter(e=>e.length>0).length}getReadingTime(e=200){const t=this.getWordCount();return Math.ceil(t/e)}isItem(e){return"Type"in e&&"firstByte"in e&&"low"in e&&"high"in e}isShortcode(e){return"name"in e&&"placeholder"in e&&"params"in e}isContentReplacement(e){return"val"in e&&"source"in e}}}}),init_parserresult=__esm({"internal/domain/markdown/vo/parserresult.ts"(){RenderingResultImpl=class{constructor(e){this.buffer=e}bytes(){return this.buffer.bytes()}toString(){return(new TextDecoder).decode(this.bytes())}},ResultImpl=class{constructor(e,t){this.parsingResult=e,this.renderingResult=t}headers(){return this.parsingResult.headers()}tableOfContents(){return this.parsingResult.tableOfContents()}bytes(){return this.renderingResult.bytes()}}}});import*as yaml from"js-yaml";import{parse as parseToml2}from"smol-toml";var ParserResult,init_markdown3=__esm({"internal/domain/markdown/entity/markdown.ts"(){init_parserresult(),init_context(),init_parseinfo(),init_item(),init_shortcode(),init_content(),init_log(),log18=getDomainLogger("markdown",{component:"MarkdownImpl"}),MarkdownImpl=class{constructor(e,t){this.renderer=e,this.highlighter=t}async render(e,t){const r=await this.parse(e),i=await this.renderToBytes(e,t,r);return new ResultImpl(r,i)}async highlight(e,t,r){return this.highlighter.highlight(e,t,r)}async highlightCodeBlock(e,t){return this.highlighter.highlightCodeBlock(e,t)}async renderCodeblock(e,t,r){return this.highlighter.renderCodeblock(e,t,r)}isDefaultCodeBlockRenderer(){return this.highlighter.isDefaultCodeBlockRenderer()}async prepareRender(e){const t=await this.parseContent(e),r=t.frontMatter?.params,i=await this.renderer.parse(t.content.pureContent());return{frontMatter:()=>r||{},toc:()=>i.tableOfContents(),render:async e=>{const i=await t.content.renderedContentAsync(e.shortcodeRenderer),s=await t.content.getRenderedSummary(i,e.maxSummaryLength),n=t.content.getWordCount(),a=t.content.getReadingTime(e.wordsPerMinute),o={renderedContent:t.content.cleanDividerPlaceholders(i),wordCount:n,readingTime:a};return r&&(o.frontMatter=r),s&&(o.summary=s),o}}}async parseAndRenderContent(e,t={}){const r=await this.parseContent(e),i=r.frontMatter?.params;let s;s=t.shortcodeRenderer&&r.shortcodes.length>0?await r.content.renderedContentAsync(t.shortcodeRenderer):r.content.pureContent();const n=await this.renderer.render(s);if(this.hasCollectedTagsSupport()){const e=this.getCollectedTags();if(e.length>0){const t=i||{},s=Array.isArray(t.tags)?t.tags:t.tags?[t.tags]:[],n=[...new Set([...s,...e])];t.tags=n,r.frontMatter&&(r.frontMatter.params=t),log18.debug(`Merged tags: YAML [${s.join(", ")}] + inline [${e.join(", ")}] = [${n.join(", ")}]`)}}const a=r.content.getDividedSummary(n),o={renderedContent:n,wordCount:r.content.getWordCount(),readingTime:r.content.getReadingTime(t.wordsPerMinute)};return i&&(o.frontMatter=i),a&&(o.summary=a),o}hasCollectedTagsSupport(){return"function"==typeof this.renderer.getCollectedTags}getCollectedTags(){return this.hasCollectedTagsSupport()?this.renderer.getCollectedTags():[]}async parseContent(e){let t;const r=new Content(e,this.renderer),i=new ShortcodeParser(e),s=[],n=function(e,t){return new SourceParseInfo(e,t)}(e,{frontMatterHandler:()=>r=>{t=this.parseFrontMatter(r,e)},summaryHandler:()=>(t,i)=>{let s=-1;i.PeekWalk(t=>(-1!==s||t.IsDone()||(s=t.Pos()),!t.IsNonWhitespace(e)||(r.setSummaryTruncated(),!1))),r.setSummaryDivider(),r.addReplacement(INTERNAL_SUMMARY_DIVIDER_PRE,t)},shortcodeHandler:()=>(e,t)=>{const n=i.parseItem(e,t);s.push(n),r.addShortcode(n)},bytesHandler:()=>e=>{r.addItem(e)}});return await n.parse(),await n.handle(),{frontMatter:t,content:r,shortcodes:s,summary:await r.getRenderedSummary(),wordCount:r.getWordCount(),readingTime:r.getReadingTime()}}parseFrontMatter(e,t){const r=e.ValStr(t);let i,s={};switch(e.Type){case 3:i="yaml",s=this.parseYAML(r);break;case 4:i="toml",s=this.parseTOML(r);break;case 5:i="json",s=this.parseJSON(r);break;case 6:i="org",s=this.parseOrg(r);break;default:i="yaml"}return{params:s,format:i}}parseYAML(e){try{const t=yaml.load(e);return t&&"object"==typeof t&&!Array.isArray(t)?t:{}}catch(e){return{}}}parseTOML(e){try{const t=parseToml2(e);return t&&"object"==typeof t&&!Array.isArray(t)?t:{}}catch(e){return{}}}parseJSON(e){try{return JSON.parse(e)}catch(e){return{}}}parseOrg(e){const t={},r=e.split("\n");for(const e of r){const r=e.trim();if(!r.startsWith("#+"))continue;const i=r.match(/^#\+([^:]+):\s*(.*)$/);if(i){const e=i[1].trim().toLowerCase(),r=i[2].trim();t[e]=this.parseValue(r)}}return t}parseValue(e){if(e.startsWith('"')&&e.endsWith('"')||e.startsWith("'")&&e.endsWith("'"))return e.slice(1,-1);if("true"===e)return!0;if("false"===e)return!1;if(/^-?\d+$/.test(e))return parseInt(e,10);if(/^-?\d*\.\d+$/.test(e))return parseFloat(e);if(e.startsWith("[")&&e.endsWith("]")){const t=e.slice(1,-1).trim();return t?t.split(",").map(e=>this.parseValue(e.trim())):[]}return e}async parse(e){const t=(new TextDecoder).decode(e.src);return await this.renderer.parse(t)}async renderToBytes(e,t,r){const i=(new TextDecoder).decode(e.src),s=await this.renderer.render(i),n=new BufWriter;return await n.writeString(s),new RenderingResultImpl(n)}}}}),init_parserresult2=__esm({"internal/domain/markdown/factory/it/parserresult.ts"(){init_tableofcontents(),ParserResult=class{_headers=[];_toc;tokens;source;idGenerator;constructor(e,t,r){this.tokens=e,this.source=t,this.idGenerator=r||new AutoIDGenerator,this._toc=this.buildTableOfContents(),this._headers=this.extractHeaders()}headers(){return[...this._headers]}tableOfContents(){return this._toc}getTokens(){return[...this.tokens]}getSource(){return this.source}buildTableOfContents(){const e=new TOCBuilder;for(const t of this.tokens)if("heading_open"===t.type){const r=parseInt(t.tag.substring(1)),i=this.findNextTextToken(t);if(i){const t=i.content,s=this.idGenerator.generateID(t);e.addHeading(t,r,s)}}return e.build()}extractHeaders(){const e=[];for(let t=0;t<this.tokens.length;t++){const r=this.tokens[t];if("heading_open"===r.type){const i=parseInt(r.tag.substring(1)),s=this.findNextTextToken(r,t);if(s){const t=new HeaderImpl(s.content,i);e.push(t)}}}return e}findNextTextToken(e,t){for(let r=void 0!==t?t+1:this.tokens.indexOf(e)+1;r<this.tokens.length;r++){const e=this.tokens[r];if("inline"===e.type)return e;if("heading_close"===e.type)break}return null}}}}),init_slugger_fallback=__esm({"internal/domain/markdown/factory/it/util/slugger-fallback.ts"(){}});function slugifyFilePath(e,t){e=function(e){return e.startsWith("/")&&(e=e.substring(1)),e.endsWith("/")&&(e=e.slice(0,-1)),e}(e);let r=(i=e,i.match(/\.[A-Za-z0-9]+$/)?.[0]);var i;const s=e.replace(new RegExp(r+"$"),"");(t||[".md",".html",void 0].includes(r))&&(r="");let n=function(e){return e.split("/").map(e=>e.replace(/\s/g,"-").replace(/&/g,"-and-").replace(/%/g,"-percent").replace(/\?/g,"").replace(/#/g,"")).join("/").replace(/\/$/,"")}(s);return function(e,t){return e===t||e.endsWith("/"+t)}(n,"_index")&&(n=n.replace(/_index$/,"index")),n+r}function splitAnchor(e){let[t,r]=e.split("#",2);return t.endsWith(".pdf")?[t,void 0===r?"":`#${r}`]:(r=void 0===r?"":"#"+r.toLowerCase().trim().replace(/\s+/g,"-").replace(/[^\w\u4e00-\u9fa5\-]+/g,"").replace(/\-+/g,"-").replace(/^-+|-+$/g,""),[t,r])}var externalLinkRegex,wikilinkRegex,tableRegex,tableWikilinkRegex,wikilinkImageEmbedRegex,init_path=__esm({"internal/domain/markdown/factory/it/util/path.ts"(){init_slugger_fallback()}}),init_wikilink=__esm({"internal/domain/markdown/factory/it/plugins/wikilink.ts"(){init_path(),externalLinkRegex=/^https?:\/\//i,wikilinkRegex=new RegExp(/!?\[\[([^\[\]\|\#\\]+)?(#+[^\[\]\|\#\\]+)?(\\?\|[^\[\]\#]*)?\]\]/g),tableRegex=new RegExp(/^\|([^\n])+\|\n(\|)( ?:?-{3,}:? ?\|)+\n(\|([^\n])+\|\n?)+/gm),tableWikilinkRegex=new RegExp(/(!?\[\[[^\]]*?\]\]|\[\^[^\]]*?\])/g)}});function wikilinkInlineRule(e,t){const r=e.pos,i=e.posMax;if(r+5>i)return!1;const s=33===e.src.charCodeAt(r),n=s?1:0;if(91!==e.src.charCodeAt(r+n)||91!==e.src.charCodeAt(r+n+1))return!1;let a=r+n+2,o=!1;for(;a<i-1;){if(93===e.src.charCodeAt(a)&&93===e.src.charCodeAt(a+1)){o=!0;break}a++}if(!o)return!1;const l=e.src.slice(r+n+2,a);if(0===l.trim().length)return!1;const c=l.indexOf("|"),h=l.indexOf("#");let u,g="",d="";if(-1!==c){const e=l.slice(0,c);u=l.slice(c+1).trim();const t=e.indexOf("#");-1!==t?(g=e.slice(0,t).trim(),d=e.slice(t).trim()):g=e.trim()}else-1!==h?(g=l.slice(0,h).trim(),d=l.slice(h).trim()):g=l.trim();if(!t){const t=s?"wikilink_embed":"wikilink_link",r=e.push(t,"",0),i={isEmbed:s,filepath:g,anchor:d,alias:u,url:g+d};r.meta=i,r.content=u||g}return e.pos=a+2,!0}function renderWikilinkLink(e,t){const r=e[t].meta,[i,s]=splitAnchor(r.url),n=slugifyFilePath(i),a=escapeHtml(r.alias??r.filepath);return`<a class="internal" data-slug="${n}" data-wikilink="${escapeHtml(r.url)}">${a}</a>`}function renderWikilinkEmbed(e,t){const r=e[t].meta,{filepath:i,anchor:s,alias:n}=r,a=slugifyFilePath(i),o=function(e){const t=e.toLowerCase().match(/\.[a-z0-9]+$/);return t?t[0]:""}(i);if([".png",".jpg",".jpeg",".gif",".bmp",".svg",".webp"].includes(o)){const{alt:e,width:t,height:r}=function(e){if(!e)return{alt:"",width:"auto",height:"auto"};const t=wikilinkImageEmbedRegex.exec(e);return t&&t.groups?{alt:t.groups.alt||"",width:t.groups.width||"auto",height:t.groups.height||"auto"}:{alt:e,width:"auto",height:"auto"}}(n);return`<img src="${a}" alt="${escapeHtml(e)}" width="${t}" height="${r}" />`}return[".mp4",".webm",".ogv",".mov",".mkv"].includes(o)?`<video src="${a}" controls></video>`:[".mp3",".webm",".wav",".m4a",".ogg",".3gp",".flac"].includes(o)?`<audio src="${a}" controls></audio>`:[".pdf"].includes(o)?`<iframe src="${a}" class="pdf"></iframe>`:`<blockquote class="transclude" data-url="${a}" data-block="${s}"><a href="${a+s}" class="transclude-inner">Transclude of ${a}</a></blockquote>`}function escapeHtml(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#039;")}function wikilinkPlugin(e,t){!1!==t?.enable&&(e.inline.ruler.before("link","wikilink",wikilinkInlineRule),e.renderer.rules.wikilink_link=renderWikilinkLink,e.renderer.rules.wikilink_embed=renderWikilinkEmbed)}var init_wikilink_plugin=__esm({"internal/domain/markdown/factory/it/plugins/wikilink-plugin.ts"(){init_path(),wikilinkImageEmbedRegex=new RegExp(/^(?<alt>(?!^\d*x?\d*$).*?)?(\|?\s*?(?<width>\d+)(x(?<height>\d+))?)?$/)}});function tagInlineRule(e,t){const r=e.pos;if(r+2>e.posMax)return!1;if(35!==e.src.charCodeAt(r))return!1;if(r>0){const t=e.src.charCodeAt(r-1);if(32!==t&&10!==t&&9!==t)return!1}const i=e.src.slice(r),s=/^#((?:[-_\p{L}\p{Emoji}\p{M}\d])+(?:\/[-_\p{L}\p{Emoji}\p{M}\d]+)*)/u.exec(i);if(!s)return!1;const n=s[0],a=s[1];if(/^[\/\d]+$/.test(a))return!1;if(!t){const t=e.push("tag","",0),r=a.split("/").map(e=>e.trim().toLowerCase().replace(/\s+/g,"-").replace(/[^\p{L}\p{Emoji}\p{M}\d\-_]/gu,"")).join("/"),i=e.md.__tagPluginState,s={rawTag:a,slugTag:r,url:`${i?.tagBaseURL||"tags/"}${r}`};t.meta=s,t.content=a,i?.onTagFound&&i.onTagFound(r)}return e.pos=r+n.length,!0}function renderTag(e,t){const r=e[t].meta,i=r.rawTag.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#039;");return`<a href="${r.url}" class="internal tag-link">${i}</a>`}function tagPlugin(e,t){const r={enable:!0,tagBaseURL:"tags/",...t};!1!==r.enable&&(e.__tagPluginState={tagBaseURL:r.tagBaseURL,onTagFound:r.onTagFound},e.inline.ruler.before("emphasis","tag",tagInlineRule),e.renderer.rules.tag=renderTag)}var calloutMapping,calloutRegex,init_tag_plugin=__esm({"internal/domain/markdown/factory/it/plugins/tag-plugin.ts"(){new RegExp(/(?<=^| )#((?:[-_\p{L}\p{Emoji}\p{M}\d])+(?:\/[-_\p{L}\p{Emoji}\p{M}\d]+)*)/gu)}});import Token from"markdown-it/lib/token.mjs";function parseCallout(e,t){if("blockquote_open"!==e[t].type)return null;let r=t+1;for(;r<e.length&&"paragraph_open"!==e[r].type;){if("blockquote_close"===e[r].type)return null;r++}if(r>=e.length)return null;const i=r+1;if("inline"!==e[i].type)return null;const s=e[i].content,n=s.match(calloutRegex);if(!n)return null;const[a,o,l="",c]=n;var h;return{type:function(e){const t=e.toLowerCase();return calloutMapping[t]??e}(o.toLowerCase()),title:s.split("\n")[0].slice(a.length).trim()||(h=o.replace(/-/g," ")).charAt(0).toUpperCase()+h.slice(1),collapse:c,metadata:l,firstLineIdx:i}}function transformCalloutTokens(e,t,r){const i=parseCallout(e,t);if(!i)return t;const{type:s,title:n,collapse:a,metadata:o,firstLineIdx:l}=i;let c=t+1,h=1;for(;c<e.length&&h>0;)"blockquote_open"===e[c].type&&h++,"blockquote_close"===e[c].type&&h--,c++;c--,e[t].type="callout_open",e[t].tag="div",e[t].attrSet("class",`callout ${s}${a?" is-collapsible":""}${"-"===a?" is-collapsed":""}`),e[t].attrSet("data-callout",s),a&&e[t].attrSet("data-callout-fold",a),o&&e[t].attrSet("data-callout-metadata",o);const u=e[l],g=u.content.split("\n"),d=g[0],p=d.match(calloutRegex);if(p){const t=p[0],r=d.slice(t.length).trim(),i=g.slice(1);if(u.content=r,i.length>0&&i.join("\n").trim()){const t=l+1,r=new Token("paragraph_open","p",1),s=new Token("inline","",0);s.content=i.join("\n").trim(),s.children=[];const n=new Token("paragraph_close","p",-1);e.splice(t+1,0,r,s,n),c+=3}}let m=t+1;for(;m<c&&"paragraph_open"!==e[m].type;)m++;let f=m+1;for(;f<c&&"paragraph_close"!==e[f].type;)f++;const y=[],w=new Token("callout_title_open","div",1);w.attrSet("class","callout-title"),y.push(w);const S=new Token("callout_icon","div",0);S.attrSet("class","callout-icon"),y.push(S);const b=new Token("callout_title_inner_open","div",1);b.attrSet("class","callout-title-inner"),y.push(b);const _=new Token("inline","",0);_.content=n,_.children=[],y.push(_);const k=new Token("callout_title_inner_close","div",-1);if(y.push(k),a){const e=new Token("callout_fold_icon","div",0);e.attrSet("class","fold-callout-icon"),y.push(e)}const v=new Token("callout_title_close","div",-1);y.push(v),e.splice(m,f-m+1),c-=f-m+1,e.splice(t+1,0,...y),c+=y.length;const P=t+1+y.length;if(P<c){const t=new Token("callout_content_open","div",1);t.attrSet("class","callout-content"),e.splice(P,0,t),c++;const r=new Token("callout_content_close","div",-1);e.splice(c,0,r),c++}return e[c].type="callout_close",e[c].tag="div",c}function calloutRule(e){let t=0,r=0;for(;t<e.tokens.length;)"blockquote_open"===e.tokens[t].type&&parseCallout(e.tokens,t)?(transformCalloutTokens(e.tokens,t,e.md),r++,t++):t++;return r>0}function calloutPlugin(e,t){!1!=={enable:!0,...t}.enable&&(e.core.ruler.after("block","callout",calloutRule),function(e){e.renderer.rules.callout_open=(e,t)=>{const r=e[t];return`<div${r.attrs?r.attrs.map(e=>{return` ${e[0]}="${t=e[1],t.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#039;")}"`;var t}).join(""):""}>`},e.renderer.rules.callout_close=()=>"</div>\n",e.renderer.rules.callout_title_open=(e,t)=>'<div class="callout-title">',e.renderer.rules.callout_title_close=()=>"</div>",e.renderer.rules.callout_title_inner_open=()=>'<div class="callout-title-inner">',e.renderer.rules.callout_title_inner_close=()=>"</div>",e.renderer.rules.callout_icon=()=>'<div class="callout-icon"></div>',e.renderer.rules.callout_fold_icon=()=>'<div class="fold-callout-icon"></div>',e.renderer.rules.callout_content_open=()=>'<div class="callout-content">',e.renderer.rules.callout_content_close=()=>"</div>"}(e))}var init_callout_plugin=__esm({"internal/domain/markdown/factory/it/plugins/callout-plugin.ts"(){calloutMapping={note:"note",abstract:"abstract",summary:"abstract",tldr:"abstract",info:"info",todo:"todo",tip:"tip",hint:"tip",important:"tip",success:"success",check:"success",done:"success",question:"question",help:"question",faq:"question",warning:"warning",caution:"warning",attention:"warning",failure:"failure",fail:"failure",missing:"failure",danger:"danger",error:"danger",bug:"bug",example:"example",quote:"quote",cite:"quote"},calloutRegex=/^\[\!([\w-]+)\|?(.+?)?\]([+-]?)/}});function escapeHtml4(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#039;")}function mathInlineRule(e,t){const r=e.pos,i=e.posMax;if(36!==e.src.charCodeAt(r))return!1;if(r>0&&92===e.src.charCodeAt(r-1))return!1;if(36===e.src.charCodeAt(r+1))return!1;let s=r+1,n=!1;for(;s<i;){const t=e.src.charCodeAt(s);if(10===t)return!1;if(36===t&&92!==e.src.charCodeAt(s-1)){n=!0;break}s++}if(!n)return!1;const a=e.src.slice(r+1,s);if(0===a.trim().length)return!1;if(!t){const t=e.push("math_inline","math",0);t.content=a,t.markup="$"}return e.pos=s+1,!0}function mathBlockRule(e,t,r,i){let s=e.bMarks[t]+e.tShift[t],n=e.eMarks[t];if(s+2>n)return!1;if(36!==e.src.charCodeAt(s)||36!==e.src.charCodeAt(s+1))return!1;if("$$"!==e.src.slice(s,n).trim())return!1;let a=t+1,o=!1;for(;a<r;){if(s=e.bMarks[a]+e.tShift[a],n=e.eMarks[a],"$$"===e.src.slice(s,n).trim()){o=!0;break}a++}if(!o)return!1;const l=[];for(let r=t+1;r<a;r++){const t=e.bMarks[r]+e.tShift[r],i=e.eMarks[r];l.push(e.src.slice(t,i))}const c=l.join("\n");if(!i){const r=e.push("math_block","math",0);r.content=c,r.markup="$$",r.block=!0,r.map=[t,a+1]}return e.line=a+1,!0}function renderMathInline(e,t){return`<span class="math math-inline" data-math="inline">${escapeHtml4(e[t].content)}</span>`}function renderMathBlock(e,t){return`<div class="math math-display" data-math="block">${escapeHtml4(e[t].content)}</div>\n`}function latexPlugin(e,t){!1!==t?.enable&&(e.inline.ruler.before("escape","math_inline",mathInlineRule),e.block.ruler.before("fence","math_block",mathBlockRule,{alt:["paragraph","reference","blockquote","list"]}),e.renderer.rules.math_inline=renderMathInline,e.renderer.rules.math_block=renderMathBlock)}var init_latex_plugin=__esm({"internal/domain/markdown/factory/it/plugins/latex-plugin.ts"(){}});function mermaidPlugin(e,t){if(!1===t?.enable)return;const r=e.renderer.rules.fence||function(e,t,r,i,s){return s.renderToken(e,t,r)};e.renderer.rules.fence=function(t,i,s,n,a){const o=t[i],l=o.info?e.utils.unescapeAll(o.info).trim():"";if("mermaid"===(l?l.split(/\s+/g)[0]:"")){const t=o.content;return`<pre class="mermaid-wrapper"><code class="language-mermaid mermaid">${e.utils.escapeHtml(t)}</code><button class="expand-button" aria-label="Expand diagram"><svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M15 3h6v6M9 21H3v-6M21 3l-7 7M3 21l7-7"/></svg></button><div id="mermaid-container"><div id="mermaid-space"><div class="mermaid-content"></div></div></div></pre>\n`}return r(t,i,s,n,a)}}var MarkdownItRenderer,init_mermaid_plugin=__esm({"internal/domain/markdown/factory/it/plugins/mermaid-plugin.ts"(){}}),init_config5=__esm({"internal/domain/markdown/factory/it/config.ts"(){}}),init_tableofcontents2=__esm({"internal/domain/markdown/factory/it/tableofcontents.ts"(){}});import MarkdownIt from"markdown-it";var init_it=__esm({"internal/domain/markdown/factory/it/index.ts"(){init_markdown5(),init_parserresult2(),init_wikilink(),init_wikilink_plugin(),init_tag_plugin(),init_callout_plugin(),init_latex_plugin(),init_mermaid_plugin(),init_config5(),init_parserresult2(),init_tableofcontents2(),init_wikilink_plugin(),init_tag_plugin(),init_callout_plugin(),init_latex_plugin(),init_mermaid_plugin(),init_wikilink(),init_path(),init_slugger_fallback(),MarkdownItRenderer=class{md;config;idGenerator;collectedTags=new Set;constructor(e,t){this.config=e,this.idGenerator=new AutoIDGenerator,t?(this.md=t,this.config.extensions.wikilink?.enable&&this.md.use(wikilinkPlugin,{enable:!0}),this.config.extensions.parseTags&&this.md.use(tagPlugin,{enable:!0,tagBaseURL:"tags/",onTagFound:e=>this.collectedTags.add(e)}),this.config.extensions.callouts&&this.md.use(calloutPlugin,{enable:!0}),this.config.extensions.latex?.enable&&this.md.use(latexPlugin,{enable:!0}),this.config.extensions.mermaid?.enable&&this.md.use(mermaidPlugin,{enable:!0})):this.md=this.createMarkdownItInstance(),this.setupRendererRules()}setupRendererRules(){const e=this.idGenerator;this.md.renderer.rules.heading_open=function(t,r){const i=t[r+1].content,s=e.generateID(i);return t[r].attrPush(["id",s]),`<${t[r].tag} id="${s}">`}}async render(e){return this.idGenerator.reset(),this.collectedTags.clear(),this.config.extensions.wikilink?.enable&&(e=e.replace(tableRegex,e=>e.replace(tableWikilinkRegex,(e,t)=>{let r=t??"";return r=r.replace("#","\\#"),r=r.replace(/((^|[^\\])(\\\\)*)\|/g,"$1\\|"),r})).replace(wikilinkRegex,(e,...t)=>{const[r,i,s]=t,[n,a]=splitAnchor(`${r??""}${i??""}`),o=Boolean(i?.startsWith("#^"))?"^":"",l=a?`#${o}${a.trim().replace(/^#+/,"")}`:"",c=s??i?.replace("#","|")??"",h=e.startsWith("!")?"!":"";return r?.match(externalLinkRegex)?`${h}[${c.replace(/^\|/,"")}](${r})`:`${h}[[${n}${l}${c}]]`})),this.md.render(e)}getCollectedTags(){return Array.from(this.collectedTags)}async parse(e){this.idGenerator.reset();const t=await this._parse(e);return new ParserResult(t,(new TextEncoder).encode(e),this.idGenerator)}async _parse(e){return this.md.parse(e,{})}getMarkdownIt(){return this.md}addPlugin(e,t){this.md.use(e,t)}createMarkdownItInstance(){const e=new MarkdownIt({html:this.config.renderer.unsafe,breaks:!1,linkify:this.config.extensions.linkify,typographer:!this.config.extensions.typographer.disable});return this.config.extensions.typographer.disable||(e.options.quotes=[this.config.extensions.typographer.leftDoubleQuote,this.config.extensions.typographer.rightDoubleQuote,this.config.extensions.typographer.leftSingleQuote,this.config.extensions.typographer.rightSingleQuote]),this.configureBasicPlugins(e),this.config.extensions.wikilink?.enable&&e.use(wikilinkPlugin,{enable:!0}),this.config.extensions.parseTags&&e.use(tagPlugin,{enable:!0,tagBaseURL:"tags/",onTagFound:e=>this.collectedTags.add(e)}),this.config.extensions.callouts&&e.use(calloutPlugin,{enable:!0}),this.config.extensions.latex?.enable&&e.use(latexPlugin,{enable:!0}),this.config.extensions.mermaid?.enable&&e.use(mermaidPlugin,{enable:!0}),e}configureBasicPlugins(e){this.config.extensions.table&&e.enable(["table"]),this.config.extensions.strikethrough&&e.enable(["strikethrough"])}}}});var PathType,PATH_CONSTANTS,init_markdown4=__esm({"internal/domain/markdown/factory/markdown.ts"(){init_markdown3(),init_highlight(),init_it()}}),init_markdown5=__esm({"internal/domain/markdown/index.ts"(){init_type5(),init_config4(),init_context(),init_tableofcontents(),init_highlight(),init_pageparser2(),init_parseinfo(),init_shortcode(),init_content(),init_markdown3(),init_markdown4()}});import{sep as PATH_SEP}from"path";var PathComponentsImpl,PathPositionsImpl,LowHighImpl,PathComponentsFactory,Path,PathUtils,PathProcessorImpl,PathParsingNormalizer,BasicPathNormalizer,DefaultFileExtensionChecker,PathParserUtils,PathFactoryImpl,DefaultPathFactory,SimplePathPool,PathBuilder,PathFactoryUtils,PathDomain,log19,Translator,init_type7=__esm({"internal/domain/paths/type.ts"(){PathType=(e=>(e[e.File=0]="File",e[e.ContentResource=1]="ContentResource",e[e.ContentSingle=2]="ContentSingle",e[e.Leaf=3]="Leaf",e[e.Branch=4]="Branch",e))(PathType||{}),PATH_CONSTANTS={CONTENT_EXTENSIONS:[".md",".markdown",".mdown",".mkd",".mkdn",".html",".htm",".xml"],HTML_EXTENSIONS:[".html",".htm"],INDEX_NAMES:["index","_index"],PATH_SEPARATOR:"/",EXTENSION_SEPARATOR:".",LANGUAGE_SEPARATOR:".",SYSTEM_PATH_SEPARATOR:PATH_SEP,COMPONENT_FOLDER_CONTENT:"content",COMPONENT_FOLDER_STATIC:"static",COMPONENT_FOLDER_LAYOUTS:"layouts",COMPONENT_FOLDER_ARCHETYPES:"archetypes",COMPONENT_FOLDER_DATA:"data",COMPONENT_FOLDER_ASSETS:"assets",COMPONENT_FOLDER_I18N:"i18n",normalizePath:e=>{let t=e.replace(/\\/g,"/");return t.startsWith("//")&&(t=t.substring(1)),t}}}}),init_pathcomponents=__esm({"internal/domain/paths/vo/pathcomponents.ts"(){init_type7(),PathComponentsImpl=class e{constructor(e,t,r,i,s,n=!1,a){this.original=e,this.normalized=t,this.positions=r,this.identifiers=i,this.bundleType=s,this.disabled=n,this.component=a}withBundleType(t){return new e(this.original,this.normalized,this.positions,this.identifiers,t,this.disabled)}withDisabled(t){return new e(this.original,this.normalized,this.positions,this.identifiers,this.bundleType,t)}hasIdentifiers(){return this.identifiers.length>0}firstIdentifier(){return this.identifiers.length>0?this.identifiers[0]:null}lastIdentifier(){return this.identifiers.length>0?this.identifiers[this.identifiers.length-1]:null}getIdentifier(e){return e>=0&&e<this.identifiers.length?this.identifiers[e]:null}isContentComponent(e){return"content"===e||"archetypes"===e}clone(){return new e(this.original,this.normalized,{...this.positions},[...this.identifiers],this.bundleType,this.disabled,this.component)}toString(){return`PathComponents{original="${this.original}", normalized="${this.normalized}", bundleType=${PathType[this.bundleType]}, identifiers=${this.identifiers.length}}`}},PathPositionsImpl=class e{constructor(e=-1,t=-1,r=-1,i=-1){this.containerLow=e,this.containerHigh=t,this.sectionHigh=r,this.identifierLanguage=i}reset(){this.containerLow=-1,this.containerHigh=-1,this.sectionHigh=-1,this.identifierLanguage=-1}hasContainer(){return-1!==this.containerLow&&-1!==this.containerHigh}hasSection(){return this.sectionHigh>0}hasLanguageIdentifier(){return-1!==this.identifierLanguage}clone(){return new e(this.containerLow,this.containerHigh,this.sectionHigh,this.identifierLanguage)}},LowHighImpl=class{constructor(e,t){if(this.low=e,this.high=t,e>t)throw new Error(`Invalid range: low (${e}) must be <= high (${t})`)}length(){return this.high-this.low}isEmpty(){return this.low===this.high}contains(e){return e>=this.low&&e<this.high}substring(e){return e.substring(this.low,this.high)}toString(){return`[${this.low}, ${this.high})`}},PathComponentsFactory=class{static createEmpty(e="",t=0){return new PathComponentsImpl(e,e,new PathPositionsImpl,[],t,!1)}static create(e,t,r=0){return new PathComponentsImpl(e,t||e,new PathPositionsImpl,[],r,!1)}static createFull(e,t,r,i,s,n=!1){return new PathComponentsImpl(e,t,r,i,s,n)}}}}),init_path2=__esm({"internal/domain/paths/entity/path.ts"(){init_type7(),init_pathcomponents(),Path=class e{constructor(e){this.components=e}_unnormalized;shouldTrimLeadingSlash=!1;component(){if(this.components.component)return this.components.component;const e=this.components.normalized.split("/").filter(e=>e.length>0);return 0===e.length?"content":{static:"static",layouts:"layouts",themes:"themes",archetypes:"archetypes",data:"data",i18n:"i18n",assets:"assets"}[e[0]]||"content"}path(){return this.norm(this.components.normalized)}name(){return this.components.positions.containerHigh>0?this.components.normalized.substring(this.components.positions.containerHigh):this.components.normalized}originalNameNoExt(){const e=this.components.firstIdentifier();return e?this.components.original.substring(this.components.positions.containerHigh,e.low-1):this.components.original.substring(this.components.positions.containerHigh)}nameNoExt(){const e=this.components.firstIdentifier();return e?this.components.normalized.substring(this.components.positions.containerHigh,e.low-1):this.components.normalized.substring(this.components.positions.containerHigh)}nameNoLang(){return this.name()}dir(){let e="";return this.components.positions.containerHigh>0&&(e=this.components.normalized.substring(0,this.components.positions.containerHigh-1)),""===e&&(e="/"),this.norm(e)}ext(){if(0===this.components.identifiers.length)return"";const e=this.components.identifiers[this.components.identifiers.length-1],t=this.components.normalized.substring(e.low,e.high);return t?"."+t:""}lang(){return""}section(){if(this.components.positions.sectionHigh<=0)return"";const e=this.components.normalized.substring(1,this.components.positions.sectionHigh);return"_index.md"===e||"index.md"===e||e.endsWith("/_index.md")||e.endsWith("/index.md")?"":this.norm(e)}sections(){const e=this.dir();if("/"===e||""===e)return[];const t=[],r=(e.startsWith("/")?e.substring(1):e).split("/").filter(e=>e.length>0);let i="";for(const e of r)""===i?i=e:i+="/"+e,t.push(this.norm(i));return t}container(){return-1===this.components.positions.containerLow?"":this.norm(this.components.normalized.substring(this.components.positions.containerLow,this.components.positions.containerHigh-1))}containerDir(){return this.isLeafBundle()||this.isBranchBundle(),this.dir()}base(){return this.isBranchBundle()&&"/_index.md"===this.components.normalized?"/":this.isLeafBundle()?this.baseInternal(!1,!0):this.isContent()&&!this.isBundle()?this.pathNoIdentifier():this.isContent()?this.isBundle()?this.baseInternal(!1,!0):this.baseInternal(!this.isContentPage(),this.isBundle()):this.path()}baseNoLeadingSlash(){return this.base().substring(1)}baseNameNoIdentifier(){return this.isBundle()?this.container():this.nameNoIdentifier()}nameNoIdentifier(){if(0===this.components.identifiers.length)return this.name();const e=this.components.identifiers[0],t=this.components.positions.containerHigh;return this.components.normalized.substring(t,e.low-1)}pathNoLang(){return this.baseInternal(!0,!1)}pathNoIdentifier(){if(0===this.components.identifiers.length)return this.path();const e=this.components.identifiers[0],t=this.components.normalized.substring(0,e.low-1);return this.norm(t)}pathRel(e){let t=e.base();return t.endsWith("/")||(t+="/"),this.path().replace(new RegExp("^"+this.escapeRegExp(t)),"")}baseRel(e){let t=e.base();return"/"===t&&(t=""),this.base().substring(t.length+1)}trimLeadingSlash(){const t=this.components.clone(),r=new e(t);return r.setShouldTrimLeadingSlash(!0),r}identifier(e){const t=this.components.identifiers.length;if(0===t||e<0||e>=t)return"";let r;r=1===t?0:0===e?t-1:t-1-e;const i=this.identifierAsString(r);return i?"."+i:""}identifiers(){const e=[],t=this.components.identifiers.length;for(let r=0;r<t;r++){const t=this.identifier(r);t&&e.push(t)}return e}bundleType(){return this.components.bundleType}isContent(){return this.bundleType()>=1}isBundle(){return this.bundleType()>3}isBranchBundle(){return 4===this.bundleType()}isLeafBundle(){return 3===this.bundleType()}isHTML(){const e=this.ext().toLowerCase();return PATH_CONSTANTS.HTML_EXTENSIONS.some(t=>t===e)}disabled(){return this.components.disabled}forBundleType(t){const r=this.components.withBundleType(t);return new e(r)}unnormalized(){if(!this._unnormalized)if(this.components.original===this.components.normalized)this._unnormalized=this;else{const t=new PathComponentsImpl(this.components.original,this.components.original,this.components.positions,this.components.identifiers,this.components.bundleType,this.components.disabled);this._unnormalized=new e(t)}return this._unnormalized}setShouldTrimLeadingSlash(e){this.shouldTrimLeadingSlash=e}norm(e){return this.shouldTrimLeadingSlash&&e.startsWith("/")?e.substring(1):e}isContentPage(){return this.bundleType()>=2}baseInternal(e,t){if(0===this.components.identifiers.length)return this.norm(this.components.normalized);if(e&&1===this.components.identifiers.length)return this.norm(this.components.normalized);let r=this.components.identifiers[this.components.identifiers.length-1].low-1;if(t&&(r=this.components.positions.containerHigh-1),0===r&&r++,!e)return this.norm(this.components.normalized.substring(0,r));const i=this.components.identifiers[0];return this.norm(this.components.normalized.substring(0,r)+this.components.normalized.substring(i.low-1,i.high))}identifierAsString(e){const t=this.identifierIndex(e);if(-1===t)return"";const r=this.components.identifiers[t];return this.components.normalized.substring(r.low,r.high)}identifierIndex(e){return e<0||e>=this.components.identifiers.length?-1:e}escapeRegExp(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}toString(){return`Path{path="${this.path()}", component="${this.component()}", bundleType=${PathType[this.bundleType()]}}`}equals(e){return this.path()===e.path()&&this.component()===e.component()&&this.bundleType()===e.bundleType()}hashCode(){return`${this.component()}:${this.path()}:${this.bundleType()}`}},PathUtils=class{static fromString(e,t){const r=new PathComponentsImpl(t,t,{containerLow:-1,containerHigh:-1,sectionHigh:-1,identifierLanguage:-1},[],0,!1);return new Path(r)}static hasExtension(e,t){const r=e.ext(),i=t.startsWith(".")?t:"."+t;return r.toLowerCase()===i.toLowerCase()}static isUnder(e,t){const r=e.path();let i;i=t.isBranchBundle()?t.dir():t.path();const s="/"===i?"/":i+"/";return r!==i&&r.startsWith(s)}static relativeTo(e,t){return t.pathRel(e)}static compare(e,t){const r=e.path().localeCompare(t.path());if(0!==r)return r;const i=e.component().localeCompare(t.component());return 0!==i?i:e.bundleType()-t.bundleType()}}}}),init_pathparser=__esm({"internal/domain/paths/vo/pathparser.ts"(){init_type7(),init_pathcomponents(),init_path2(),PathProcessorImpl=class{normalizer;extChecker;constructor(e,t){this.normalizer=e||new PathParsingNormalizer,this.extChecker=t||new DefaultFileExtensionChecker}parse(e,t){let r=t;r&&""!==r||(r="/");const i=this.normalizer.normalize(r),s=this.createPathComponents(e,i,t);return new Path(s)}parseIdentity(e,t){const r=this.parse(e,t);return{identifierBase:()=>r.base()}}parseBaseAndBaseNameNoIdentifier(e,t){const r=this.parse(e,t);return[r.base(),r.baseNameNoIdentifier()]}createPathComponents(e,t,r){let i=e,s=t;if(t.startsWith("/")){const r=t.split("/").filter(e=>e.length>0);if(r.length>0){const t=r[0];["static","layouts","themes","archetypes","data","i18n","assets"].includes(t)&&"content"===e&&(i=t),["images","assets","static","css","js","fonts"].includes(t)&&"content"===e&&(i="static")}}const n=s.lastIndexOf("/"),a=n>=0?s.substring(n+1):s;n>=0&&s.substring(0,n);let o=this.detectBundleType(a,i);const l=this.calculatePathPositions(s),c=this.extractIdentifiers(s,a);return new PathComponentsImpl(r,s,l,c,o,!1,i)}detectBundleType(e,t){if("content"!==t&&"archetypes"!==t)return 0;let r=e.split(".")[0];return"index"===r&&this.isContentFile(e)?3:"_index"===r&&this.isContentFile(e)?4:this.isContentFile(e)?2:0}isContentFile(e){const t=this.getFileExtension(e);return["md","html","markdown","mdown","mkd","mkdn","htm"].includes(t.toLowerCase())}getFileExtension(e){const t=e.lastIndexOf(".");return t>0&&t<e.length-1?e.substring(t+1):""}calculatePathPositions(e){let t=-1,r=-1,i=-1;for(let s=e.length-1;s>=0;s--)"/"===e[s]&&(-1===i?i=s+1:-1===r&&(r=s+1),s>0&&(t=s));return new PathPositionsImpl(r,i,t,-1)}extractIdentifiers(e,t){const r=[],i=e.substring(0,e.length-t.length).length,s=t.split(".");if(s.length<=1)return r;let n=i;for(let e=0;e<s.length-1;e++)n+=s[e].length+1;const a=n,o=a+s[s.length-1].length;return r.push(new LowHighImpl(a,o)),r}},PathParsingNormalizer=class{constructor(e=!0,t=!0){this.toLowerCase=e,this.replaceSpaces=t}normalize(e){let t=e;return t=t.replace(/\\/g,"/"),this.toLowerCase&&(t=t.toLowerCase()),this.replaceSpaces&&(t=t.replace(/\s/g,"-")),t}},BasicPathNormalizer=class{constructor(e=!0,t=!0){this.toLowerCase=e,this.replaceSpaces=t}normalize(e){let t=e;return t=t.replace(/\\/g,"/"),this.toLowerCase&&(t=t.toLowerCase()),this.replaceSpaces&&(t=t.replace(/\s+/g,"-")),t}},DefaultFileExtensionChecker=class{isContentExt(e){return PATH_CONSTANTS.CONTENT_EXTENSIONS.includes(e.toLowerCase())}isHTML(e){return PATH_CONSTANTS.HTML_EXTENSIONS.includes(e.toLowerCase())}hasExt(e){for(let t=e.length-1;t>=0;t--){if("."===e[t])return!0;if("/"===e[t])return!1}return!1}},PathParserUtils=class e{static parseBasic(e){const t=e.lastIndexOf("/"),r=t>=0?e.substring(0,t):"",i=t>=0?e.substring(t+1):e,s=i.lastIndexOf("."),n=s>=0?i.substring(s):"",a=s>=0?i.substring(0,s):i;return{dir:r,name:i,ext:n,nameWithoutExt:a}}static join(...e){return e.filter(e=>e.length>0).map(e=>e.replace(/^\/+|\/+$/g,"")).join("/").replace(/\/+/g,"/")}static normalizeBasic(e){return(new BasicPathNormalizer).normalize(e)}static isBundle(t){const r=e.parseBasic(t);return PATH_CONSTANTS.INDEX_NAMES.includes(r.nameWithoutExt)}static extractSection(e){const t=e.startsWith("/")?e.substring(1):e,r=t.indexOf("/");return r>=0?t.substring(0,r):t}static removeExtension(e){const t=e.lastIndexOf(".");return t>e.lastIndexOf("/")?e.substring(0,t):e}static hasExtension(e){return(new DefaultFileExtensionChecker).hasExt(e)}}}}),init_pathfactory=__esm({"internal/domain/paths/factory/pathfactory.ts"(){init_pathparser(),init_pathcomponents(),init_path2(),PathFactoryImpl=class{processor;pool;constructor(e,t){const r=e?.normalizer?{normalize:e.normalizer}:new BasicPathNormalizer(!1!==e?.normalize,!1!==e?.replaceSpaces),i=new DefaultFileExtensionChecker;this.processor=new PathProcessorImpl(r,i),t&&(this.pool=t)}create(e,t,r){return this.pool&&this.pool.get(),this.processor.parse(e,t)}createFromComponents(e){return new Path(e)}createMany(e,t,r){return t.map(t=>this.create(e,t,r))}createWithConfig(e,t,r){const i={};return void 0!==r?.toLowerCase&&(i.normalize=r.toLowerCase),void 0!==r?.replaceSpaces&&(i.replaceSpaces=r.replaceSpaces),void 0!==r?.customNormalizer&&(i.normalizer=r.customNormalizer),this.create(e,t,i)}},DefaultPathFactory=class extends PathFactoryImpl{constructor(){super({normalize:!0,replaceSpaces:!0})}},SimplePathPool=class{pool=[];maxSize;constructor(e=100){this.maxSize=e}get(){if(this.pool.length>0)return this.pool.pop();const e=PathComponentsFactory.createEmpty();return new Path(e)}put(e){this.pool.length<this.maxSize&&this.pool.push(e)}clear(){this.pool=[]}size(){return this.pool.length}},PathBuilder=class{component="";path="";config={};factory;constructor(e){this.factory=e||new DefaultPathFactory}withComponent(e){return this.component=e,this}withPath(e){return this.path=e,this}withNormalization(e){return this.config.normalize=e,this}withSpaceReplacement(e){return this.config.replaceSpaces=e,this}withNormalizer(e){return this.config.normalizer=e,this}build(){if(!this.component||!this.path)throw new Error("Component and path must be set");return this.factory.create(this.component,this.path,this.config)}reset(){return this.component="",this.path="",this.config={},this}},PathFactoryUtils=class e{static defaultFactory=new DefaultPathFactory;static createContentPath(t){return e.defaultFactory.create("content",t)}static createStaticPath(t){return e.defaultFactory.create("static",t)}static createLayoutPath(t){return e.defaultFactory.create("layouts",t)}static createArchetypePath(t){return e.defaultFactory.create("archetypes",t)}static createDataPath(t){return e.defaultFactory.create("data",t)}static createThemePath(t){return e.defaultFactory.create("themes",t)}static createFromConfig(e){const t={};void 0!==e.normalize&&(t.normalize=e.normalize),void 0!==e.replaceSpaces&&(t.replaceSpaces=e.replaceSpaces);const r=new PathFactoryImpl(t);return e.paths.map(t=>r.create(e.component,t))}static builder(){return new PathBuilder}static createWithPool(e,t,r){return new PathFactoryImpl(void 0,r).create(e,t)}}}}),init_paths=__esm({"internal/domain/paths/index.ts"(){init_type7(),init_pathcomponents(),init_pathparser(),init_path2(),init_pathfactory(),init_type7(),init_type7(),init_type7(),init_pathfactory(),init_pathparser(),init_path2(),init_pathparser(),init_pathfactory(),init_pathfactory(),init_pathparser(),PathDomain={createContentPath:PathFactoryUtils.createContentPath,createStaticPath:PathFactoryUtils.createStaticPath,createLayoutPath:PathFactoryUtils.createLayoutPath,createArchetypePath:PathFactoryUtils.createArchetypePath,createDataPath:PathFactoryUtils.createDataPath,createThemePath:PathFactoryUtils.createThemePath,builder:PathFactoryUtils.builder,parseBasic:PathParserUtils.parseBasic,join:PathParserUtils.join,normalizeBasic:PathParserUtils.normalizeBasic,isBundle:PathParserUtils.isBundle,extractSection:PathParserUtils.extractSection,removeExtension:PathParserUtils.removeExtension,checkExtension:PathParserUtils.hasExtension,hasSpecificExtension:PathUtils.hasExtension,isUnder:PathUtils.isUnder,relativeTo:PathUtils.relativeTo,compare:PathUtils.compare,createProcessor:()=>new PathProcessorImpl,createFactory:()=>new DefaultPathFactory,createPool:e=>new SimplePathPool(e),createNormalizer:e=>new BasicPathNormalizer(e?.toLowerCase,e?.replaceSpaces)}}});import*as yaml2 from"js-yaml";var log20,init_translator=__esm({"internal/domain/content/entity/translator.ts"(){init_log(),init_paths(),log19=getDomainLogger("content",{component:"translator"}),Translator=class{contentLanguage;translateFuncs=new Map;constructor(e){this.contentLanguage=e}translate(e,t){const r=e.toLowerCase(),i=this.translateFuncs.get(r);if(i){const e=i(t);if(e)return e}log19.info(`Translation func for language ${e} not found, use default.`);const s=this.translateFuncs.get(this.contentLanguage.toLowerCase());if(s){const e=s(t);if(e)return e}return log19.info("i18n not initialized; if you need string translations, check that you have a bundle in /i18n that matches the site language or the default language."),`[i18n] ${t}`}async setupTranslateFuncs(e){try{await e.walkI18n("",{walkFn:async(e,t)=>{if(e.endsWith(".yaml")||e.endsWith(".yml"))try{const r=(PATH_CONSTANTS.normalizePath(e).split("/").pop()||"").replace(/\.(yaml|yml)$/,"").toLowerCase(),i=await this.readI18nFile(t),s=this.parseI18nContent(i),n=new Map;s.forEach(e=>{n.set(e.id,e.translation)});const a=e=>n.get(e)||(log19.warn(`i18n|MISSING_TRANSLATION|${r}|${e}`),"");this.translateFuncs.set(r,a),log19.info(`✅ Loaded i18n translations for language: ${r} (${s.length} items)`)}catch(t){log19.error(`❌ Failed to load i18n file ${e}:`,t)}}},{}),log19.info(`🌍 Translation setup complete. Loaded ${this.translateFuncs.size} languages: [${Array.from(this.translateFuncs.keys()).join(", ")}]`)}catch(e){throw e}}async readI18nFile(e){let t=null;try{t=await e.open();const r=await t.stat(),i=new Uint8Array(r.size()),s=await t.read(i),n=new TextDecoder("utf-8").decode(s.buffer);return 65279===n.charCodeAt(0)?n.slice(1):n}catch(e){throw log19.error("❌ Failed to read i18n file:",e),e}finally{if(t)try{await t.close()}catch(e){log19.warn(`Failed to close i18n file: ${e}`)}}}parseI18nContent(e){try{const t=yaml2.load(e);return Array.isArray(t)?t.filter(e=>e&&"object"==typeof e&&e.id&&e.translation).map(e=>({id:String(e.id),translation:String(e.translation)})):(log19.warn("i18n YAML content is not an array"),[])}catch(e){return log19.error("❌ Failed to parse i18n YAML content:",e),[]}}getAvailableLanguages(){return Array.from(this.translateFuncs.keys())}hasLanguage(e){return this.translateFuncs.has(e.toLowerCase())}}}});async function createContent(e){const t=new MDConverter(function(e,t){const r=new DefaultHighlighter({style:"github",lineNos:!1,lineNoStart:1,anchorLineNos:!1,lineAnchors:"",lineNumbersInTable:!0,noClasses:!0,codeFences:!0,guessSyntax:!1,tabWidth:4});return new MarkdownImpl(t||!e?new MarkdownItRenderer({extensions:{typographer:{disable:!1,leftSingleQuote:"&lsquo;",rightSingleQuote:"&rsquo;",leftDoubleQuote:"&ldquo;",rightDoubleQuote:"&rdquo;",enDash:"&ndash;",emDash:"&mdash;",ellipsis:"&hellip;",leftAngleQuote:"&laquo;",rightAngleQuote:"&raquo;",apostrophe:"&rsquo;"},footnote:!0,definitionList:!0,table:!0,strikethrough:!0,linkify:!0,linkifyProtocol:"https",taskList:!0,cjk:{enable:!1,eastAsianLineBreaks:!1,eastAsianLineBreaksStyle:"simple",escapedSpace:!1},passthrough:{enable:!1,delimiters:{inline:[],block:[]}},highlight:{style:"github",lineNos:!1,lineNoStart:1,anchorLineNos:!1,lineAnchors:"",lineNumbersInTable:!0,noClasses:!0,codeFences:!0,guessSyntax:!1,tabWidth:4},wikilink:{enable:!0,disableBrokenWikilinks:!1,markdownLinkResolution:"shortest",prettyLinks:!0},parseTags:!0,callouts:!0,latex:{enable:!0},mermaid:{enable:!0}},renderer:{unsafe:!0},parser:{autoHeadingID:!0,autoHeadingIDType:"github",wrapStandAloneImageWithinParagraph:!0,attribute:{title:!0,block:!1}},duplicateResourceFiles:!1,renderHooks:{image:{enableDefault:!0},link:{enableDefault:!0}}},void 0):e,r)}(e.markdown(),e.useInternalRenderer())),r=await async function(e){const t=new Translator(e.defaultLanguage());try{await t.setupTranslateFuncs(e)}catch(e){log20.warn("Failed to setup translator, continuing without i18n support:",e)}return t}(e),i=new PageBuilder(e,e,e,null,null,new Taxonomy2(e.views(),e),new Term(e),new Section(e),new Standalone(e),t,null),s=new PageMap(i);i.pageMapper=s,s.setupReverseIndex();const n=new Content2(e,t,s,r);return i.contentHub=n,n}var kindMapMain,init_hub=__esm({"internal/domain/content/factory/hub.ts"(){init_content3(),init_markdown5(),init_translator(),init_log(),log20=getDomainLogger("content",{component:"content"})}});function getKindMain(e){return kindMapMain[e.toLowerCase()]||""}var Identity,contentFileExtensionsSet,FileInfo7,init_kind=__esm({"internal/domain/content/vo/kind.ts"(){init_type4(),kindMapMain={[PageKind.PAGE]:PageKind.PAGE,[PageKind.HOME]:PageKind.HOME,[PageKind.SECTION]:PageKind.SECTION,[PageKind.TAXONOMY]:PageKind.TAXONOMY,[PageKind.TERM]:PageKind.TERM,[PageKind.STATUS_404]:PageKind.STATUS_404,[PageKind.SITEMAP]:PageKind.SITEMAP,taxonomyterm:PageKind.TAXONOMY}}}),init_identity=__esm({"internal/domain/content/vo/identity.ts"(){init_log(),getDomainLogger("content",{component:"identity"}),Identity=class{id;lang;langIdx;stale=!0;constructor(e,t="",r=0){this.id=e,this.lang=t,this.langIdx=r}ID(){return this.id}identifierBase(){return`${this.id}-${this.lang}`}pageLanguage(){return this.lang}pageLanguageIndex(){return this.langIdx}pageIdentity(){return this}markStale(){this.stale||(this.stale=!0)}isStale(){return this.stale}clearStale(){this.stale&&(this.stale=!1)}}}});import*as crypto from"crypto";import*as path16 from"path";function newFileInfo2(e){return FileInfo7.newFileInfo(e)}var PageByWrapper,lessPageTitle,language,weight,collatorStringCompare,PageSorterImpl,init_fileinfo2=__esm({"internal/domain/content/vo/fileinfo.ts"(){init_paths(),init_log(),getDomainLogger("content",{component:"FileInfo"}),contentFileExtensionsSet=new Set([".md"]),FileInfo7=class e{fileMetaInfo;pathInfo;bundleType;uniqueIDCache;lazyInitDone=!1;constructor(e,t){this.fileMetaInfo=e;const r=PathDomain.createProcessor();this.pathInfo=r.parse(PATH_CONSTANTS.COMPONENT_FOLDER_CONTENT,t),this.bundleType=0,this.determineBundleType()}static newFileInfo(t){const r=PATH_CONSTANTS.normalizePath(t.relativeFilename());return new e(t,r)}pageFile(){return this}shiftToResource(){this.isContent()&&(this.bundleType=1)}relPath(){const e=this.pathInfo.dir(),t=e.startsWith("/")?e.substring(1):e;return path16.join(t,this.pathInfo.name())}section(){return this.pathInfo.section()}isZero(){return null==this.fileMetaInfo}filename(){return this.fileMetaInfo.fileName()}dir(){return this.pathToDir(this.pathInfo.dir())}ext(){return this.pathInfo.ext()}logicalName(){return this.pathInfo.name()}originalBaseFileName(){return this.pathInfo.originalNameNoExt()}baseFileName(){return this.pathInfo.nameNoExt()}translationBaseName(){return this.pathInfo.nameNoIdentifier()}contentBaseName(){return this.pathInfo.baseNameNoIdentifier()}baseNameNoIdentifier(){return this.pathInfo.baseNameNoIdentifier()}root(){return this.pathInfo.dir()||"/"}uniqueID(){return this.init(),this.uniqueIDCache}fileInfo(){return this.fileMetaInfo}type(){const e=this.section();return""!==e?e:"page"}async open(){return await this.fileMetaInfo.open()}paths(){return this.pathInfo}path(){return this.pathInfo.path()}toString(){return this.baseFileName()}getBundleType(){return this.bundleType}isBundle(){return this.bundleType>=3}isLeafBundle(){return 3===this.bundleType}isBranchBundle(){return 4===this.bundleType}isContentResource(){return 1===this.bundleType}isContent(){return this.bundleType>=1}init(){if(!this.lazyInitDone){this.lazyInitDone=!0;const e=this.relPath().replace(/\\/g,"/");this.uniqueIDCache=crypto.createHash("md5").update(e).digest("hex")}}pathToDir(e){return""===e?e:path16.normalize(e.substring(1)+"/")}determineBundleType(){var e;if(e=this.pathInfo.ext(),contentFileExtensionsSet.has(e))switch(this.pathInfo.nameNoIdentifier()){case"index":this.bundleType=3;break;case"_index":this.bundleType=4;break;default:this.bundleType=2}}}}});function sortByTitle(e){pageBy(lessPageTitle).sort(e)}function pageBy(e){return new PageByWrapper(e)}var Cast,Strings,Types,FrontMatterParserImpl,init_sort=__esm({"internal/domain/content/vo/sort.ts"(){PageByWrapper=class{constructor(e){this.by=e}sort(e){!function(e,t){const r=Array.from({length:t.len()},(e,t)=>t);r.sort((e,r)=>t.less(e,r)?-1:t.less(r,e)?1:e-r);const i=[...e];for(let t=0;t<r.length;t++)e[t]=i[r[t]]}(e,new PageSorterImpl(e,this.by))}},lessPageTitle=(e,t)=>collatorStringCompare(e=>e.title(),e,t)<0,language=(e,t)=>collatorStringCompare(e=>e.pageIdentity().pageLanguage(),e,t)<0,weight=(e,t)=>e.pageWeight()<t.pageWeight(),collatorStringCompare=(e,t,r)=>{const i=e(t),s=e(r);return i<s?-1:i>s?1:0},PageSorterImpl=class{constructor(e,t){this.pages=e,this.by=t}len(){return this.pages.length}swap(e,t){[this.pages[e],this.pages[t]]=[this.pages[t],this.pages[e]]}less(e,t){return this.by(this.pages[e],this.pages[t])}}}}),init_cast=__esm({"pkg/cast/cast.ts"(){Cast=class{static toString(e){return null==e?"":"string"==typeof e?e:"number"==typeof e||"boolean"==typeof e?e.toString():String(e)}static toInt(e){if(null==e)return 0;if("number"==typeof e)return Math.floor(e);if("string"==typeof e){const t=parseInt(e,10);return isNaN(t)?0:t}return 0}static toTime(e){if(null==e)return new Date;if(e instanceof Date)return e;if("string"==typeof e){const t=new Date(e);return isNaN(t.getTime())?new Date:t}return"number"==typeof e?new Date(e):new Date}}}}),init_cast2=__esm({"pkg/cast/index.ts"(){init_cast()}}),init_string=__esm({"pkg/string/string.ts"(){Strings=class{static sliceToLower(e){return e.map(e=>e.toLowerCase())}}}}),init_string2=__esm({"pkg/string/index.ts"(){init_string()}}),init_types2=__esm({"pkg/types/types.ts"(){init_cast2(),Types=class{static toStringSlicePreserveString(e){return null==e?null:Array.isArray(e)?e.map(e=>Cast.toString(e)):"string"==typeof e?[e]:[Cast.toString(e)]}}}}),init_types3=__esm({"pkg/types/index.ts"(){init_types2()}});import path17 from"path";function getParamToLower(e,t){return getParam(e,t,!0)}function getParam(e,t,r){const i=e[t.toLowerCase()];if(null==i)return null;switch(typeof i){case"boolean":return i;case"string":return r?i.toLowerCase():i;case"number":return Number.isInteger(i)?Cast.toInt(i):i;default:return i instanceof Date?i:Array.isArray(i)&&i.every(e=>"string"==typeof e)&&r?Strings.sliceToLower(i):i}}var dimensionFlag,LeafNode,Edge,Node,Tree,init_frontmatter=__esm({"internal/domain/content/vo/frontmatter.ts"(){init_kind(),init_cast2(),init_string2(),init_types3(),FrontMatterParserImpl=class{params;langSvc;taxonomySvc;constructor(e,t,r){this.params=e,this.langSvc=t,this.taxonomySvc=r}async parse(e){const t={terms:{},params:this.params,path:"",lang:"",kind:"",title:"",description:"",weight:999};try{await this.parseCustomized(t)}catch(e){throw e}try{await this.parseTerms(t)}catch(e){throw e}try{await this.parseTitle(t)}catch(e){throw e}try{await this.parseDescription(t)}catch(e){throw e}try{await this.parseWeight(t)}catch(e){throw e}try{await this.parseDate(t)}catch(e){throw e}try{await this.parseOrganization(t,e)}catch(e){throw e}try{await this.parseAuthor(t,e)}catch(e){throw e}try{await this.parseMenu(t)}catch(e){throw e}return t}async parseDate(e){if(this.params){const t=this.params.date;null!=t&&(e.date=Cast.toTime(t))}}async parseWeight(e){if(e.weight=999,this.params){const t=this.params.weight;null!=t&&(e.weight=Cast.toInt(t))}}async parseTitle(e){if(this.params){const t=this.params.title;null!=t&&(e.title=Cast.toString(t))}}async parseDescription(e){if(this.params){const t=this.params.description;null!=t&&(e.description=Cast.toString(t))}}async parseCustomized(e){if(!this.params)return;const t=this.params.path;null!=t&&(e.path=this.toSlashPreserveLeading(Cast.toString(t)));const r=this.params.lang;if(null!=r){const t=Cast.toString(r).toLowerCase();this.langSvc.isLanguageValid(t)&&(e.lang=t)}const i=this.params.kind;if(null!=i){const t=Cast.toString(i);if(""!==t){const r=getKindMain(t);if(""===r)throw new Error(`unknown kind "${t}" in front matter`);e.kind=r}}}async parseTerms(e){const t=this.taxonomySvc.views();for(const r of t){const t=Types.toStringSlicePreserveString(getParam(this.params||{},r.plural(),!1));null!==t&&(e.terms[r.plural()]=t)}}async parseOrganization(e,t){if(!this.params)return;const r=this.params.organization;if(!r||"object"!=typeof r)return;const i={};void 0!==r.name&&null!==r.name&&(i.name=Cast.toString(r.name)),void 0!==r.description&&null!==r.description&&(i.description=Cast.toString(r.description)),void 0!==r.vision&&null!==r.vision&&(i.vision=Cast.toString(r.vision)),void 0!==r.website&&null!==r.website&&(i.website=Cast.toString(r.website)),void 0!==r.logo&&null!==r.logo&&(i.logo=path17.join(t,Cast.toString(r.logo)));const s=this.parseContact(r.contact);s&&(i.contact=s);const n=this.parseSocial(r.social);n&&(i.social=n),Object.keys(i).length>0&&(e.organization=i)}async parseMenu(e){if(!this.params)return;const t=this.params.menu;if(!t||"object"!=typeof t)return;const r={};for(const[e,i]of Object.entries(t))if(!1!==i){if(Array.isArray(i)){const t=this.parseMenuItems(i);t.length>0&&(r[e]=t)}else if(i&&"object"==typeof i){const t={};for(const[e,r]of Object.entries(i))if(!1===r)t[e]=!1;else if(Array.isArray(r)){const i=this.parseMenuItems(r);i.length>0&&(t[e]=i)}Object.keys(t).length>0&&(r[e]=t)}}else r[e]=!1;Object.keys(r).length>0&&(e.menu=r)}parseMenuItems(e){const t=[];for(const r of e){if(!r||"object"!=typeof r)continue;const e={title:"",url:""};if(void 0!==r.title&&null!==r.title&&(e.title=Cast.toString(r.title),void 0!==r.url&&null!==r.url)){{const t=Cast.toString(r.url);e.url=""===t?"":t}if(void 0!==r.weight&&null!==r.weight&&(e.weight=Cast.toInt(r.weight)),Array.isArray(r.children)){const t=this.parseMenuItems(r.children);t.length>0&&(e.children=t)}t.push(e)}}return t}async parseAuthor(e,t){if(!this.params)return;const r=this.params.author;if(!r||"object"!=typeof r)return;const i={};void 0!==r.name&&null!==r.name&&(i.name=Cast.toString(r.name)),void 0!==r.description&&null!==r.description&&(i.description=Cast.toString(r.description)),void 0!==r.website&&null!==r.website&&(i.website=Cast.toString(r.website)),void 0!==r.avatar&&null!==r.avatar&&(i.avatar=path17.join(t,Cast.toString(r.avatar)));const s=this.parseContact(r.contact);s&&(i.contact=s);const n=this.parseSocial(r.social);n&&(i.social=n),Object.keys(i).length>0&&(e.author=i)}parseContact(e){if(!e||"object"!=typeof e)return null;const t={};return void 0!==e.email&&null!==e.email&&(t.email=Cast.toString(e.email)),void 0!==e.address&&null!==e.address&&(t.address=Cast.toString(e.address)),void 0!==e.phone&&null!==e.phone&&(t.phone=Cast.toString(e.phone)),Object.keys(t).length>0?t:null}parseSocial(e){if(!e||"object"!=typeof e)return null;const t={},r=["github","twitter","linkedin"];for(const i of r)void 0!==e[i]&&null!==e[i]&&(t[i]=Cast.toString(e[i]));for(const[i,s]of Object.entries(e))r.includes(i)||null==s||(t[i]=Cast.toString(s));return Object.keys(t).length>0?t:null}toSlashPreserveLeading(e){return e.replace(/\\/g,"/")}}}}),init_classifier=__esm({"internal/domain/content/vo/classifier.ts"(){init_fileinfo2()}}),init_dimensions=__esm({"pkg/doctree/dimensions.ts"(){dimensionFlag={has:(e,t)=>(e&t)===t,set:(e,t)=>e|t,index:e=>{if(0===e)throw new Error("dimension flag not set");return e-1}}}});function longestPrefix(e,t){const r=Math.min(e.length,t.length);let i=0;for(i=0;i<r&&e[i]===t[i];i++);return i}async function recursiveWalk(e,t){if(null!==e.leaf&&await t(e.leaf.key,e.leaf.val))return!0;let r=0,i=e.edges.length;for(;r<i;){const s=e.edges[r];if(await recursiveWalk(s.node,t))return!0;if(0===e.edges.length)return recursiveWalk(e,t);e.edges.length>=i&&r++,i=e.edges.length}return!1}var WalkableTrees,MutableTrees,init_radix=__esm({"pkg/radix/radix.ts"(){LeafNode=class{key;val;constructor(e,t){this.key=e,this.val=t}},Edge=class{label;node;constructor(e,t){this.label=e,this.node=t}},Node=class{leaf=null;prefix="";edges=[];isLeaf(){return null!==this.leaf}addEdge(e){const t=this.edges.length;let r=0;for(;r<t&&this.edges[r].label<e.label;)r++;this.edges.splice(r,0,e)}updateEdge(e,t){const r=this.edges.length;let i=0;for(;i<r&&this.edges[i].label<e;)i++;if(!(i<r&&this.edges[i].label===e))throw new Error("replacing missing edge");this.edges[i].node=t}getEdge(e){const t=this.edges.length;let r=0;for(;r<t&&this.edges[r].label<e;)r++;return r<t&&this.edges[r].label===e?this.edges[r].node:null}delEdge(e){const t=this.edges.length;let r=0;for(;r<t&&this.edges[r].label<e;)r++;r<t&&this.edges[r].label===e&&this.edges.splice(r,1)}mergeChild(){const e=this.edges[0].node;this.prefix=this.prefix+e.prefix,this.leaf=e.leaf,this.edges=e.edges}},Tree=class e{root;size;constructor(){this.root=new Node,this.size=0}static newFromMap(t){const r=new e;if(t)if(t instanceof Map)t.forEach((e,t)=>{r.insert(t,e)});else for(const[e,i]of Object.entries(t))r.insert(e,i);return r}len(){return this.size}insert(e,t){let r=null,i=this.root,s=e;for(;;){if(0===s.length){if(i.isLeaf()){const e=i.leaf.val;return i.leaf.val=t,[e,!0]}return i.leaf=new LeafNode(e,t),this.size++,[void 0,!1]}if(r=i,i=i.getEdge(s.charCodeAt(0)),null===i){const i=new Edge(s.charCodeAt(0),new Node);return i.node.leaf=new LeafNode(e,t),i.node.prefix=s,r.addEdge(i),this.size++,[void 0,!1]}const n=longestPrefix(s,i.prefix);if(n===i.prefix.length){s=s.substring(n);continue}this.size++;const a=new Node;a.prefix=s.substring(0,n),r.updateEdge(s.charCodeAt(0),a),a.addEdge(new Edge(i.prefix.charCodeAt(n),i)),i.prefix=i.prefix.substring(n);const o=new LeafNode(e,t);if(s=s.substring(n),0===s.length)return a.leaf=o,[void 0,!1];const l=new Node;return l.leaf=o,l.prefix=s,a.addEdge(new Edge(s.charCodeAt(0),l)),[void 0,!1]}}delete(e){let t=null,r=0,i=this.root,s=e;for(;;){if(0===s.length){if(!i.isLeaf())break;const e=i.leaf;return i.leaf=null,this.size--,null!==t&&0===i.edges.length&&t.delEdge(r),i!==this.root&&1===i.edges.length&&i.mergeChild(),null===t||t===this.root||1!==t.edges.length||t.isLeaf()||t.mergeChild(),[e.val,!0]}if(t=i,r=s.charCodeAt(0),i=i.getEdge(r),null===i)break;if(!s.startsWith(i.prefix))break;s=s.substring(i.prefix.length)}return[void 0,!1]}async deletePrefix(e){return await this._deletePrefix(null,this.root,e)}async _deletePrefix(e,t,r){if(0===r.length){let r=0;return await recursiveWalk(t,(e,t)=>(r++,Promise.resolve(!1))),t.isLeaf()&&(t.leaf=null),t.edges=[],null===e||e===this.root||1!==e.edges.length||e.isLeaf()||e.mergeChild(),this.size-=r,r}const i=r.charCodeAt(0),s=t.getEdge(i);return null===s||!s.prefix.startsWith(r)&&!r.startsWith(s.prefix)?0:(r=s.prefix.length>r.length?r.substring(r.length):r.substring(s.prefix.length),this._deletePrefix(t,s,r))}get(e){let t=this.root,r=e;for(;;){if(0===r.length){if(t.isLeaf())return[t.leaf.val,!0];break}if(t=t.getEdge(r.charCodeAt(0)),null===t)break;if(!r.startsWith(t.prefix))break;r=r.substring(t.prefix.length)}return[void 0,!1]}longestPrefix(e){let t=null,r=this.root,i=e;for(;r.isLeaf()&&(t=r.leaf),0!==i.length&&(r=r.getEdge(i.charCodeAt(0)),null!==r)&&i.startsWith(r.prefix);)i=i.substring(r.prefix.length);return null!==t?[t.key,t.val,!0]:["",void 0,!1]}minimum(){let e=this.root;for(;;){if(e.isLeaf())return[e.leaf.key,e.leaf.val,!0];if(!(e.edges.length>0))break;e=e.edges[0].node}return["",void 0,!1]}maximum(){let e=this.root;for(;;){const t=e.edges.length;if(!(t>0)){if(e.isLeaf())return[e.leaf.key,e.leaf.val,!0];break}e=e.edges[t-1].node}return["",void 0,!1]}async walk(e){await recursiveWalk(this.root,e)}async walkPrefix(e,t){let r=this.root,i=e;for(;;){if(0===i.length)return void await recursiveWalk(r,t);if(r=r.getEdge(i.charCodeAt(0)),null===r)return;if(!i.startsWith(r.prefix))return void(r.prefix.startsWith(i)&&await recursiveWalk(r,t));i=i.substring(r.prefix.length)}}async walkPath(e,t){let r=this.root,i=e;for(;;){if(null!==r.leaf&&await t(r.leaf.key,r.leaf.val))return;if(0===i.length)return;if(r=r.getEdge(i.charCodeAt(0)),null===r)return;if(!i.startsWith(r.prefix))break;i=i.substring(r.prefix.length)}}async toMap(){const e={};return await this.walk((t,r)=>(e[t]=r,Promise.resolve(!1))),e}}}}),init_radix2=__esm({"pkg/radix/index.ts"(){init_radix()}});function cleanKey(e){return"/"===e?"":e}function mustValidateKey(e){const t=function(e){return""===e?null:e.length<2?new Error(`too short key: "${e}"`):"/"!==e[0]?new Error(`key must start with '/': "${e}"`):"/"===e[e.length-1]?new Error(`key must not end with '/': "${e}"`):null}(e);if(t)throw t;return e}var SimpleTree,init_support=__esm({"pkg/doctree/support.ts"(){init_radix2(),WalkableTrees=class{trees;constructor(e){this.trees=e}walkPrefixRaw(e,t){for(const r of this.trees)r.walkPrefixRaw(e,t)}},MutableTrees=class{trees;constructor(e){this.trees=e}delete(e){for(const t of this.trees)t.delete(e)}deleteAll(e){for(const t of this.trees)t.deleteAll(e)}async deletePrefix(e){let t=0;for(const r of this.trees)t+=await r.deletePrefix(e);return Promise.resolve(t)}async deletePrefixAll(e){let t=0;for(const r of this.trees)t+=await r.deletePrefixAll(e);return t}lock(e){const t=this.trees.map(t=>t.lock(e));return()=>{for(const e of t)e()}}canLock(){for(const e of this.trees)if(!e.canLock())return!1;return!0}}}});function newSimpleTree(){return new SimpleTree}var TreeShiftTree,NodeShiftTree,NodeShiftTreeWalker,Shifter2,PageShifter,SourceShifter,WeightedTermTreeNode,PageTreesNode,PageTrees,init_simpletree=__esm({"pkg/doctree/simpletree.ts"(){init_radix2(),init_support(),SimpleTree=class{mu;tree;zero;constructor(){this.tree=new Tree,this.zero=void 0;let e=!1,t=0;this.mu={lock:()=>{for(;e||t>0;);e=!0},unlock:()=>{e=!1},rLock:()=>{for(;e;);t++},rUnlock:()=>{t--}}}get(e){this.mu.rLock();try{const[t,r]=this.tree.get(e);return r?t:this.zero}finally{this.mu.rUnlock()}}longestPrefix(e){this.mu.rLock();try{const[t,r,i]=this.tree.longestPrefix(e);return i?[t,r]:["",this.zero]}finally{this.mu.rUnlock()}}insert(e,t){this.mu.lock();try{return this.tree.insert(e,t),t}finally{this.mu.unlock()}}async walkPrefix(e,t,r){switch(e){case 0:break;case 1:this.mu.rLock();break;case 2:this.mu.lock()}try{let e=null;return await this.tree.walkPrefix(t,async(t,i)=>{const[s,n]=r(t,i);return n?(e=n,Promise.resolve(!0)):s}),e}finally{switch(e){case 0:break;case 1:this.mu.rUnlock();break;case 2:this.mu.unlock()}}}}}}),init_treeshifttree=__esm({"pkg/doctree/treeshifttree.ts"(){init_simpletree(),TreeShiftTree=class e{d;v;trees;constructor(e,t){if(t<=0)throw new Error("length must be > 0");this.d=e,this.v=0,this.trees=[];for(let e=0;e<t;e++)this.trees.push(newSimpleTree())}static newTreeShiftTree(t,r){return new e(t,r)}shape(t,r){if(t!==this.d)throw new Error("dimension mismatch");if(r>=this.trees.length)throw new Error("value out of range");const i=Object.create(e.prototype);return Object.assign(i,this),i.v=r,i}get(e){return this.trees[this.v].get(e)}longestPrefix(e){return this.trees[this.v].longestPrefix(e)}insert(e,t){return this.trees[this.v].insert(e,t)}async walkPrefix(e,t,r){return await this.trees[this.v].walkPrefix(e,t,r)}delete(e){for(const t of this.trees)t.tree.delete(e)}async deletePrefix(e){let t=0;for(const r of this.trees)t+=await r.tree.deletePrefix(e);return t}lock(e){if(e){for(const e of this.trees)e.mu.lock();return()=>{for(const e of this.trees)e.mu.unlock()}}for(const e of this.trees)e.mu.rLock();return()=>{for(const e of this.trees)e.mu.rUnlock()}}}}}),init_nodeshifttree=__esm({"pkg/doctree/nodeshifttree.ts"(){init_radix2(),init_dimensions(),init_support(),NodeShiftTree=class e{tree;dims;shifter;mu;constructor(e){if(!e.shifter)throw new Error("Shifter is required");this.shifter=e.shifter,this.tree=new Tree,this.dims=[0];let t=!1,r=0;this.mu={lock:()=>{for(;t||r>0;);t=!0},unlock:()=>{t=!1},rLock:()=>{for(;t;);r++},rUnlock:()=>{r--},tryLock:()=>!(t||r>0||(t=!0,0))}}static new(t){return new e(t)}delete(e){this.deleteInternal(e)}async deleteAll(e){await this.tree.walkPrefix(e,(e,t)=>{const[r,i]=this.tree.delete(e);return Promise.resolve(!1)})}async deletePrefix(e){let t=0;const r=[];await this.tree.walkPrefix(e,(e,t)=>(r.push(e),Promise.resolve(!1)));for(const e of r)this.deleteInternal(e)&&t++;return t}deleteInternal(e){let t=!1;const[r,i]=this.tree.get(e);if(i){const[i,s]=this.shifter.delete(r,this.dims);t=i,s&&this.tree.delete(e)}return t}async deletePrefixAll(e){let t=0;return await this.tree.walkPrefix(e,(e,r)=>{const[i,s]=this.tree.delete(e);return s&&t++,Promise.resolve(!1)}),t}increment(e){return this.shape(e,this.dims[e]+1)}insertIntoCurrentDimension(e,t){e=mustValidateKey(cleanKey(e));const[r,i]=this.tree.get(e);return i&&(t=this.shifter.insertInto(r,t,this.dims)),this.tree.insert(e,t),[t,!0]}insertIntoValuesDimension(e,t){e=mustValidateKey(cleanKey(e));const[r,i]=this.tree.get(e);return i&&(t=this.shifter.insert(r,t)),this.tree.insert(e,t),[t,!0]}insertRawWithLock(e,t){this.mu.lock();try{return this.tree.insert(e,t)}finally{this.mu.unlock()}}insertWithLock(e,t){this.mu.lock();try{return this.insertIntoValuesDimension(e,t)}finally{this.mu.unlock()}}len(){return this.tree.len()}canLock(){const e=this.mu.tryLock();return e&&this.mu.unlock(),e}lock(e){return e?this.mu.lock():this.mu.rLock(),()=>{e?this.mu.unlock():this.mu.rUnlock()}}longestPrefix(e,t,r){let i=e;for(;;){const[e,s,n]=this.tree.longestPrefix(i);if(n){const[i,n]=this.shift(s,t);if(n&&(!r||r(i)))return[e,i]}if(""===i||"/"===i)return["",void 0];const a=i.lastIndexOf("/");if(0===a)i="";else{if(!(a>0))break;i=i.substring(0,a)}}return["",void 0]}longestPrefixAll(e){const[t,,r]=this.tree.longestPrefix(e);return[t,r]}getRaw(e){const[t,r]=this.tree.get(e);return r?[t,!0]:[void 0,!1]}async walkPrefixRaw(e,t){await this.tree.walkPrefix(e,(e,r)=>t(e,r))}shape(e,t){const r=this.clone();return r.dims[e]=t,r}toString(){return`Root{${this.dims}}`}get(e){const[t]=this.getInternal(e);return t}forEachInDimension(e,t,r){e=cleanKey(e);const[i,s]=this.tree.get(e);s&&this.shifter.forEachInDimension(i,t,r)}has(e){const[,t]=this.getInternal(e);return t}clone(){const t=Object.create(e.prototype);return Object.assign(t,this),t.dims=[...this.dims],t}shift(e,t){const[r,i]=this.shifter.shift(e,this.dims,t);return[r,i]}getInternal(e){e=cleanKey(e);const[t,r]=this.tree.get(e);if(!r)return[void 0,!1];const[i,s]=this.shift(t,!0);return[i,s]}},NodeShiftTreeWalker=class e{tree;handle;prefix;lockType;noShift;exact;debug;walkContext;skipPrefixes=[];constructor(e){if(!e.tree)throw new Error("Tree is required");this.tree=e.tree,this.handle=e.handle,this.prefix=e.prefix||"",this.lockType=e.lockType||0,this.noShift=e.noShift||!1,this.exact=e.exact||!1,this.debug=e.debug||!1,this.walkContext=e.walkContext}extend(){const t=new e({tree:this.tree,handle:this.handle,prefix:this.prefix,lockType:this.lockType,noShift:this.noShift,exact:this.exact,debug:this.debug,walkContext:this.walkContext});return t.resetLocalState(),t}skipPrefix(...e){this.skipPrefixes.push(...e)}shouldSkip(e){for(const t of this.skipPrefixes)if(e.startsWith(t))return!0;return!1}async walk(){this.resetLocalState();let e=null;this.lockType>0&&(e=this.tree.lock(2===this.lockType));try{let e=null;const t=async(t,r)=>{if(this.shouldSkip(t))return!1;const[i,s,n]=this.toT(this.tree,r);if(!s)return!1;const[a,o]=await this.handle(t,i,n);return!(!a&&!o||(e=o,0))};return""!==this.prefix?await this.tree.tree.walkPrefix(this.prefix,t):await this.tree.tree.walk(t),e}finally{e&&e()}}resetLocalState(){this.skipPrefixes=[]}toT(e,t){if(this.noShift)return[t,!0,2];{const[r,i,s]=e.shifter.shift(t,e.dims,this.exact);return[r,i,s]}}}}}),init_doctree=__esm({"pkg/doctree/index.ts"(){init_dimensions(),init_support(),init_simpletree(),init_treeshifttree(),init_nodeshifttree()}}),init_shifter=__esm({"internal/domain/content/entity/shifter.ts"(){init_pagetrees(),init_doctree(),Shifter2=class{delete(e,t){return[e.delete(t[dimensionFlag.index(1)]),e.isEmpty()]}shift(e,t,r){const[i,s]=e.shift(t[dimensionFlag.index(1)],r);return null!==i?s?[i,!0,1]:[i,!0,2]:[new PageTreesNode,!1,2]}forEachInDimension(e,t,r){if(t!==dimensionFlag.index(1))throw new Error("only language dimension supported");r(e)}insertInto(e,t,r){return e.mergeWithLang(t,r[dimensionFlag.index(1)])}insert(e,t){return e.merge(t)}}}}),init_shifterpage=__esm({"internal/domain/content/entity/shifterpage.ts"(){init_pagetrees(),init_doctree(),init_shifter(),PageShifter=class extends Shifter2{shift(e,t,r){const[i,s]=e.shift(t[dimensionFlag.index(1)],r);return null!==i&&s?[i,!0,1]:[new PageTreesNode,!1,2]}}}}),init_shifterpagesource=__esm({"internal/domain/content/entity/shifterpagesource.ts"(){init_pagetrees(),init_doctree(),init_shifter(),SourceShifter=class extends Shifter2{shift(e,t,r){const[i,s]=e.shift(t[dimensionFlag.index(1)],r);return null!==i?s?[i,!0,1]:[i,!0,2]:[new PageTreesNode,!1,2]}}}});function newPageTreesNode2(e){const t=new PageTreesNode;return e&&t.setNode(e.pageIdentity(),e),t}var pageIDCounter,log23,Source,init_pagetrees=__esm({"internal/domain/content/entity/pagetrees.ts"(){init_doctree(),init_shifterpage(),init_shifterpagesource(),WeightedTermTreeNode=class{pageTreesNodeInstance;term;constructor(e,t){this.pageTreesNodeInstance=e,this.term=t}getPage(){return this.pageTreesNodeInstance.getPage()}getPages(){return this.pageTreesNodeInstance.getPages()}getResource(){return this.pageTreesNodeInstance.getResource()}isEmpty(){return this.pageTreesNodeInstance.isEmpty()}shift(e,t){return this.pageTreesNodeInstance.shift(e,t)}},PageTreesNode=class{nodes;constructor(){this.nodes=new Map}setNode(e,t){this.nodes.set(e,t)}merge(e){const t=new Map;for(const e of this.nodes.keys())t.set(e.pageLanguage(),e);for(const[r,i]of e.nodes.entries()){const e=t.get(r.pageLanguage());e?this.nodes.set(e,i):this.nodes.set(r,i)}return this}mergeWithLang(e,t){const r=new Map;for(const e of this.nodes.keys())r.set(e.pageLanguage(),e);for(const[i,s]of e.nodes.entries()){const e=r.get(i.pageLanguage());if(e){const r=this.nodes.get(e);r&&r.pageIdentity().pageLanguageIndex()===t&&this.remove(e)}this.nodes.set(i,s)}return this}remove(e){const t=this.nodes.get(e);return!!t&&(this.markStale(t),this.nodes.delete(e),!0)}delete(e){for(const[t,r]of this.nodes.entries())if(r.pageIdentity().pageLanguageIndex()===e)return this.remove(t);return!1}isEmpty(){return 0===this.nodes.size}shift(e,t){let r=null;for(const[t,i]of this.nodes.entries())if(null===r&&(r=i),i.pageIdentity().pageLanguageIndex()===e)return[newPageTreesNode2(i),!0];return null===r||t?[null,!1]:[newPageTreesNode2(r),!1]}getPage(){for(const e of this.nodes.values())if(e&&"function"==typeof e.kind)return[e,!0];return[null,!1]}getPages(){const e=[];for(const t of this.nodes.values())t&&"function"==typeof t.kind&&e.push(t);return e}getResource(){for(const e of this.nodes.values())return[e,!0];return[null,!1]}markStale(e){"staleVersions"in e&&e.staleVersions}},PageTrees=class{treePages;treeResources;treePagesResources;treeTaxonomyEntries;resourceTrees;constructor(){this.treePages=new NodeShiftTree({shifter:new PageShifter}),this.treeResources=new NodeShiftTree({shifter:new SourceShifter}),this.treeTaxonomyEntries=TreeShiftTree.newTreeShiftTree(0,10),this.treePagesResources=new WalkableTrees([]),this.resourceTrees=new MutableTrees([]),this.treePagesResources=new WalkableTrees([this.treePages,this.treeResources]),this.resourceTrees=new MutableTrees([this.treeResources])}createMutableTrees(){this.treePagesResources=new WalkableTrees([this.treePages,this.treeResources]),this.resourceTrees=new MutableTrees([this.treeResources])}get TreePages(){return this.treePages}get TreeResources(){return this.treeResources}get TreePagesResources(){return this.treePagesResources}get TreeTaxonomyEntries(){return this.treeTaxonomyEntries}get ResourceTrees(){return this.resourceTrees}}}});function newPageSource(e){return new Source(e)}var log24,ambiguousContentNode,ContentTreeReverseIndexMap,ContentTreeReverseIndex,pagePredicates,PageMapQueryPagesBelowPathImpl,PageMapQueryPagesInSectionImpl,PageMap,init_pagesource=__esm({"internal/domain/content/entity/pagesource.ts"(){init_log(),init_identity(),pageIDCounter=0,log23=getDomainLogger("content",{component:"pagesource"}),Source=class{id;identity;file;constructor(e){this.id=(++pageIDCounter).toString(),this.identity=new Identity(pageIDCounter),this.file=e}sourceKey(){return`${this.identity.lang}/${this.file.filename()}`.replace(/\\/g,"/")}async contentSource(){return await this.readSourceAll()}async readSourceAll(){try{const e=await this.file.open(),t=await e.stat(),r=new Uint8Array(t.size()),i=await e.read(r);return await e.close(),i.buffer}catch(e){const t=e instanceof Error?e.message:String(e);throw new Error(`Failed to read file content: ${t}`)}}async posOffset(e){try{const t=await this.contentSource();return function(e,t,r){if(r<0)return{filename:e,lineNumber:0,columnNumber:0,offset:0};const i=t.slice(0,r);let s=1;for(let e=0;e<i.length;e++)10===i[e]&&s++;let n=-1;for(let e=i.length-1;e>=0;e--)if(10===i[e]){n=e;break}return{filename:e,lineNumber:s,columnNumber:r-n,offset:r}}(this.file.filename(),t,e)}catch(e){throw new Error(`failed to read content source for "${this.file.filename()}": ${e}`)}}pageIdentity(){return this.identity}pageFile(){return this.file}staleVersions(){return[]}section(){return this.file.section()}paths(){return this.file.paths()}path(){return this.file.paths().path()}slug(){return this.pathToSlug(this.path())}pathToSlug(e){let t=e.replace(/^\//,"");return t=t.replace(/\.md$/,""),t.endsWith("/index")&&(t=t.replace(/\/index$/,"")),"index"!==t&&""!==t||(t="index"),t.endsWith("/_index")&&(t=t.replace(/\/_index$/,"")),t}opener(){return()=>this.file.open()}openReader(){return{read:async()=>new Uint8Array(0)}}async content(){try{return log23.error(`Reading content not implemented from: ${this.file.filename()}`),new Uint8Array(0)}catch(e){const t=`failed to read content source for "${this.file.filename()}": ${e}`;throw log23.error(t),new Error(t)}}}}});function addTrailingSlash(e){return e.endsWith("/")||(e+="/"),e}var log25,PagesCollector,log26,Content2,MDConverter,Content3,init_pagemap=__esm({"internal/domain/content/entity/pagemap.ts"(){init_pagetrees(),init_pagesource(),init_type7(),init_doctree(),init_sort(),init_log(),log24=getDomainLogger("content",{component:"pagemap"}),ambiguousContentNode=new PageTreesNode,ContentTreeReverseIndexMap=class{initOnce=!1;m=new Map;constructor(){}},ContentTreeReverseIndex=class{initFn;contentTreeReverseIndexMap;constructor(e){this.initFn=e,this.contentTreeReverseIndexMap=new ContentTreeReverseIndexMap}reset(){this.contentTreeReverseIndexMap=new ContentTreeReverseIndexMap}get(e){return this.contentTreeReverseIndexMap.initOnce||(this.contentTreeReverseIndexMap.m=new Map,this.initFn(this.contentTreeReverseIndexMap.m),this.contentTreeReverseIndexMap.initOnce=!0),this.contentTreeReverseIndexMap.m.get(e)||null}},pagePredicates={kindPage:e=>"page"===e.kind(),kindSection:e=>"section"===e.kind(),kindHome:e=>"home"===e.kind(),kindTerm:e=>"term"===e.kind(),shouldListLocal:e=>!e.shouldList||e.shouldList(!1),shouldListGlobal:e=>!e.shouldList||e.shouldList(!0),shouldListAny:e=>!e.shouldListAny||e.shouldListAny(),shouldLink:e=>!e.noLink||!e.noLink()},PageMapQueryPagesBelowPathImpl=class{path;keyPart;include;constructor(e,t,r=pagePredicates.shouldListLocal){this.path=e,this.keyPart=t,this.include=r}key(){return this.path+"/"+this.keyPart}},PageMapQueryPagesInSectionImpl=class extends PageMapQueryPagesBelowPathImpl{recursive;includeSelf;index;constructor(e,t,r,i,s,n){super(e,t,n),this.recursive=r,this.includeSelf=i,this.index=s}key(){return"gagesInSection/"+super.key()+"/"+this.recursive.toString()+"/"+this.index.toString()+"/"+this.includeSelf.toString()}},PageMap=class extends PageTrees{pageReverseIndex=null;pageBuilder;constructor(e){super(),this.pageBuilder=e}setupReverseIndex(){this.pageReverseIndex=new ContentTreeReverseIndex(async e=>{const t=new NodeShiftTreeWalker({tree:this.treePages,lockType:1,handle:async(t,r,i)=>{if(r){const[t,i]=r.getPage();if(!i)return[!1,null];t.pageFile&&t.pageFile()&&((t,r)=>{const i=e.get(t);i&&i!==ambiguousContentNode?e.set(t,ambiguousContentNode):i||e.set(t,r)})(t.paths().baseNameNoIdentifier(),r)}return[!1,null]}});try{await t.walk()}catch(e){log24.error(`setupReverseIndex error: ${e}`)}})}insertResourceNode(e,t){const r=this.treeResources,i=r.lock(!0);try{r.insertIntoValuesDimension(e,t)}finally{i()}}async addFi(e){if(e.fileInfo().isDir())return;const t=newPageSource(e),r=t.paths().base();switch(t.file.getBundleType()){case 0:this.insertResourceNode(r,newPageTreesNode2(t));break;case 1:const e=await this.pageBuilder.withSource(t).build();if(!e)return;this.insertResourceNode(r,newPageTreesNode2(e));break;default:const i=await this.pageBuilder.withSource(t).build();this.treePages.insertWithLock(t.paths().base(),newPageTreesNode2(i))}}async assemble(){await this.assembleStructurePages(),await this.applyAggregates(),await this.cleanPages(),await this.assembleTerms()}async assembleTerms(){for(const e of this.pageBuilder.langSvc.languageIndexes()){const t=this.treePages.shape(0,e),r=this.treeTaxonomyEntries.shape(0,e);await this.pageBuilder.term.assemble(t,r,this.pageBuilder,e)}}async cleanPages(){}async applyAggregates(){}async assembleStructurePages(){await this.addMissingTaxonomies();for(const e of this.pageBuilder.langSvc.languageIndexes()){const t=this.treePages.shape(0,e);await this.pageBuilder.section.assemble(t,this.pageBuilder,e)}await this.addMissingStandalone()}async addMissingTaxonomies(){const e=this.treePages.lock(!0);try{for(const e of this.pageBuilder.langSvc.languageIndexes()){const t=this.treePages.shape(0,e);await this.pageBuilder.taxonomy.assemble(t,this.pageBuilder,e)}}finally{e()}}async addMissingStandalone(){const e=this.treePages,t=e.lock(!0);try{await this.pageBuilder.standalone.assemble(e,this.pageBuilder)}finally{t()}}async getResourcesForPage(e){const t=[];return await this.forEachResourceInPage(e,0,!1,(e,r,i)=>{const[s,n]=r.getResource();return n&&t.push(s),[!1,null]}),t}async forEachResourceInPage(e,t,r,i){let s=e.paths().base();"/"===s&&(s="");const n=addTrailingSlash(s),a="page"!==e.kind(),o=new NodeShiftTreeWalker({tree:this.treeResources.shape(0,e.pageIdentity().pageLanguageIndex()),prefix:n,lockType:t,exact:r,handle:async(e,t,r)=>{if(a){const[t]=this.treePages.longestPrefixAll(e);if(t!==s&&this.pathDir(t)!==this.pathDir(e))return o.skipPrefix(t+"/"),[!1,null]}return i(e,t,r)}});try{await o.walk()}catch(e){log24.error(`forEachResourceInPage error: ${e}`)}}async getPagesInSection(e,t){const r=t.key(),i=this.treePages.shape(0,e);return this.getOrCreatePagesFromCacheSync(null,r,async e=>{const r=addTrailingSlash(t.path),s=[];let n="";const a=t.include,o=new NodeShiftTreeWalker({tree:i,prefix:r,handle:async(e,r,i)=>{if(t.recursive){const[e,t]=r.getPage();return t&&a(e)&&s.push(e),[!1,null]}const[l,c]=r.getPage();if(c&&a(l)&&s.push(l),!l.isPage||!l.isPage()){const t=e+"/";""!==n&&n===t||o.skipPrefix(t),n=t}return[!1,null]}});try{if(await o.walk(),t.includeSelf){const e=i.get(t.path);if(e){const[t,r]=e.getPage();r&&a(t)&&s.push(t)}}const e=s;return function(e){if(0===e.length)return;const t=e[0].pageWeight();e.every(e=>e.pageWeight()===t)?sortByTitle(e):function(e){pageBy(weight).sort(e)}(e)}(e),Promise.resolve(e)}catch(e){log24.error(`getPagesInSection error: ${e}`)}return Promise.resolve(s)})}async getOrCreatePagesFromCacheSync(e,t,r){return await r(t)}async getPagesWithTerm(e,t){const r=t.key(),i=this.treeTaxonomyEntries.shape(0,e);return await this.getOrCreatePagesFromCacheSync(null,r,async e=>{const r=[],s=t.include;try{await i.walkPrefix(0,addTrailingSlash(t.path),(e,t)=>{const[i,n]=t.getPage();return n&&s(i)&&r.push(i),[!1,null]});const e=r;return sortByTitle(e),e}catch(e){log24.error(`getPagesWithTerm error: ${e}`)}return r})}getTermsForPageInTaxonomy(e,t,r){const i=((s=r).startsWith("/")||(s="/"+s),s);var s;const n=this.treeTaxonomyEntries.shape(0,e);return this.getOrCreatePagesFromCacheSync(null,i+t,async e=>{const r=[];try{await n.walkPrefix(0,addTrailingSlash(i),(e,i)=>(e.endsWith(t)&&r.push(i.term.page),[!1,null]));const e=r;return sortByTitle(e),e}catch(e){log24.error(`getTermsForPageInTaxonomy error: ${e}`)}return r})}async getSections(e,t){const r=[];let i="";const s=this.treePages.shape(0,e),n=new NodeShiftTreeWalker({tree:s,prefix:t,handle:async(e,t,s)=>{const[a,o]=t.getPage();return o?(a.isPage&&a.isPage()||(""!==i&&e.startsWith(i)||(a.isSection&&a.isSection()&&a.shouldList&&a.shouldList(!1)&&a.parent&&a.parent()===a?r.push(a):n.skipPrefix(e+"/")),i=e+"/"),[!1,null]):[!1,null]}});try{await n.walk();const e=r;return sortByTitle(e),e}catch(e){log24.error(`getSections error: ${e}`)}return r}pathDir(e){const t=e.lastIndexOf("/");return-1===t?"":e.substring(0,t)}}}}),init_pagecollector=__esm({"internal/domain/content/entity/pagecollector.ts"(){init_content3(),init_log(),log25=getDomainLogger("content",{component:"pagecollector"}),PagesCollector=class{m;fs;processedPaths=new Set;constructor(e,t){this.m=e,this.fs=t}async collect(){try{const e="",t=this.fs.contentFs();for(const r of t){this.processedPaths.clear();const t=await r.stat(e);await this.collectDir(r,e,t)}}catch(e){log25.error(`Failed to collect directory: ${e}, continuing...`)}}async collectDir(e,t,r){try{await this.fs.walkContent(e,t,{hookPre:async(e,t,r)=>{const i=t;if(this.processedPaths.has(i))return log25.warn("Path already processed!",{path:i,dirName:e.name(),dirIsDir:e.isDir(),readdirLength:r.length}),[];if(this.processedPaths.add(i),0===r.length)return[];for(const e of r){if(e.isDir&&e.isDir())continue;const t=newFileInfo2(e);await this.m.addFi(t)}return r},walkFn:async(e,t)=>{}},{info:r})}catch(e){throw log25.error(`Failed to collect directory: ${e}`,{path:t,rootName:r.name(),rootIsDir:r.isDir(),stack:e.stack||"No stack trace available"}),new Error(`Failed to collect directory: ${e}`)}}async handleBundleLeaf(e,t,r,i){const s=t.paths(),n=async(e,r)=>{if(r.isDir())return;const i=newFileInfo2(r);r!==t.fileInfo()&&(i.isLeafBundle()&&i.paths().dir()===s.dir()||i.shiftToResource()),await this.m.addFi(i)},a=this.fs.contentFs();for(const t of a)await this.fs.walkContent(t,r,{walkFn:n},{info:e,dirEntries:i})}}}}),init_entity=__esm({"internal/domain/content/entity/index.ts"(){init_content2(),init_pagemap(),init_pagetrees(),init_pagecollector()}}),init_content2=__esm({"internal/domain/content/entity/content.ts"(){init_entity(),init_doctree(),init_fileinfo2(),init_log(),init_paths(),log26=getDomainLogger("content",{component:"content"}),Content2=class{fs;converter;pageMap;translator;pageCollected=!1;constructor(e,t,r,i){this.fs=e,this.converter=t,this.pageMap=r,this.translator=i}setTemplateSvc(e){this.pageMap.pageBuilder.templateSvc=e}async renderString(e,...t){if(t.length<1||t.length>2)throw new Error("RenderString want 1 or 2 arguments");let r=1;if(1!==t.length){const e=t[0];if("object"!=typeof e||null===e)throw new Error("first argument must be a map");throw new Error("RenderString not implemented yet")}r=0;const i=t[0],s=String(i);return newFileInfo2(this.fs.newFileMetaInfoWithContent(s)),s}async collectPages(){if(this.pageCollected)log26.info("Pages have already been collected, skipping.");else try{await this.process(),await this.assemble(),this.pageCollected=!0}catch(e){throw new Error(`process/assemble: ${e}`)}}async process(){try{const e=new PagesCollector(this.pageMap,this.fs);await e.collect()}catch(e){throw e}}async assemble(){try{await this.pageMap.assemble()}catch(e){throw e}}async getPageSources(e){let t=e.paths().base();return"/"===t&&(t=""),await this.pageMap.getResourcesForPage(e)}async globalPages(e){return await this.pageMap.getPagesInSection(e,new PageMapQueryPagesInSectionImpl("","global",!0,!0,0,pagePredicates.shouldListGlobal))}async globalRegularPages(){return await this.pageMap.getPagesInSection(0,new PageMapQueryPagesInSectionImpl("","global",!0,!0,0,e=>pagePredicates.shouldListGlobal(e)&&pagePredicates.kindPage(e)))}async walkPages(e,t){const r=this.pageMap.treePages.shape(0,e),i=new NodeShiftTreeWalker({tree:r,handle:async(e,r,i)=>{const[s,n]=r.getPage();if(!n)return[!1,null];try{await t(s)}catch(e){return[!1,e instanceof Error?e:new Error(String(e))]}return[!1,null]}});try{await i.walk()}catch(t){throw log26.error(`WalkPages failed for langIndex ${e}:`,t),t}}async walkTaxonomies(e,t){try{const r=this.pageMap.treePages.shape(0,e),i=this.pageMap.pageBuilder.taxonomy;for(const s of i.views){const n=i.pluralTreeKey(s.plural()),a=new NodeShiftTreeWalker({tree:r,prefix:addTrailingSlash(n),lockType:1,handle:async(r,i,n)=>{const[a,o]=i.getPage();if(!o)return[!1,null];if("term"===a.kind()){const i=a;if(!i.term)return[!0,new Error("term is empty")];const n=i.term.toLowerCase();try{const a=this.pageMap.treeTaxonomyEntries.shape(0,e);return await a.walkPrefix(1,addTrailingSlash(r),(e,r)=>{const[a,o]=r.getPage();return o?(t(s.plural(),n,{weight:()=>r.term.Weight(),ordinal:()=>r.term.Ordinal(),page:()=>a,owner:()=>i}).catch(e=>{log26.error("Error in taxonomy walker:",e)}),[!1,null]):[!1,null]}),[!1,null]}catch(e){return[!0,e]}}return[!1,null]}});await a.walk()}}catch(e){throw e}}getPageFromPath(e,t){try{const r=PathDomain.createProcessor().parse(PATH_CONSTANTS.COMPONENT_FOLDER_CONTENT,t);let i=this.pageMap.treePages.shape(0,e).get(r.base());if(i){const[e,t]=i.getPage();if(t)return e}return null}catch(e){return log26.error(`❌ Content.getPageFromPath error for path "${t}":`,e),null}}getPageFromFile(e,t){try{let r=this.pageMap.treePages.shape(0,e).get(t.paths().base());if(r){const[e,t]=r.getPage();if(t)return e}return null}catch(e){return log26.error(`❌ Content.getPageFromPath error for path "${t.path()}":`,e),null}}async handleChangeFiles(e){const t=[];for(const[r,i]of e)try{await this.addOrUpdateFile(i,t)}catch(e){log26.error(`Failed to process file change for ${r}:`,e)}return t}async addOrUpdateFile(e,t){if(!e.isDir())try{const r=newFileInfo2(e),i=r.paths().base();i&&t.push(i),await this.pageMap.addFi(r);const s=this.getPageFromFile(0,r);s&&s.pageIdentity&&s.pageIdentity().markStale()}catch(t){throw log26.error(`Failed to add/update file in PageMap: ${e.fileName()}`,t),t}}translate(e,t){return this.translator?this.translator.translate(e,t):(log26.warn("Translator not initialized, returning fallback translation"),`[i18n] ${t}`)}getAvailableLanguages(){return this.translator?this.translator.getAvailableLanguages():[]}hasLanguageSupport(e){return!!this.translator&&this.translator.hasLanguage(e)}}}}),init_converter=__esm({"internal/domain/content/entity/converter.ts"(){MDConverter=class{md;constructor(e){this.md=e}async convert(e,t){return this.md.render(t,e)}async parseContent(e){return this.md.parseContent(e)}async parseAndRenderContent(e,t){return this.md.parseAndRenderContent(e,t)}async prepareRender(e){return this.md.prepareRender(e)}}}});function newContent(e){return new Content3(e)}var log27,PAGE_HOME_BASE,Section,STANDALONE_PAGE_404_BASE,STANDALONE_PAGE_SITEMAP_BASE,Standalone,Output,PaginatorImpl,PagerImpl,PaginatorManagerImpl,Scratch,init_pagecontent=__esm({"internal/domain/content/entity/pagecontent.ts"(){Content3=class{rawSource;frontMatter;renderedContent="";summary="";wordCount=0;readingTime=0;toc;lazyRendered=!0;lazyRender;constructor(e){this.rawSource=e}updateWithContentResult(e){e.frontMatter&&(this.frontMatter=e.frontMatter),this.renderedContent=e.renderedContent||"",this.summary=e.summary,this.wordCount=e.wordCount||0,this.readingTime=e.readingTime||0}getRawSource(){return this.rawSource}async RenderedContent(){return await this.render(),this.renderedContent}async Summary(){return await this.render(),this.summary}async WordCount(){return await this.render(),this.wordCount}async ReadingTime(){return await this.render(),this.readingTime}async render(){return this.lazyRendered&&this.lazyRender&&(await this.lazyRender(),this.lazyRendered=!1),Promise.resolve()}isEmpty(){return!this.rawSource||0===this.rawSource.length}}}}),init_section=__esm({"internal/domain/content/entity/section.ts"(){init_pagetrees(),init_fileinfo2(),init_pagesource(),init_kind(),init_doctree(),init_log(),log27=getDomainLogger("content",{component:"section"}),PAGE_HOME_BASE="/",Section=class{home;seen;fsSvc;constructor(e){this.home=null,this.seen={},this.fsSvc=e}isHome(e){return""===e}isSectionExist(e){return!(""!==e&&!this.seen[e]&&(this.seen[e]=!0,1))}async assemble(e,t,r){this.seen={};const i=new NodeShiftTreeWalker({tree:e,lockType:2,handle:async(e,s,n)=>{if(!s)throw new Error("n is null");const[a,o]=s.getPage();if(!o)return[!1,null];if(this.isHome(e))return this.home=a,[!1,null];const l=a.kind();if(l!==getKindMain("page")&&l!==getKindMain("section"))return[!1,null];const c=a.paths().sections();for(const e of c)if(!this.isSectionExist(e))try{const s=newPageSource(newFileInfo2(this.fsSvc.newFileMetaInfo("/"+e+"/_index.md"))),n=s.paths().base();if(!i.tree.get(n)){const e=await t.withSource(s).withLangIdx(r).kindBuild();i.tree.insertIntoValuesDimension(n,newPageTreesNode2(e))}}catch(e){return[!1,e]}return[!1,null]}});try{await i.walk()}catch(e){throw log27.error("Error walking pages:",e),e}if(!this.home&&(await this.createHome(t),this.home)){const t=this.home;e.insertWithLock(t.paths().base(),newPageTreesNode2(t))}}async createHome(e){const t=newPageSource(newFileInfo2(this.fsSvc.newFileMetaInfo("/_index.md"))),r=await e.withSource(t).kindBuild();this.home=r}}}}),init_standalone=__esm({"internal/domain/content/entity/standalone.ts"(){init_pagetrees(),init_fileinfo2(),init_pagesource(),STANDALONE_PAGE_404_BASE="404",STANDALONE_PAGE_SITEMAP_BASE="_sitemap",Standalone=class{fsSvc;constructor(e){this.fsSvc=e}async assemble(e,t){const r="/"+STANDALONE_PAGE_404_BASE,i=await this.addStandalone(r,t);e.insertIntoValuesDimension(r,newPageTreesNode2(i));const s="/"+STANDALONE_PAGE_SITEMAP_BASE,n=await this.addStandalone(s,t);e.insertIntoValuesDimension(s,newPageTreesNode2(n))}async addStandalone(e,t){const r=newPageSource(newFileInfo2(this.fsSvc.newFileMetaInfo(e+".md")));return await t.withSource(r).kindBuild()}}}}),init_pageoutput=__esm({"internal/domain/content/entity/pageoutput.ts"(){init_content3(),Output=class{source;pageKind;baseName;target=null;constructor(e,t){this.source=e,this.pageKind=t,this.baseName="",this.setBasename(),this.buildTarget()}setBasename(){switch(this.pageKind){case getKindMain("404"):this.baseName="404";break;case getKindMain("sitemap"):this.baseName="sitemap";break;default:this.baseName=this.source.paths().baseNameNoIdentifier()||"index"}}buildTarget(){let e="",t="";const r="index";switch(this.pageKind){case getKindMain("home"):e=`${r}.html`,t="";break;case getKindMain("page"):const i=this.source.paths().containerDir();e=i&&"/"!==i?`${i}/${this.baseName}.html`:`/${this.baseName}.html`,t=i||"";break;case getKindMain("section"):case getKindMain("taxonomy"):case getKindMain("term"):const s=this.source.paths().dir();e=s?`${s}/${r}.html`:`${r}.html`,t=s||"";break;case getKindMain("404"):const n=this.source.paths().dir();e=n?`${n}/${this.baseName}.html`:`${this.baseName}.html`,t=n||"";break;case getKindMain("sitemap"):const a=this.source.paths().dir();e=a?`${a}/${this.baseName}.xml`:`${this.baseName}.xml`,t=a||"";break;default:e=`${r}.html`,t=""}this.target={prefix:this.source.identity.pageLanguage(),filePath:e,subResourceBaseTarget:t}}createBasicResult(){return{bytes:()=>new Uint8Array,headers:()=>[],tableOfContents:()=>({toHTML:(e,t,r)=>""})}}output(e){return{targetFileBase:()=>{if(!this.target)return"index.html";const e=this.target.filePath,t=e.lastIndexOf("/");return t>=0?e.substring(t+1):e},targetFilePath:()=>this.target.filePath,targetSubResourceDir:()=>this.target.subResourceBaseTarget,targetPrefix:()=>this.target.prefix,content:async()=>e.content?e.content.RenderedContent():"",summary:async()=>e.content?e.content.Summary():"",tableOfContents:()=>e.content&&e.content.toc?e.content.toc.toHTML(1,6,!1):"",result:()=>this.createBasicResult(),readingTime:async()=>e.content?e.content.ReadingTime():0,wordCount:async()=>e.content?e.content.WordCount():0}}}}}),init_paginator=__esm({"internal/domain/content/entity/paginator.ts"(){init_log(),getDomainLogger("content",{component:"paginator"}),PaginatorImpl=class{paginatedElements;_pagers;base;total;size;constructor(e,t,r,i){if(this.paginatedElements=e,this.base=i,this.total=t,this.size=r,this._pagers=[],e.length>0)for(let t=0;t<e.length;t++)this._pagers.push(new PagerImpl(t+1,this));else this._pagers.push(new PagerImpl(1,this))}totalPages(){return this.paginatedElements.length}pagers(){return[...this._pagers]}getElement(e){return 0===this.paginatedElements.length?[]:this.paginatedElements[e-1]||[]}getBase(){return this.base}getPagers(){return this._pagers}getAllPages(){const e=[];for(const t of this.paginatedElements)e.push(...t);return e}},PagerImpl=class{number;paginator;constructor(e,t){this.number=e,this.paginator=t}pageNumber(){return this.number}totalPages(){return this.paginator.totalPages()}url(){const e=this.pageNumber();if(e>1){const t=`/page/${e}/`;return this.pathJoin(this.paginator.getBase(),t)}return this.paginator.getBase()}pages(){return this.element()}allPages(){return this.paginator.getAllPages()}pagers(){return this.paginator.pagers()}first(){return this.paginator.getPagers()[0]}last(){const e=this.paginator.getPagers();return e[e.length-1]}hasPrev(){return this.pageNumber()>1}prev(){return this.hasPrev()?this.paginator.getPagers()[this.pageNumber()-2]:null}hasNext(){return this.pageNumber()<this.paginator.totalPages()}next(){return this.hasNext()?this.paginator.getPagers()[this.pageNumber()]:null}element(){return this.paginator.getElement(this.pageNumber())}pathJoin(e,t){return e.endsWith("/")&&(e=e.slice(0,-1)),t.startsWith("/")||(t="/"+t),e+t}},PaginatorManagerImpl=class{currentPager=null;initialized=!1;svc;page;constructor(e,t){this.svc=e,this.page=t}async current(){return this.initialized||await this.initializePaginator(),this.currentPager?this.currentPager:new PaginatorImpl([],0,10,this.page.paths().base()).pagers()[0]}setCurrent(e){this.currentPager=e}async paginate(e){if(!this.initialized){const t=this.svc.pageSize();let r;r=Array.isArray(e)&&e.length>0&&"key"in e[0]?this.newPaginatorFromPageGroups(e,t,this.page.paths().base()):this.newPaginatorFromPages(e,t,this.page.paths().base()),this.currentPager=r.pagers()[0],this.initialized=!0}return this.currentPager||this.current()}async paginator(){return this.initialized||await this.initializePaginator(),this.currentPager||this.current()}async initializePaginator(){try{const e=this.svc.pageSize();let t=[];switch(this.page.kind()){case"home":t=await this.svc.globalRegularPages();break;case"term":case"taxonomy":const e=await this.page.pages();t=e?.length?Array.from({length:e.length},(t,r)=>e[r]):[];break;default:const r=await this.page.regularPages();t=r&&r.length>0?Array.from({length:r.length},(e,t)=>r[t]):await this.svc.globalRegularPages()}const r=this.page.paths().base(),i=this.newPaginatorFromPages(t,e,r);this.currentPager=i.pagers()[0],this.initialized=!0}catch(e){const t=this.page.paths().base(),r=new PaginatorImpl([],0,10,t);this.currentPager=r.pagers()[0],this.initialized=!0}}newPaginatorFromPages(e,t,r){if(t<=0)throw new Error("paginator size must be positive");const i=this.splitPages(e,t);return new PaginatorImpl(i,e.length,t,r)}newPaginatorFromPageGroups(e,t,r){if(t<=0)throw new Error("paginator size must be positive");const i=[];if(e&&e.length>0)for(let t=0;t<e.length;t++){const r=e[t];if(r&&r.pages){const e=r.pages();if(e)for(let t=0;t<e.length;t++)i.push(e[t])}}const s=this.splitPages(i,t);return new PaginatorImpl(s,i.length,t,r)}splitPages(e,t){const r=[];for(let i=0;i<e.length;i+=t){const s=Math.min(i+t,e.length);r.push(e.slice(i,s))}return r}}}}),init_scratch=__esm({"pkg/maps/scratch.ts"(){Scratch=class{values;constructor(){this.values=new Map}add(e,t){const r=this.values.get(e);let i;return i=void 0!==r?Array.isArray(r)?[...r,t]:"number"==typeof r&&"number"==typeof t||"string"==typeof r&&"string"==typeof t?r+t:t:t,this.values.set(e,i),""}Add(e,t){return this.add(e,t)}set(e,t){return this.values.set(e,t),""}Set(e,t){return this.set(e,t)}delete(e){return this.values.delete(e),""}get(e){return this.values.get(e)}Get(e){return this.get(e)}getValues(){return this.values}setInMap(e,t,r){let i=this.values.get(e);return i&&"object"==typeof i||(i={},this.values.set(e,i)),i[t]=r,""}}}});function dir(e){const t=e.lastIndexOf("/");if(-1===t)return"";let r=e.slice(0,t+1);return r.length>1&&r.endsWith("/")&&(r=r.slice(0,-1)),r}var PageImpl,TaxonomyPageImpl,TermPageImpl,init_paths2=__esm({"pkg/paths/index.ts"(){}});import path18 from"path";var Meta,Layout,ShortcodeWithPage,BASE_FILE_BASE,BASE_DEFAULT,PARTIALS_PREFIX,TemplateError,BaseOf,init_page=__esm({"internal/domain/content/entity/page.ts"(){init_content3(),init_pageoutput(),init_paginator(),init_scratch(),init_pagemap(),init_paths2(),init_doctree(),init_sort(),init_log(),getDomainLogger("content",{component:"page"}),PageImpl=class{source;content;meta;layout;pagerManager;title_;description_="";kind_;pageMap;output_=null;store_=null;constructor(e,t,r,i,s="",n="page",a=null){this.source=e,this.content=t,this.meta=r,this.layout=i,this.title_=s,this.kind_=n,this.pageMap=a,this.pagerManager=new PaginatorManagerImpl({pageSize:()=>10,globalRegularPages:async()=>[]},this)}rawContent(){if(!this.content)return"";const e=this.content.getRawSource();return(new TextDecoder).decode(e)}pageIdentity(){return this.source.identity}pageFile(){return this.source.file}staleVersions(){return[]}section(){return this.source.file.section()}paths(){return this.source.file.paths()}path(){return this.source.file.paths().path()}slug(){return this.pathToSlug(this.path())}pathToSlug(e){let t=e.replace(/^\//,"");return t=t.replace(/\.md$/,""),t.endsWith("/index")&&(t=t.replace(/\/index$/,"")),"index"!==t&&""!==t||(t="index"),t.endsWith("/_index")&&(t=t.replace(/\/_index$/,"")),t}posOffset(e){return this.source.posOffset(e)}description(){return this.description_}get Description(){return this.description()}StaticURL(e){return/^(https?:)?\/\//.test(e)?e:((e=(e=path18.normalize(e)).replace(/\\/g,"/")).startsWith("/")&&(e=e.slice(1)),`${this.meta.pageBaseUrl().replace(/\/+$/,"")}/${e}`)}params(){return this.meta.params()}get Params(){return this.params()}store(){return this.store_||(this.store_=new Scratch),this.store_}get Store(){return this.store()}scratch(){return this.store()}get Scratch(){return this.scratch()}pageBaseUrl(){return this.meta.pageBaseUrl()}pageWeight(){return this.meta.pageWeight()}pageDate(){return this.meta.pageDate()}publishDate(){return this.meta.publishDate()}async relatedKeywords(e){return this.meta.relatedKeywords(e)}shouldList(e){return this.meta.shouldList(e)}shouldListAny(){return this.meta.shouldListAny()}noLink(){return this.meta.noLink()}organization(){return this.meta.organization()}author(){return this.meta.author()}menu(){return this.meta.menu()}async current(){return await this.pagerManager.current()}setCurrent(e){this.pagerManager.setCurrent(e)}async paginator(){return await this.pagerManager.paginator()}async paginate(e){return this.pagerManager.paginate(e)}file(){return this.source.file}get Type(){return this.file().type()}name(){return this.source.file.baseFileName()}title(){return this.title_}get Title(){return this.title()}kind(){return this.kind_}isHome(){return this.kind()===getKindMain("home")}isPage(){return this.kind()===getKindMain("page")}isSection(){return this.kind()===getKindMain("section")}isAncestor(e){return e.path()!==this.path()&&e.paths().base().startsWith(this.paths().base())}eq(e){return this.pageIdentity().identifierBase()===e.pageIdentity().identifierBase()}layouts(){switch(this.kind_){case getKindMain("home"):return this.source.file.isBranchBundle()?this.layout.homeList():this.layout.home();case getKindMain("page"):return this.layout.page(this.source.file.section(),this.source.file.baseFileName());case getKindMain("section"):return this.layout.section(this.source.file.section());case getKindMain("taxonomy"):return this.layout.taxonomy();case getKindMain("term"):return this.layout.term();case getKindMain("404"):return this.layout.standalone404();case getKindMain("sitemap"):return this.layout.standaloneSitemap();default:return[]}}output(){return this.output_||(this.output_=new Output(this.source,this.kind())),this.output_.output(this)}get TargetPath(){return this.output().targetFilePath()}get Summary(){return this.output().summary()}truncated(){return!0}parent(){if(this.isHome())return null;let e=this.paths().containerDir();if(""===e)return null;for(;;){const t=this.pageMap?.treePages.longestPrefix(e,!0);if(!t)return null;const[r,i]=t;if(!i)return null;const[s,n]=i.getPage();if(!s)return null;if(this.isBundled())return n?s:null;if(!s.isPage())return n?s:null;e=dir(e)}}async Pages(){return await this.pages()}async pages(){const e=this.pageIdentity().pageLanguageIndex();switch(this.kind()){case PageKind.PAGE:case PageKind.SECTION:case PageKind.HOME:return await this.pageMap.getPagesInSection(e,new PageMapQueryPagesInSectionImpl(this.paths().base(),"page-section",!1,!1,e,e=>pagePredicates.shouldListLocal(e)&&(pagePredicates.kindPage(e)||pagePredicates.kindSection(e))));case PageKind.TERM:return await this.pageMap.getPagesWithTerm(e,new PageMapQueryPagesBelowPathImpl(this.paths().base(),"term"));case PageKind.TAXONOMY:return await this.pageMap.getPagesInSection(e,new PageMapQueryPagesInSectionImpl(this.paths().base(),"term",!0,!1,e,e=>pagePredicates.shouldListLocal(e)&&pagePredicates.kindTerm(e)));default:return Promise.resolve([])}}prevInSection(){return null}nextInSection(){return null}sections(e){return[]}async regularPages(){const e=this.pageIdentity().pageLanguageIndex();switch(this.kind()){case PageKind.PAGE:case PageKind.SECTION:case PageKind.HOME:case PageKind.TAXONOMY:return this.pageMap?await this.pageMap.getPagesInSection(e,new PageMapQueryPagesInSectionImpl(this.paths().base(),"",!1,!1,e,e=>pagePredicates.shouldListLocal(e)&&pagePredicates.kindPage(e))):[];case PageKind.TERM:return this.pageMap?await this.pageMap.getPagesWithTerm(e,new PageMapQueryPagesBelowPathImpl(this.paths().base(),"",e=>pagePredicates.shouldListLocal(e)&&pagePredicates.kindPage(e))):[];default:return[]}}regularPagesRecursive(){return[]}async terms(e,t){return this.pageMap?this.pageMap?.getTermsForPageInTaxonomy(e,this.paths().base(),t):null}async isTranslated(){return(await this.translations()).length>0}async translations(){const e=this.path()+"/"+this.pageIdentity().pageLanguage()+"/translations";if(!this.pageMap)return[];try{return await this.pageMap.getOrCreatePagesFromCacheSync(null,e,async e=>{const t=await this.allTranslations(),r=[];for(let e=0;e<t.length;e++){const i=t.at(e);i&&!i.eq(this)&&r.push(i)}return r})}catch(e){throw e}}async allTranslations(){const e=this.path()+"/translations-all";if(!this.pageMap)return[];try{return await this.pageMap.getOrCreatePagesFromCacheSync(null,e,async e=>{const t=[];var r;return this.pageMap.treePages.forEachInDimension(this.paths().base(),dimensionFlag.index(1),e=>{if(null!=e){const r=e.getPages();t.push(...r)}return!1}),r=t,pageBy(language).sort(r),t})}catch(e){throw e}}isBundled(){return this.source.file.isBundle()}},TaxonomyPageImpl=class extends PageImpl{singular;constructor(e,t,r,i,s,n="",a="taxonomy",o=null){super(e,t,r,i,n,a,o),this.singular=s}params(){const e=super.params();return e.Singular=this.singular,e}},TermPageImpl=class extends TaxonomyPageImpl{term;constructor(e,t,r,i,s,n,a="",o="term",l=null){super(e,t,r,i,s,a,o,l),this.term=n}params(){const e=super.params();return e.Term=this.term,e}}}}),init_pagemeta=__esm({"internal/domain/content/entity/pagemeta.ts"(){Meta=class{baseURL;list;parameters;weight;date;org;authorInfo;menuConfig;constructor(e,t="always",r={},i=999,s=new Date,n,a,o){this.baseURL=e,this.list=t,this.parameters=r,this.weight=i,this.date=s,this.org=n,this.authorInfo=a,this.menuConfig=o}description(){return""}params(){return this.parameters}pageBaseUrl(){return this.baseURL}pageWeight(){return this.weight}pageDate(){return this.date}publishDate(){return this.pageDate()}async relatedKeywords(e){return[]}shouldList(e){switch(this.list){case"always":default:return!0;case"never":return!1;case"local":return!e}}shouldListAny(){return this.shouldList(!0)||this.shouldList(!1)}noLink(){return!1}organization(){return this.org}author(){return this.authorInfo}menu(){return this.menuConfig}}}}),init_pagelayout=__esm({"internal/domain/content/entity/pagelayout.ts"(){Layout=class{home(){return["index.html","_default/index.html","_default/single.html"]}homeList(){return["index.html","_default/index.html","_default/list.html"]}section(e){return[`${e}/section.html`,`${e}/list.html`,"_default/section.html","_default/list.html","_default/index.html"]}page(e,t){const r=e?`${e}/${t}`:t,i=e?`${e}/single.html`:"single.html",s=[];return"index"!==r&&s.push(`${r}.html`),s.push(i),"index"!==t&&s.push(`_default/${t}.html`),s.push("_default/single.html"),s.push("index.html"),s.push("_default/index.html"),s}taxonomy(){return["taxonomy/taxonomy.html","taxonomy/list.html","_default/list.html","_default/taxonomy.html"]}term(){return["taxonomy/tag.html","term/term.html","taxonomy/list.html","_default/list.html","_default/term.html"]}standalone404(){return["404.html"]}standaloneSitemap(){return["sitemap.xml","_default/sitemap.xml"]}}}}),init_shortcode2=__esm({"internal/domain/content/entity/shortcode.ts"(){init_scratch(),ShortcodeWithPage=class{_params;_inner;_page;_parent;_name;_isNamedParams;_ordinal;_indentation;_innerDeindent=null;_posOffset;_pos=null;_scratch=null;constructor(e,t,r,i,s,n,a,o="",l=0){this._params=e,this._inner=t,this._page=r,this._parent=i,this._name=s,this._isNamedParams=n,this._ordinal=a,this._indentation=o,this._posOffset=l}get params(){return this._params}get Params(){return this._params}get IsNamedParams(){return this._isNamedParams}get inner(){return this._inner}get Inner(){return this._inner}get page(){return this._page}get Page(){return this._page}get parent(){return this._parent}get Parent(){return this._parent}get name(){return this._name}get isNamedParams(){return this._isNamedParams}get ordinal(){return this._ordinal}get Ordinal(){return this._ordinal}innerDeindent(){if(""===this._indentation)return this._inner;if(null===this._innerDeindent){const e=this._inner.split("\n");this._innerDeindent=e.map(e=>e.startsWith(this._indentation)?e.substring(this._indentation.length):e).join("\n")}return this._innerDeindent}get InnerDeindent(){return this.innerDeindent()}async position(){return this._pos||(this._pos=await this._page.posOffset(this._posOffset)),this._pos}scratch(){return this._scratch||(this._scratch=new Scratch),this._scratch}get(e){return this._params?Array.isArray(this._params)?"number"==typeof e?e>=this._params.length?"":this._params[e]:null:"object"==typeof this._params&&"string"==typeof e?this._params[e]||"":null:null}Get(e){return this.get(e)}}}}),init_type8=__esm({"internal/domain/template/type.ts"(){BASE_FILE_BASE="baseof",BASE_DEFAULT="_default",PARTIALS_PREFIX="partials/",new(TemplateError=class extends Error{constructor(e,t){super(e),this.code=t,this.name="TemplateError"}})("template not found","TEMPLATE_NOT_FOUND"),new TemplateError("template parse failed","PARSE_FAILED"),new TemplateError("template execute failed","EXECUTE_FAILED"),new TemplateError("invalid template","INVALID_TEMPLATE")}});import*as path19 from"path";var TemplateInfo2,init_baseof=__esm({"internal/domain/template/vo/baseof.ts"(){init_type8(),BaseOf=class{baseof=new Map;needsBaseof=new Map;getTemplateSearchOrder(e){const t=[];return t.push(`${BASE_DEFAULT}/baseof.html`),t}getBaseOf(e){return this.baseof.get(e)||null}getNeedsBaseOf(e){return this.needsBaseof.get(e)||null}addBaseOf(e,t){this.baseof.set(e,t)}addNeedsBaseOf(e,t){this.needsBaseof.set(e,t)}isBaseTemplatePath(e){return path19.basename(e).includes(BASE_FILE_BASE)}needsBaseOf(e,t){return!this.noBaseNeeded(e)&&this.needsBaseTemplate(t)}noBaseNeeded(e){return!!e.startsWith(PARTIALS_PREFIX)}needsBaseTemplate(e){let t=-1,r=!1;for(let i=0;i<e.length;)if(!r&&e.substring(i).startsWith("{{/*"))r=!0,i+=4;else if(!r&&e.substring(i).startsWith("{{- /*"))r=!0,i+=6;else if(r&&e.substring(i).startsWith("*/}}"))r=!1,i+=4;else if(r&&e.substring(i).startsWith("*/ -}}"))r=!1,i+=6;else{const s=e[i];if(!r){if(e.substring(i).startsWith("{{")){t=i;break}if(!/\s/.test(s))break}i++}return-1!==t&&/^{{-?\s*define/.test(e.substring(t))}getAllBaseOf(){return new Map(this.baseof)}getAllNeedsBaseOf(){return new Map(this.needsBaseof)}clear(){this.baseof.clear(),this.needsBaseof.clear()}getStats(){return{baseOfCount:this.baseof.size,needsBaseOfCount:this.needsBaseof.size}}}}});function removeLeadingBOM(e){for(let t=0;t<e.length;t++){const r=e[t];if(0===t&&"\ufeff"!==r)return e;if(t>0)return e.substring(t)}return e}function resolveTemplateType(e){return function(e){return e.includes("_shortcodes/")}(e)?1:e.includes("_partials/")?2:0}var BaseNamespace,RegularTemplateNamespace,PartialTemplateNamespace,ShortcodeTemplateNamespace,Executor,log31,ConcurrentCache,log32,Parser,init_info=__esm({"internal/domain/template/vo/info.ts"(){init_type8(),TemplateInfo2=class e{constructor(e,t,r){this.name=e,this.template=t,this.fi=r}identifierBase(){return this.name}errWithFileContext(e,t){const r=`${e}: ${t.message}`,i=new TemplateError(r,"TEMPLATE_FILE_ERROR");return Object.defineProperty(i,"fileName",{value:this.name,enumerable:!0}),Object.defineProperty(i,"fileContent",{value:this.template,enumerable:!0}),i}isZero(){return""===this.name}copy(){return new e(this.name,this.template,this.fi)}getCleanContent(){return removeLeadingBOM(this.template)}}}}),init_namespace=__esm({"internal/domain/template/vo/namespace.ts"(){init_type8(),init_log(),getDomainLogger("template",{component:"namespace"}),BaseNamespace=class{templates=new Map;mutex=new Set;addTemplate(e,t){this.withLock(()=>{this.templates.set(e,t)})}findTemplate(e){return this.withReadLock(()=>{if(this.templates.has(e))return this.templates.get(e)||null;if(!e.endsWith(".html")){const t=e+".html";if(this.templates.has(t))return this.templates.get(t)||null}for(const[t,r]of this.templates.entries())if(t.includes(e))return r;return null})}getTemplates(){return this.withReadLock(()=>new Map(this.templates))}hasTemplate(e){return this.withReadLock(()=>this.templates.has(e))}getTemplateNames(){return this.withReadLock(()=>Array.from(this.templates.keys()))}removeTemplate(e){return this.withLock(()=>this.templates.delete(e))}clear(){this.withLock(()=>{this.templates.clear()})}size(){return this.withReadLock(()=>this.templates.size)}getTemplatesByPattern(e){return this.withReadLock(()=>{const t=[];for(const[r,i]of this.templates)e.test(r)&&t.push(i);return t})}withLock(e){const t="write";for(;this.mutex.has(t););this.mutex.add(t);try{return e()}finally{this.mutex.delete(t)}}withReadLock(e){const t="read";this.mutex.add(t);try{return e()}finally{this.mutex.delete(t)}}},RegularTemplateNamespace=class extends BaseNamespace{lookup(e){const t=this.findTemplate(e);return t?t.template:null}findTemplateWithDependencies(e){return this.findTemplate(e)}getTemplatesNeedingBase(){return this.withReadLock(()=>Array.from(this.templates.values()).filter(e=>e.baseInfo))}},PartialTemplateNamespace=class extends BaseNamespace{lookup(e){const t=this.findTemplate(e);return t?t.template:null}addPartialTemplate(e,t){const r={...t,type:2};this.addTemplate(e,r)}},ShortcodeTemplateNamespace=class extends BaseNamespace{lookup(e){const t=this.findTemplate(e);return t?t.template:null}addShortcodeTemplate(e,t){const r={...t,type:1};this.addTemplate(e,r)}getShortcode(e){return this.lookup("_shortcodes/"+e)}hasShortcode(e){return this.hasTemplate(e)}getShortcodeNames(){return this.getTemplateNames()}}}}),init_executor=__esm({"internal/domain/template/entity/executor.ts"(){init_type8(),Executor=class{async execute(e,t){try{const[r,i]=await e.Execute(t);if(i)throw new TemplateError(`Template execution failed: ${i.message}`,"EXECUTION_FAILED");return r}catch(e){if(e instanceof TemplateError)throw e;const t=e instanceof Error?e.message:String(e);throw new TemplateError(`Template execution failed: ${t}`,"EXECUTION_FAILED")}}async executeWithTimeout(e,t,r){return new Promise(async(i,s)=>{const n=setTimeout(()=>{s(new TemplateError("Template execution timeout","EXECUTION_TIMEOUT"))},r);await this.execute(e,t).then(e=>{clearTimeout(n),i(e)}).catch(e=>{clearTimeout(n),s(e)})})}async executeSafely(e,t){try{return{result:await this.execute(e,t),error:null}}catch(e){if(e instanceof TemplateError)return{result:null,error:e};const t=e instanceof Error?e.message:String(e);return{result:null,error:new TemplateError(`Execution failed: ${t}`,"EXECUTION_ERROR")}}}async executeBatch(e){return(await Promise.allSettled(e.map(async({name:e,template:t,data:r})=>{try{return{name:e,result:await this.execute(t,r),error:null}}catch(t){return{name:e,result:null,error:t instanceof TemplateError?t:new TemplateError(`Batch execution failed: ${t.message}`,"BATCH_EXECUTION_FAILED")}}}))).map(e=>"fulfilled"===e.status?e.value:{name:"unknown",result:null,error:new TemplateError(`Batch execution failed: ${e.reason}`,"BATCH_EXECUTION_FAILED")})}async executeWithContext(e,t,r){if(r.signal?.aborted)throw new TemplateError("Template execution was cancelled","EXECUTION_CANCELLED");const i=new Promise((e,t)=>{r.signal&&r.signal.addEventListener("abort",()=>{t(new TemplateError("Template execution was cancelled","EXECUTION_CANCELLED"))})}),s=r.timeout?new Promise((e,t)=>{setTimeout(()=>{t(new TemplateError("Template execution timeout","EXECUTION_TIMEOUT"))},r.timeout)}):new Promise(()=>{});try{return await Promise.race([this.execute(e,t),i,s])}catch(e){if(e instanceof TemplateError)throw e;throw new TemplateError(`Context execution failed: ${e.message}`,"CONTEXT_EXECUTION_FAILED")}}}}}),init_cache2=__esm({"pkg/cahce/cache.ts"(){init_log(),log31=getDomainLogger("content",{component:"cache"}),new(ConcurrentCache=class{cache=new Map;pendingPromises=new Map;deletedKeys=new Set;constructor(){}get(e){return this.cache.get(e)}set(e,t){this.deletedKeys.has(e)||this.cache.set(e,t),this.pendingPromises.delete(e),this.deletedKeys.delete(e)}has(e){return this.cache.has(e)}isPending(e){return this.pendingPromises.has(e)}delete(e){return this.deletedKeys.add(e),this.pendingPromises.delete(e),this.cache.delete(e)}clear(){this.cache.clear(),this.pendingPromises.clear(),this.deletedKeys.clear()}size(){return this.cache.size}pendingCount(){return this.pendingPromises.size}async getOrCreate(e,t){const r=this.cache.get(e);if(void 0!==r)return r;const i=this.pendingPromises.get(e);return i?await i:this.createAndCache(e,t)}async createAndCache(e,t){const r=this.executeCreate(e,t);this.pendingPromises.set(e,r);try{const t=await r;return this.deletedKeys.has(e)?(this.deletedKeys.delete(e),this.pendingPromises.delete(e),t):(this.set(e,t),t)}catch(t){throw this.pendingPromises.delete(e),log31.error(`Failed to create value for key ${String(e)} : ${t}`),t}}async executeCreate(e,t){try{return await t(e)}catch(t){const r=t instanceof Error?t.message:String(t),i=new Error(`Cache creation failed for key ${String(e)}: ${r}`);throw t instanceof Error&&t.stack&&(i.stack=t.stack,i.originalError=t),i}}getStats(){return{size:this.cache.size,pendingCount:this.pendingPromises.size,keys:Array.from(this.cache.keys()),pendingKeys:Array.from(this.pendingPromises.keys())}}async preload(e){const t=e.filter(({key:e})=>!this.has(e)&&!this.isPending(e)).map(({key:e,create:t})=>this.getOrCreate(e,t));t.length>0&&await Promise.allSettled(t)}})}});import{New as New2}from"@mdfriday/text-template";import{NodeType}from"@mdfriday/text-template";var Lookup,log33,TemplateEngine,log34,engineDependentFunctions,PartialFunction,DefaultTemplateRegistry,init_parser=__esm({"internal/domain/template/entity/parser.ts"(){init_type8(),init_info(),init_log(),init_cache2(),log32=getDomainLogger("template",{component:"parser"}),Parser=class{prototypeText;prototypeTextClone;readyInit=!1;funcMap;parseOverlapCache;constructor(e=new Map){this.funcMap=e,this.prototypeText=New2(""),this.parseOverlapCache=new ConcurrentCache,this.funcMap.size>0&&this.prototypeText.Funcs(this.funcMap)}async markReady(){this.readyInit||(this.prototypeTextClone=this.prototypeText,this.readyInit=!0)}async parse(e){try{const t=New2(e.name);this.funcMap&&this.funcMap.size>0&&t.Funcs(this.funcMap);const[r,i]=t.Parse(e.template);if(i)throw new TemplateError(`Parse failed: ${i.message}`,"PARSE_FAILED");return{template:r,info:e,type:resolveTemplateType(e.name)}}catch(e){if(e instanceof TemplateError)throw e;const t=e instanceof Error?e.message:String(e);throw new TemplateError(`Parse failed: ${t}`,"PARSE_FAILED")}}async parseWithLock(e,t){try{this.prototypeTextClone||await this.markReady();const r=New2(e);this.funcMap&&this.funcMap.size>0&&r.Funcs(this.funcMap);const[i,s]=r.Parse(t);if(s)throw new TemplateError(`Parse with lock failed: ${s.message}`,"PARSE_LOCK_FAILED");return i}catch(e){if(e instanceof TemplateError)throw e;const t=e instanceof Error?e.message:String(e);throw new TemplateError(`Parse with lock failed: ${t}`,"PARSE_LOCK_FAILED")}}async parseOverlap(e,t,r){const i=`${e.name}::${t.name||"empty"}`;return this.parseOverlapCache.getOrCreate(i,async()=>{try{const i={template:await this.applyBaseTemplate(e,t,r),info:e,type:resolveTemplateType(e.name)};return t.isZero&&!t.name||(i.baseInfo=t),[i,!0,null]}catch(e){const t=e instanceof TemplateError?e:new TemplateError(`Parse overlap failed: ${e.message}`,"PARSE_OVERLAP_FAILED");return log32.error(`Failed to parse template overlap for key: ${i}: ${t.message}`),[null,!1,t]}})}async applyBaseTemplate(e,t,r){try{const i=New2(e.name);if(this.funcMap&&this.funcMap.size>0&&i.Funcs(this.funcMap),!t.isZero||t.name){const[e,r]=i.Parse(t.template);if(r)throw new TemplateError(`Base template parse failed: ${r.message}`,"BASE_PARSE_FAILED")}const[s,n]=i.Clone();if(n)throw new TemplateError(`Template clone failed: ${n.message}`,"CLONE_FAILED");const[a,o]=s.Parse(e.template);if(o)throw new TemplateError(`Overlay template parse failed: ${o.message}`,"OVERLAY_PARSE_FAILED");const l=await this.getDependencies(a,new Map,r);for(const[t,r]of l)if(t!==e.name)try{if(r.template.Tree){const[,e]=a.AddParseTree(t,r.template.Tree);if(e)throw log32.error(`AddParseTree failed: ${e.message} with name ${t}`),new TemplateError(`AddParseTree failed: ${e.message}`,"ADD_PARSE_TREE_FAILED")}}catch(r){throw log32.error(`Error adding dependency ${t} to template ${e.name}:`,r),new TemplateError(`Failed to add dependency ${t}: ${r.message}`,"DEPENDENCY_ADD_FAILED")}return a}catch(e){if(e instanceof TemplateError)throw e;const t=e instanceof Error?e.message:String(e);throw new TemplateError(`Apply base template failed: ${t}`,"APPLY_BASE_FAILED")}}async getDependencies(e,t,r){const i=new Map;if(t.has(e.Name()))return i;t.set(e.Name(),e);try{const s=new Set,n=e=>{if(!e)return;const t=e.Type();if(t===NodeType.NodeTemplate){const t=e.Name;t&&s.add(t)}else if(t===NodeType.NodeList){const t=e;if(t.Nodes)for(const e of t.Nodes)n(e)}if(t===NodeType.NodeAction){const t=e;t.Pipe&&n(t.Pipe)}else if(t===NodeType.NodePipe){const t=e;if(t.Cmds)for(const e of t.Cmds)n(e)}else if(t===NodeType.NodeCommand){const t=e;if(t.Args)for(const e of t.Args)n(e)}else if(t===NodeType.NodeIf||t===NodeType.NodeRange||t===NodeType.NodeWith){const t=e;t.Pipe&&n(t.Pipe),t.List&&n(t.List),t.ElseList&&n(t.ElseList)}};e.Tree&&e.Tree.Root&&n(e.Tree.Root);for(const e of s){const s=r(e);if(s&&(i.set(e,s),!t.has(s.template.Name()))){const e=await this.getDependencies(s.template,t,r);for(const[t,r]of e)i.has(t)||i.set(t,r)}}}catch(t){log32.error(`Error getting dependencies for template ${e.Name()}:`,t)}return i}setFuncMap(e){this.funcMap=new Map([...this.funcMap,...e]),this.funcMap.size>0&&this.prototypeText.Funcs(this.funcMap)}getFuncMap(){return new Map(this.funcMap)}async parseMultiple(e){const t=await Promise.allSettled(e.map(e=>this.parse(e))),r=[],i=[];for(const e of t)"fulfilled"===e.status?r.push(e.value):i.push(e.reason);if(i.length>0)throw new TemplateError(`Failed to parse ${i.length} templates: ${i.map(e=>e.message).join(", ")}`,"MULTIPLE_PARSE_FAILED");return r}clearCache(){this.parseOverlapCache.clear()}getCacheStats(){return this.parseOverlapCache.getStats()}}}}),init_lookup=__esm({"internal/domain/template/entity/lookup.ts"(){init_baseof(),Lookup=class{baseOf;funcsv;constructor(e,t){if(this.baseOf=e||new BaseOf,this.funcsv=new Map,t)for(const[e,r]of t)this.funcsv.set(e,r)}findNoDependence(e,t){try{const r=t.lookup(e);return r?[r,!0,null]:[null,!1,null]}catch(e){return[null,!1,e]}}findTemplate(e,t){try{const r=t.lookup(e);if(r)return[r,!0,null];const i=t.findTemplateWithDependencies(e);return i&&i.baseInfo?[i.template,!0,null]:[null,!1,null]}catch(e){return[null,!1,e]}}findPartial(e,t){try{const r=t.lookup(e);return r?[r,!0,null]:[null,!1,null]}catch(e){return[null,!1,e]}}findShortcode(e,t){try{const r=t.getShortcode(e);return r?[r,!0,null]:[null,!1,null]}catch(e){return[null,!1,e]}}findDependentInfo(e){const t=this.baseOf.getNeedsBaseOf(e);if(!t)return[null,null,!1];let r=null,i=!1;for(const t of this.baseOf.getTemplateSearchOrder(e))if(r=this.baseOf.getBaseOf(t),r){i=!0;break}return[t,r,i]}getFunc(e){return this.funcsv.get(e)}setFunc(e,t){this.funcsv.set(e,t)}setFuncMap(e){this.funcsv.clear();for(const[t,r]of e)this.funcsv.set(t,r)}getFuncMap(){return new Map(this.funcsv)}newTemplateLookup(e){return t=>e.findTemplate(t)}getBaseOf(){return this.baseOf}setBaseOf(e){this.baseOf=e}hasDependencies(e){const[t,r,i]=this.findDependentInfo(e);return i&&(null!==t||null!==r)}getAllFunctions(){return Array.from(this.funcsv.keys())}clearFunctions(){this.funcsv.clear()}getStats(){const e=this.baseOf.getStats();return{functionCount:this.funcsv.size,baseTemplateCount:e.baseOfCount,dependentTemplateCount:e.needsBaseOfCount}}}}}),init_template=__esm({"internal/domain/template/entity/template.ts"(){init_type8(),init_info(),init_info(),init_log(),init_paths(),log33=getDomainLogger("template",{component:"template-engine"}),TemplateEngine=class{executor;lookup;parser;templateNamespace;partialNamespace;shortcodeNamespace;fs;constructor(e,t,r,i,s,n,a){this.executor=e,this.lookup=t,this.parser=r,this.templateNamespace=i,this.partialNamespace=s,this.shortcodeNamespace=n,this.fs=a}async markReady(){try{await this.parser.markReady()}catch(e){throw new TemplateError(`Failed to mark template engine ready: ${e.message}`,"TEMPLATE_ENGINE_READY_FAILED")}}async getTemplate(e){const[t,r,i]=this.lookup.findTemplate(e,this.templateNamespace);if(i)return[null,!1,i];if(r&&t)return[t,!0,null];const[s,n,a]=this.lookup.findDependentInfo(e);if(a&&s)try{const[e,t,r]=await this.parser.parseOverlap(s,n||s,this.lookup.newTemplateLookup(this.templateNamespace));if(r)return[null,!1,r];if(t&&e)return[e.template,!0,null]}catch(e){return[null,!1,e]}return[null,!1,null]}async getPartial(e){let t=e.startsWith(PARTIALS_PREFIX)?e:`${PARTIALS_PREFIX}${e}`;return t=e.endsWith(".html")?t:`${t}.html`,this.lookup.findPartial(t,this.partialNamespace)}async getShortcode(e){return this.lookup.findShortcode(e,this.shortcodeNamespace)}async get(e){switch(resolveTemplateType(e)){case 1:return this.getShortcode(e);case 2:return this.getPartial(e);default:return this.getTemplate(e)}}async findFirst(e){if(!e||0===e.length)return[null,null,!1,null];for(const t of e)try{const[e,r,i]=await this.get(t);if(i)continue;if(r&&e)return[e,t,!0,null]}catch(e){log33.error("Error finding template:",e)}return[null,null,!1,null]}hasShortcode(e){return this.shortcodeNamespace.hasShortcode(e)}getShortcodeNames(){return this.shortcodeNamespace.getShortcodeNames()}getShortcodeCount(){return this.getShortcodeNames().length}async loadTemplates(){const e=async(e,t)=>{if(t.isDir())return;const r=e.startsWith(PATH_CONSTANTS.SYSTEM_PATH_SEPARATOR)?e.substring(1):e,i=PATH_CONSTANTS.normalizePath(r);try{await this.addTemplateFileInfo(i,t)}catch(e){log33.error("Error adding template:",new TemplateError(`Failed to add template ${i}: ${e.message}`,"LOAD_TEMPLATE_FAILED"))}};try{await this.fs.walk("",{walkFn:e},{})}catch(e){if(!e.message?.includes("ENOENT")&&!e.message?.includes("no such file"))throw e}}async addTemplateFileInfo(e,t){try{const r=await async function(e,t){let r=null;try{r=await t.open();const i=await r.stat(),s=new Uint8Array(i.size()),n=await r.read(s),a=removeLeadingBOM(new TextDecoder("utf-8").decode(n.buffer));return new TemplateInfo2(e,a,t)}catch(r){throw new TemplateInfo2(e,"",t).errWithFileContext("failed to load template",r)}finally{if(r)try{await r.close()}catch(e){console.warn(`Failed to close template file: ${e}`)}}}(e,t);await this.addTemplate(r.name,r)}catch(t){throw new TemplateError(`Failed to load template info for ${e}: ${t.message}`,"LOAD_TEMPLATE_INFO_FAILED")}}async addTemplate(e,t){try{if(this.lookup.getBaseOf().isBaseTemplatePath(e))return void this.lookup.getBaseOf().addBaseOf(e,t);if(this.lookup.getBaseOf().needsBaseOf(e,t.template))return void this.lookup.getBaseOf().addNeedsBaseOf(e,t);const r=resolveTemplateType(e),i=await this.parser.parse(t);switch(r){case 1:this.shortcodeNamespace.addShortcodeTemplate(e,i);break;case 2:this.partialNamespace.addPartialTemplate(e,i);break;default:this.templateNamespace.addTemplate(e,i)}}catch(t){throw new TemplateError(`Failed to add template ${e}: ${t.message}`,"ADD_TEMPLATE_FAILED")}}async execute(e,t){const[r,i,s]=await this.get(e);if(s)throw s;if(!i||!r)throw new TemplateError(`Template not found: ${e}`,"TEMPLATE_NOT_FOUND");return await this.executor.execute(r,t)}async executeRaw(e,t,r){const i=await this.parser.parseWithLock(e,t);if(!i)throw new TemplateError(`Raw Template parse error: ${e}`,"TEMPLATE_PARSE_ERROR");return await this.executor.execute(i,r)}async executeShortcode(e,t){const r=this.shortcodeNamespace.getShortcode(e);if(!r)throw new TemplateError(`Shortcode template '${e}' not found`,"SHORTCODE_NOT_FOUND");try{return await this.executor.execute(r,t)}catch(t){throw new TemplateError(`Error executing shortcode template '${e}': ${t.message}`,"SHORTCODE_EXECUTION_FAILED")}}async executeSafely(e,t){try{return{result:await this.execute(e,t),error:null}}catch(e){return e instanceof TemplateError?{result:null,error:e}:{result:null,error:new TemplateError(`Execute safely failed: ${e.message}`,"EXECUTE_SAFELY_FAILED")}}}async executeShortcodeSafely(e,t){try{return{result:await this.executeShortcode(e,t),error:null}}catch(e){return e instanceof TemplateError?{result:null,error:e}:{result:null,error:new TemplateError(`Execute shortcode safely failed: ${e.message}`,"EXECUTE_SHORTCODE_SAFELY_FAILED")}}}async hasTemplate(e){const[,t]=await this.get(e);return t}getTemplateNames(){return this.templateNamespace.getTemplateNames()}getPartialTemplateNames(){return this.partialNamespace.getTemplateNames()}getAllTemplateNames(){return[...this.templateNamespace.getTemplateNames(),...this.partialNamespace.getTemplateNames(),...this.shortcodeNamespace.getTemplateNames()]}getPartialNamespace(){return this.partialNamespace}getShortcodeNamespace(){return this.shortcodeNamespace}getTemplateNamespace(){return this.templateNamespace}clear(){this.templateNamespace.clear(),this.lookup.getBaseOf().clear()}getTemplatesByPattern(e){return this.templateNamespace.getTemplatesByPattern(e).map(e=>e.info.name)}}}});import*as crypto2 from"crypto";function newTemplateRegistry(){return new DefaultTemplateRegistry}var Factory2,Builder,init_registry=__esm({"internal/domain/template/vo/registry.ts"(){init_log(),init_lang(),log34=getDomainLogger("template",{component:"registry"}),engineDependentFunctions=[],PartialFunction=class{engine=null;globalPartialsCache=new Map;getFunctionName(){return"partial"}updateEngine(e){this.engine=e,this.globalPartialsCache.clear()}execute=async(e,t)=>{if(!this.engine)return log34.error(`Partial function called but engine not set: ${e}`),`\x3c!-- Partial function called but engine not ready: ${e} --\x3e`;try{const r=e.startsWith("partials/")?e:`partials/${e}`,i=r.includes("global");if(i&&this.globalPartialsCache.has(r))return this.globalPartialsCache.get(r);const s=await this.executePartial(r,t);return i&&this.globalPartialsCache.set(r,s),s}catch(t){return log34.error(`Partial execution failed for "${e}":`,t),`\x3c!-- Partial execution failed: ${e} - ${t.message} --\x3e`}};async executePartial(e,t){if(!this.engine)return`\x3c!-- Template engine not available: ${e} --\x3e`;try{const[r,i,s]=await this.engine.getPartial(e);if(s)return log34.error("Error getting partial template:",s),`\x3c!-- Error getting partial template: ${e} - ${s.message} --\x3e`;if(!i||!r)return log34.warn(`Template not found: ${e}`),`\x3c!-- Template not found: ${e} --\x3e`;const[n,a]=await r.Execute(t);return a?(log34.error("Template execution error:",a),`\x3c!-- Template execution error: ${e} - ${a.message} --\x3e`):n}catch(t){return log34.error("Sync partial execution failed:",t),`\x3c!-- Partial sync execution failed: ${e} - ${t.message} --\x3e`}}},DefaultTemplateRegistry=class{registerCoreFunctions(e){this.registerCryptoFunctions(e),this.registerStringFunctions(e),this.registerMathFunctions(e),this.registerTimeFunctions(e),this.registerCollectionFunctions(e),this.registerSafeFunctions(e),this.registerReflectFunctions(e),this.registerFmtFunctions(e),this.registerPathFunctions(e),this.registerTransformFunctions(e)}registerCryptoFunctions(e){e.set("md5",e=>e?crypto2.createHash("md5").update(e).digest("hex"):""),e.set("encryptAESGCM",(e,t)=>{if(!e||!t)return"";const r=crypto2.randomBytes(16),i=crypto2.randomBytes(12),s=crypto2.pbkdf2Sync(e,r,1e5,32,"sha256"),n=crypto2.createCipheriv("aes-256-gcm",s,i),a=Buffer.concat([n.update(t,"utf8"),n.final()]),o=n.getAuthTag();return Buffer.concat([r,i,o,a]).toString("base64")})}registerExtendedFunctions(e,t){this.registerURLFunctions(e,t),this.registerSiteFunctions(e,t),this.registerResourcesFunctions(e,t),this.registerHugoFunctions(e,t),this.registerLanguageFunctions(e,t)}registerAllFunctions(e,t){this.registerCoreFunctions(e),this.registerStringFunctions(e),this.registerMathFunctions(e),this.registerTimeFunctions(e),this.registerCollectionFunctions(e),this.registerEngineDependentFunctions(e),t&&(this.registerURLFunctions(e,t),this.registerExtendedFunctions(e,t))}registerEngineDependentFunctions(e){const t=new PartialFunction;engineDependentFunctions.push(t),e.set(t.getFunctionName(),t.execute)}registerURLFunctions(e,t){e.set("urls",()=>({Parse:e=>{try{return{Host:new URL(e).host}}catch{return{Host:""}}},JoinPath:(...e)=>e.filter(e=>""!==e).map(e=>e.replace(/^\/+|\/+$/g,"")).join("/"),URLize:e=>t.urlize(e),Abs:e=>t.absURL(e),Rel:e=>t.relURL(e),AbsLangURL:e=>t.absURL(e),RelLangURL:e=>t.relURL(e),Sanitize:e=>{try{return new URL(e).toString()}catch{return e.replace(/[<>"'%{}|\\^`]/g,"")}},PathEscape:e=>encodeURIComponent(e).replace(/%2F/g,"/").replace(/[!'()*]/g,e=>`%${e.charCodeAt(0).toString(16).toUpperCase()}`),QueryEscape:e=>encodeURIComponent(e),QueryUnescape:e=>{try{return decodeURIComponent(e)}catch{return e}},IsAbs:e=>{try{return""!==new URL(e).protocol}catch{return!1}},IsRelative:e=>{try{return new URL(e),!1}catch{return!0}}})),e.set("absURL",e=>t.absURL(e)),e.set("relURL",e=>t.relURL(e)),e.set("urlize",e=>t.urlize(e)),e.set("relref",(e,r)=>{if(/^https?:\/\//.test(r))return r;let i="";const s=r.indexOf("#");return-1!==s&&(i=r.slice(s),r=r.slice(0,s)),(r=r.replace(/^\/+|\/+$/g,"")).startsWith("./")||r.startsWith("../")||r.startsWith("/")?t.relURL(r+i):t.relURL("/"+r+i)}),e.set("ref",(e,r)=>{if(/^https?:\/\//.test(r))return r;let i="";const s=r.indexOf("#");return-1!==s&&(i=r.slice(s),r=r.slice(0,s)),(r=r.replace(/^\/+|\/+$/g,"")).startsWith("./")||r.startsWith("../")||r.startsWith("/")?t.absURL(r+i):t.absURL("/"+r+i)}),e.set("absLangURL",e=>t.absURL(e)),e.set("relLangURL",e=>t.relURL(e))}registerSiteFunctions(e,t){e.set("Site",()=>({Title:t.title(),BaseURL:t.baseURL(),Params:t.params(),Menus:t.menus(),IsMultiLingual:t.isMultiLanguage(),LanguageCode:t.defaultLanguage()}))}registerResourcesFunctions(e,t){e.set("resources",()=>({Get:async e=>await t.Get(e),GetRemote:async e=>await t.GetRemote(e),Minify:async e=>await t.Minify(e),Fingerprint:async e=>await t.Fingerprint(e),ExecuteAsTemplate:async(e,r,i)=>await t.ExecuteAsTemplate(e,r,i)}))}registerHugoFunctions(e,t){e.set("hugo",()=>({Version:t.version(),Environment:t.environment(),Generator:t.generator()}))}registerLanguageFunctions(e,t){e.set("lang",()=>({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)})),e.set("langName",e=>lang.getNameByCode(e)||e),e.set("langDirection",e=>lang.getDirection(e)||"ltr"),e.set("isLTR",e=>lang.isLTR(e)),e.set("isRTL",e=>lang.isRTL(e)),e.set("i18n",e=>t.translate(e))}registerStringFunctions(e){e.set("humanize",e=>e?(e=(e=e.replace(/([a-z])([A-Z])/g,"$1 $2")).replace(/[_-]+/g," "),/\.(md|html|htm|markdown|mdown|mkd|mkdn|txt)$/i.test(e)&&(e=e.replace(/\.[^/.]+$/,"")),(e=e.charAt(0).toUpperCase()+e.slice(1).toLowerCase()).trim()):""),e.set("upper",e=>e.toUpperCase()),e.set("lower",e=>e.toLowerCase()),e.set("title",e=>e.replace(/\w\S*/g,e=>e.charAt(0).toUpperCase()+e.substr(1).toLowerCase())),e.set("trim",e=>e.trim()),e.set("replace",(...e)=>{if(e.length<3)throw new Error("replace requires at least 3 arguments: string, old, new");const t=String(e[0]),r=String(e[1]),i=String(e[2]);if(e.length>=4){const s=Number(e[3]);if(isNaN(s))throw new Error("replace limit must be a number");let n=t,a=0,o=0;for(;a<s&&o<n.length;){const e=n.indexOf(r,o);if(-1===e)break;n=n.substring(0,e)+i+n.substring(e+r.length),o=e+i.length,a++}return n}return t.split(r).join(i)}),e.set("replaceRE",(...t)=>{if(t.length<3)throw new Error("replaceRE requires at least 3 arguments: pattern, replacement, string");const r=t[0],i=t[1],s=t[2],n=t.length>=4?t[3]:void 0;return e.get("strings")().ReplaceRE(r,i,s,n)}),e.set("split",(e,t)=>null==e?(log34.warn("split function: first argument is null or undefined"),[]):"string"!=typeof e?(log34.warn("split function: first argument must be a string, got:",typeof e,"value:",e),Array.isArray(e)?e:String(e).split(t)):e.split(t)),e.set("splitRegex",(e,t)=>{if(null==e)return log34.warn("splitRegex function: first argument is null or undefined"),[];if("string"!=typeof e){if(log34.warn("splitRegex function: first argument must be a string, got:",typeof e,"value:",e),Array.isArray(e))return e;const r=String(e);try{const e=new RegExp(t);return r.split(e)}catch(e){return log34.warn("splitRegex function: invalid regex pattern:",t,"error:",e),[r]}}try{const r=new RegExp(t);return e.split(r)}catch(r){return log34.warn("splitRegex function: invalid regex pattern:",t,"error:",r),[e]}}),e.set("delimit",(e,t)=>Array.isArray(e)?e.join(t):String(e)),e.set("in",(e,t)=>(Array.isArray(e)||"string"==typeof e&&"string"==typeof t)&&e.includes(t)),e.set("hasPrefix",(e,t)=>e.startsWith(t)),e.set("hasSuffix",(e,t)=>e.endsWith(t)),e.set("strings",()=>({ToLower:e=>String(e).toLowerCase(),ToUpper:e=>String(e).toUpperCase(),Title:e=>String(e).replace(/\w\S*/g,e=>e.charAt(0).toUpperCase()+e.substr(1).toLowerCase()),Trim:(e,t)=>String(e).split("").filter(e=>!t.includes(e)).join(""),TrimSpace:e=>String(e).trim(),TrimLeft:(e,t)=>{const r=String(t);let i=0;for(;i<r.length&&e.includes(r[i]);)i++;return r.slice(i)},TrimRight:(e,t)=>{const r=String(t);let i=r.length-1;for(;i>=0&&e.includes(r[i]);)i--;return r.slice(0,i+1)},TrimPrefix:(e,t)=>{const r=String(t);return r.startsWith(e)?r.slice(e.length):r},TrimSuffix:(e,t)=>{const r=String(t);return r.endsWith(e)?r.slice(0,-e.length):r},Contains:(e,t)=>String(e).includes(t),ContainsAny:(e,t)=>{const r=String(e);return t.split("").some(e=>r.includes(e))},HasPrefix:(e,t)=>String(e).startsWith(t),HasSuffix:(e,t)=>String(e).endsWith(t),Replace:(e,t,r,i)=>{const s=String(e);if(void 0===i)return s.split(t).join(r);let n=s,a=0,o=0;for(;a<i&&o<n.length;){const e=n.indexOf(t,o);if(-1===e)break;n=n.substring(0,e)+r+n.substring(e+t.length),o=e+r.length,a++}return n},ReplaceRE:(e,t,r,i)=>{const s=String(e),n=String(t),a=String(r);let o,l=-1;if(void 0!==i){const e=parseInt(String(i),10);if(isNaN(e))throw new Error("limit argument must be integer");l=e}try{o=new RegExp(s,"g")}catch(e){throw new Error(`invalid regular expression: ${s}`)}let c=0;return a.replace(o,e=>l>=0&&c>=l?e:(c++,n))},Split:(e,t)=>String(e).split(t),SliceString:(e,t,r)=>{const i=String(e);return void 0!==r?i.slice(t,r):i.slice(t)},Substr:(e,t,r)=>{const i=String(e);return t<0&&(t=i.length+t),t<0&&(t=0),t>=i.length?"":void 0===r?i.slice(t):r<=0?"":i.slice(t,t+r)},Count:(e,t)=>{const r=String(t);return e?(r.match(new RegExp(e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g"))||[]).length:r.length+1},CountWords:e=>{const t=String(e).trim();return t?t.split(/\s+/).length:0},CountRunes:e=>String(e).replace(/\s/g,"").length,RuneCount:e=>String(e).length,Repeat:(e,t)=>{if(e<0)throw new Error("strings: negative Repeat count");return String(t).repeat(e)},FirstUpper:e=>{const t=String(e);return t.charAt(0).toUpperCase()+t.slice(1)}})),e.set("substr",(e,...t)=>{const r=String(e),i=Array.from(r),s=i.length;let n,a;switch(t.length){case 0:throw new Error("too few arguments");case 1:const e=Number(t[0]);if(isNaN(e)||!Number.isInteger(e))throw new Error("start argument must be an integer");n=e,a=s;break;case 2:const r=Number(t[0]),i=Number(t[1]);if(isNaN(r)||!Number.isInteger(r))throw new Error("start argument must be an integer");if(isNaN(i)||!Number.isInteger(i))throw new Error("length argument must be an integer");n=r,a=i;break;default:throw new Error("too many arguments")}if(0===s)return"";if(n<0&&(n+=s),n<0&&(n=0),n>s-1)return"";let o=s;return 0===a?"":(a<0?o+=a:a>0&&(o=n+a),n>=o||o<0?"":(o>s&&(o=s),i.slice(n,o).join("")))}),e.set("truncate",(e,...t)=>{const r=Number(e);if(isNaN(r)||!Number.isInteger(r))throw new Error("truncate length must be an integer");let i,s=" …";switch(t.length){case 0:throw new Error("truncate requires a length and a string");case 1:i=t[0],s=" …";break;case 2:s=String(t[0]),i=t[1];break;default:throw new Error("too many arguments passed to truncate")}const n=String(i),a=/<[^>]+>/.test(n);return Array.from(n).length<=r?a?n:this.escapeHTML(n):a?this.truncateHTML(n,r,s):this.truncateText(n,r,s)})}escapeHTML(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;")}truncateText(e,t,r){const i=Array.from(e);if(i.length<=t)return this.escapeHTML(e);let s=0,n=0;for(let e=0;e<i.length&&n<t;e++){const t=i[e];n++,/\s/.test(t)&&(s=e),/[\u4e00-\u9fff\u3400-\u4dbf\u3040-\u309f\u30a0-\u30ff\uac00-\ud7af]/.test(t)&&(s=e)}let a=n>=t?s>0?s:t:i.length;const o=i.slice(0,a).join("");return this.escapeHTML(o)+r}truncateHTML(e,t,r){const i=/^<(\/)?([^ ]+?)(?:(\s*\/)| .*?)?>/,s=new Set(["br","col","link","base","img","param","area","hr","input"]),n=[];let a=0,o=0,l=0,c=0,h=0;const u=Array.from(e);for(;h<u.length;){const e=u[h];if("<"===e){const e=u.slice(h).join("").match(i);if(e){const t=e[0],r="/"===e[1],i=e[2].toLowerCase(),l="/"===e[3];h+=t.length,a=o,s.has(i)||l||n.push({name:i,pos:h-t.length,openTag:!r});continue}}if(l++,/\s/.test(e)?a=o:/[\u4e00-\u9fff\u3400-\u4dbf\u3040-\u309f\u30a0-\u30ff\uac00-\ud7af]/.test(e)?a=h:o=h+1,l>t){c=a>0?a:h;break}h++}if(l<=t)return e;let g=u.slice(0,c).join("")+r,d=null;for(let e=n.length-1;e>=0;e--){const t=n[e];t.pos>=c||null!==d?null!==d&&d.name===t.name&&(d=null):t.openTag?g+=`</${t.name}>`:d=t}return g}registerMathFunctions(e){e.set("add",(e,t)=>e+t),e.set("sub",(e,t)=>e-t),e.set("mul",(e,t)=>e*t),e.set("div",(e,t)=>0!==t?e/t:0),e.set("mod",(e,t)=>0!==t?e%t:0),e.set("math",()=>({Abs:e=>{const t=Number(e);if(isNaN(t))throw new Error("the math.Abs function requires a numeric argument");return Math.abs(t)},Add:(...e)=>{if(e.length<2)throw new Error("must provide at least two numbers");return e.reduce((e,t)=>{const r=Number(t);if(isNaN(r))throw new Error("Add operator can't be used with non-numeric values");return e+r},0)},Ceil:e=>{const t=Number(e);if(isNaN(t))throw new Error("Ceil operator can't be used with non-numeric value");return Math.ceil(t)},Div:(...e)=>{if(e.length<2)throw new Error("must provide at least two numbers");return e.reduce((e,t,r)=>{const i=Number(t);if(isNaN(i))throw new Error("Div operator can't be used with non-numeric values");if(0===r)return i;if(0===i)throw new Error("division by zero");return e/i})},Floor:e=>{const t=Number(e);if(isNaN(t))throw new Error("Floor operator can't be used with non-numeric value");return Math.floor(t)},Log:e=>{const t=Number(e);if(isNaN(t))throw new Error("Log operator can't be used with non-numeric value");return Math.log(t)},Max:(...e)=>{if(0===e.length)throw new Error("must provide at least one number");const t=e.flat().map(e=>{const t=Number(e);if(isNaN(t))throw new Error("Max operator can't be used with non-numeric values");return t});return Math.max(...t)},Min:(...e)=>{if(0===e.length)throw new Error("must provide at least one number");const t=e.flat().map(e=>{const t=Number(e);if(isNaN(t))throw new Error("Min operator can't be used with non-numeric values");return t});return Math.min(...t)},Mod:(e,t)=>{const r=Number(e),i=Number(t);if(isNaN(r)||isNaN(i))throw new Error("modulo operator can't be used with non-numeric value");if(0===i)throw new Error("the number can't be divided by zero at modulo operation");return r%i},ModBool:(e,t)=>{const r=Number(e),i=Number(t);if(isNaN(r)||isNaN(i))throw new Error("modulo operator can't be used with non-numeric value");if(0===i)throw new Error("the number can't be divided by zero at modulo operation");return r%i===0},Mul:(...e)=>{if(e.length<2)throw new Error("must provide at least two numbers");return e.reduce((e,t)=>{const r=Number(t);if(isNaN(r))throw new Error("Mul operator can't be used with non-numeric values");return e*r},1)},Pow:(e,t)=>{const r=Number(e),i=Number(t);if(isNaN(r)||isNaN(i))throw new Error("Pow operator can't be used with non-numeric value");return Math.pow(r,i)},Rand:()=>Math.random(),Round:e=>{const t=Number(e);if(isNaN(t))throw new Error("Round operator can't be used with non-numeric value");return Math.round(t)},Sqrt:e=>{const t=Number(e);if(isNaN(t))throw new Error("Sqrt operator can't be used with non-numeric value");return Math.sqrt(t)},Sub:(...e)=>{if(e.length<2)throw new Error("must provide at least two numbers");return e.reduce((e,t,r)=>{const i=Number(t);if(isNaN(i))throw new Error("Sub operator can't be used with non-numeric values");return 0===r?i:e-i})},Sum:(...e)=>{if(0===e.length)throw new Error("must provide at least one number");return e.flat().map(e=>{const t=Number(e);if(isNaN(t))throw new Error("Sum operator can't be used with non-numeric values");return t}).reduce((e,t)=>e+t,0)},Product:(...e)=>{if(0===e.length)throw new Error("must provide at least one number");return e.flat().map(e=>{const t=Number(e);if(isNaN(t))throw new Error("Product operator can't be used with non-numeric values");return t}).reduce((e,t)=>e*t,1)}}))}registerTimeFunctions(e){e.set("time",()=>({AsTime:e=>{if(!e)return null;if(e instanceof Date)return e;if("string"==typeof e){const t=new Date(e);return isNaN(t.getTime())?null:t}if("number"==typeof e){const t=new Date(e<1e10?1e3*e:e);return isNaN(t.getTime())?null:t}return null},Format:(e,t)=>{const r=t instanceof Date?t:new Date(t);if(isNaN(r.getTime()))return"";const i=r.getFullYear(),s=r.getMonth()+1,n=r.getDate(),a=r.getHours(),o=r.getMinutes(),l=r.getSeconds(),c=r.toLocaleString("en-US",{weekday:"short"}),h=r.toLocaleString("en-US",{month:"short"}),u=[{pattern:"2006",placeholder:"{{YEAR_FULL}}",value:i.toString()},{pattern:"January",placeholder:"{{MONTH_FULL}}",value:r.toLocaleString("en-US",{month:"long"})},{pattern:"Monday",placeholder:"{{WEEKDAY_FULL}}",value:r.toLocaleString("en-US",{weekday:"long"})},{pattern:"MST",placeholder:"{{TIMEZONE}}",value:r.toLocaleString("en-US",{timeZoneName:"short"})},{pattern:"Jan",placeholder:"{{MONTH_SHORT}}",value:h},{pattern:"Mon",placeholder:"{{WEEKDAY_SHORT}}",value:c},{pattern:"06",placeholder:"{{YEAR_SHORT}}",value:i.toString().slice(-2)},{pattern:"15",placeholder:"{{HOUR_24}}",value:a.toString().padStart(2,"0")},{pattern:"01",placeholder:"{{MONTH_ZERO}}",value:s.toString().padStart(2,"0")},{pattern:"02",placeholder:"{{DAY_ZERO}}",value:n.toString().padStart(2,"0")},{pattern:"04",placeholder:"{{MINUTE_ZERO}}",value:o.toString().padStart(2,"0")},{pattern:"05",placeholder:"{{SECOND_ZERO}}",value:l.toString().padStart(2,"0")},{pattern:"PM",placeholder:"{{AMPM_UPPER}}",value:a>=12?"PM":"AM"},{pattern:"pm",placeholder:"{{AMPM_LOWER}}",value:a>=12?"pm":"am"},{pattern:"3",placeholder:"{{HOUR_12}}",value:((a+11)%12+1).toString()},{pattern:"1",placeholder:"{{MONTH_NUM}}",value:s.toString()},{pattern:"2",placeholder:"{{DAY_NUM}}",value:n.toString()},{pattern:"4",placeholder:"{{MINUTE_NUM}}",value:o.toString()},{pattern:"5",placeholder:"{{SECOND_NUM}}",value:l.toString()}];let g=e;for(const{pattern:e,placeholder:t}of u){const r=e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");g=g.replace(new RegExp(r,"g"),t)}for(const{placeholder:e,value:t}of u)g=g.replace(new RegExp(e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g"),t);return g},Now:()=>new Date,Parse:(e,t)=>{try{const e=new Date(t);return isNaN(e.getTime())?null:e}catch{return null}},Unix:e=>{const t=e instanceof Date?e:new Date(e);return Math.floor(t.getTime()/1e3)},UnixNano:e=>1e6*(e instanceof Date?e:new Date(e)).getTime()})),e.set("now",()=>{const e=new Date;return{Format:t=>{const r=e.getFullYear(),i=e.getMonth()+1,s=e.getDate(),n=e.getHours(),a=e.getMinutes(),o=e.getSeconds(),l=[{pattern:"2006",value:r.toString()},{pattern:"06",value:r.toString().slice(-2)},{pattern:"01",value:i.toString().padStart(2,"0")},{pattern:"1",value:i.toString()},{pattern:"02",value:s.toString().padStart(2,"0")},{pattern:"2",value:s.toString()},{pattern:"15",value:n.toString().padStart(2,"0")},{pattern:"3",value:(n%12||12).toString()},{pattern:"04",value:a.toString().padStart(2,"0")},{pattern:"4",value:a.toString()},{pattern:"05",value:o.toString().padStart(2,"0")},{pattern:"5",value:o.toString()}];let c=t;for(const{pattern:e,value:t}of l){const r=new RegExp(`\\b${e}\\b`,"g");c=c.replace(r,t)}return"2006"===t?r.toString():"06"===t?r.toString().slice(-2):"01"===t?i.toString().padStart(2,"0"):"02"===t?s.toString().padStart(2,"0"):"15"===t?n.toString().padStart(2,"0"):"04"===t?a.toString().padStart(2,"0"):"05"===t?o.toString().padStart(2,"0"):c},getTime:()=>e.getTime(),toString:()=>e.toString(),toISOString:()=>e.toISOString()}}),e.set("dateFormat",(e,t)=>t.toLocaleDateString())}registerCollectionFunctions(e){e.set("len",e=>Array.isArray(e)||"string"==typeof e?e.length:e&&"object"==typeof e?Object.keys(e).length:0),e.set("first",(e,t)=>Array.isArray(e)?e.slice(0,1):Array.isArray(t)?t.slice(0,e):[]),e.set("last",(e,t)=>Array.isArray(e)?e.slice(-1):Array.isArray(t)?t.slice(-e):[]),e.set("merge",(...e)=>{const t={};for(const r of e)r&&"object"==typeof r&&!Array.isArray(r)&&Object.assign(t,r);return t}),e.set("index",(e,...t)=>{try{return this.doIndex(e,t)}catch(r){return log34.error(`Index of type ${typeof e} with args [${t.join(", ")}] failed:`,r),null}}),e.set("reverse",e=>Array.isArray(e)?[...e].reverse():e),e.set("append",(...e)=>{if(e.length<2)return e[0]||[];const t=Array.isArray(e[0])?[...e[0]]:[e[0]];for(let r=1;r<e.length;r++)Array.isArray(e[r])?t.push(...e[r]):t.push(e[r]);return t}),e.set("prepend",(e,...t)=>Array.isArray(e)?[...t,...e]:[...t,e]),e.set("seq",(...e)=>{if(e.length<1||e.length>3)throw new Error("invalid number of arguments to Seq");const t=e.map(e=>{const t=Number(e);if(isNaN(t))throw new Error("invalid arguments to Seq");return Math.floor(t)});let r,i=1,s=t[0];if(1===t.length){if(r=s,0===r)return[];r>0?s=1:(s=-1,i=-1)}else if(2===t.length)r=t[1],r<s&&(i=-1);else{if(i=t[1],r=t[2],0===i)throw new Error("'increment' must not be 0");if(s<r&&i<0)throw new Error("'increment' must be > 0");if(s>r&&i>0)throw new Error("'increment' must be < 0")}if(r<-1e5)throw new Error("size of result exceeds limit");const n=Math.floor((r-s)/i)+1;if(n<=0||n>2e3)throw new Error("size of result exceeds limit");const a=new Array(n);let o=s;for(let e=0;e<n&&(a[e]=o,o+=i,!(i<0&&o<r||i>0&&o>r));e++);return a}),e.set("sort",(e,...t)=>{if(null==e)throw new Error("sequence must be provided");let r;if(Array.isArray(e))r=[...e];else{if("object"!=typeof e||null===e)throw new Error("can't sort "+typeof e);r=Object.values(e)}if(0===r.length)return r;let i="",s=!0;for(let e=0;e<t.length;e++){const r=t[e];0===e?"string"==typeof r&&(i=r):1===e&&"string"==typeof r&&"desc"===r.toLowerCase()&&(s=!1)}const n=(e,t)=>{if(!t||"value"===t)return e;const r=t.split(".");let i=e;for(const e of r){if(null==i)return;if("object"!=typeof i)return;i=i[e]}return i};return r.sort((e,t)=>{let r=i?n(e,i):e,a=i?n(t,i):t;if(null==r)return null==a?0:s?-1:1;if(null==a)return s?1:-1;if("string"==typeof r&&"string"==typeof a){const e=r.localeCompare(a);return s?e:-e}if("number"==typeof r&&"number"==typeof a){const e=r-a;return s?e:-e}const o=String(r),l=String(a),c=o.localeCompare(l);return s?c:-c})}),e.set("where",(()=>(e,t,...r)=>{if(!e)return[];let i,s="==";if(1===r.length)i=r[0];else{if(2!==r.length)throw new Error("where function requires 2-4 arguments");s=r[0],i=r[1]}const n=[];if(Array.isArray(e))for(let r=0;r<e.length;r++){const a=e[r],o=this.getNestedValue(a,t);this.checkCondition(o,i,s)&&n.push(a)}else if("object"==typeof e)for(const[r,a]of Object.entries(e))if(Array.isArray(a)){const e=a.filter(e=>{const r=this.getNestedValue(e,t);return this.checkCondition(r,i,s)});e.length>0&&n.push({[r]:e})}return n})()),e.set("intersect",(e,t)=>Array.isArray(e)&&Array.isArray(t)?e.filter(e=>t.includes(e)):[]),e.set("querify",(...e)=>{let t=[];if(t=1===e.length&&Array.isArray(e[0])?e[0]:e,t.length%2!=0)throw new Error("querify requires an even number of arguments (key-value pairs)");const r=[];for(let e=0;e<t.length;e+=2){const i=String(t[e]),s=String(t[e+1]);r.push([i,s])}return r.sort((e,t)=>e[0].localeCompare(t[0])),r.map(([e,t])=>`${encodeURIComponent(e).replace(/%20/g,"+")}=${encodeURIComponent(t).replace(/%20/g,"+")}`).join("&")}),e.set("isset",(e,t)=>{if(null==e)return!1;if(Array.isArray(e)){const r=Number(t);return isNaN(r)||!Number.isInteger(r)?(console.warn(`isset unable to use key of type ${typeof t} as index`),!1):e.length>r&&r>=0}if("object"==typeof e)return t in e;if("string"==typeof e){const r=Number(t);return isNaN(r)||!Number.isInteger(r)?(console.warn(`isset unable to use key of type ${typeof t} as index`),!1):e.length>r&&r>=0}return console.warn(`calling isset with unsupported type "${typeof e}" (${e.constructor?.name||typeof e}) will always return false.`),!1})}doIndex(e,t){if(null==e)return null;if(0===t.length)return e;let r=e;for(const e of t){if(null==r)return null;if(Array.isArray(r))r=this.indexArray(r,e);else if("string"==typeof r)r=this.indexString(r,e);else{if("object"!=typeof r)throw new Error("can't index item of type "+typeof r);r=this.indexObject(r,e)}}return r}indexArray(e,t){const r=this.toInteger(t);if(null===r)throw new Error("cannot index slice/array with type "+typeof t);return r<0||r>=e.length?null:e[r]}indexString(e,t){const r=this.toInteger(t);if(null===r)throw new Error("cannot index string with type "+typeof t);return r<0||r>=e.length?null:e.charAt(r)}indexObject(e,t){const r=String(t);if(e.hasOwnProperty(r))return e[r];const i=Object.keys(e).find(e=>e.toLowerCase()===r.toLowerCase());if(i)return e[i];if(e instanceof Map){if(e.has(r))return e.get(r);for(const t of e.keys())if(String(t).toLowerCase()===r.toLowerCase())return e.get(t)}return null}toInteger(e){if("number"==typeof e)return Number.isInteger(e)?e:Math.floor(e);if("string"==typeof e){const t=parseInt(e,10);if(!isNaN(t))return t}return null}checkCondition(e,t,r){const i=r.toLowerCase().trim();if(null==e&&null==t)return["==","=","eq",""].includes(i);if(null==e||null==t)return["!=","<>","ne"].includes(i);if("in"===i)return(Array.isArray(t)||"string"==typeof t&&"string"==typeof e)&&t.includes(e);if("intersect"===i)return!(!Array.isArray(e)||!Array.isArray(t))&&e.some(e=>t.includes(e));const[s,n]=this.normalizeForComparison(e,t);switch(i){case"":case"=":case"==":case"eq":return s===n;case"!=":case"<>":case"ne":return s!==n;case"<":case"lt":return s<n;case"<=":case"le":return s<=n;case">":case"gt":return s>n;case">=":case"ge":return s>=n;default:return!1}}normalizeForComparison(e,t){if("number"==typeof e&&"number"==typeof t)return[e,t];if("number"==typeof e&&"string"==typeof t){const r=parseFloat(t);if(!isNaN(r))return[e,r]}if("string"==typeof e&&"number"==typeof t){const r=parseFloat(e);if(!isNaN(r))return[r,t]}return"string"==typeof e&&"string"==typeof t||"boolean"==typeof e&&"boolean"==typeof t?[e,t]:[String(e),String(t)]}registerSafeFunctions(e){e.set("return",(...e)=>0===e.length?"":1===e.length?e[0]:e),e.set("cond",(...e)=>{if(e.length<2)throw new Error("cond requires at least 2 arguments");const t=e[0],r=e[1],i=e.length>2?e[2]:"";let s=!1;return!0===t||1===t?s=!0:"string"==typeof t?s=t.length>0&&"false"!==t&&"0"!==t:"number"==typeof t?s=0!==t:Array.isArray(t)?s=t.length>0:t&&"object"==typeof t&&(s=Object.keys(t).length>0),s?r:i}),e.set("safeHTML",e=>e),e.set("safeCSS",e=>e),e.set("safeJS",e=>e),e.set("safeURL",e=>e),e.set("dict",(...e)=>{if(e.length%2!=0)throw new Error("dict requires an even number of arguments");const t={};for(let r=0;r<e.length;r+=2)t[String(e[r])]=e[r+1];return t}),e.set("slice",(...e)=>e),e.set("default",(e,t)=>null!=t&&""!==t&&0!==t?t:e),e.set("jsonify",(...e)=>{if(0===e.length)return"";let t,r={};if(1===e.length)t=e[0];else{if(2!==e.length)throw new Error("too many arguments to jsonify");{const i=e[0];t=e[1],i&&"object"==typeof i&&(r.prefix=i.prefix||"",r.indent=i.indent||"",r.noHTMLEscape=i.noHTMLEscape||!1)}}try{let e;return r.indent?(e=JSON.stringify(t,null,r.indent),r.prefix&&(e=e.split("\n").map(e=>r.prefix+e).join("\n"))):e=JSON.stringify(t),r.noHTMLEscape||(e=e.replace(/&/g,"\\u0026").replace(/</g,"\\u003c").replace(/>/g,"\\u003e")),e}catch(e){throw new Error(`failed to jsonify object: ${e.message}`)}})}registerFmtFunctions(e){e.set("printf",(e,...t)=>{let r=e,i=0;return r=r.replace(/%[vsdft%]/g,e=>{if("%%"===e)return"%";if(i>=t.length)return e;const r=t[i++];switch(e){case"%v":case"%s":default:return String(r);case"%d":return String(Math.floor(Number(r)||0));case"%f":return String(Number(r)||0);case"%t":return String(Boolean(r))}}),r}),e.set("print",(...e)=>e.map(e=>String(e)).join(" ")),e.set("println",(...e)=>e.map(e=>String(e)).join(" ")+"\n"),e.set("errorf",(e,...t)=>{let r=e;for(let e=0;e<t.length;e++)r=r.replace(/%[sd%]/,String(t[e]));return log34.error("Template Error:",r),""}),e.set("warnf",(e,...t)=>{let r=e;for(let e=0;e<t.length;e++)r=r.replace(/%[sd%]/,String(t[e]));return log34.warn("Template Warning:",r),""}),e.set("fmt",()=>({Print:(...e)=>e.map(e=>String(e)).join(" "),Printf:(e,...t)=>{let r=e;for(let e=0;e<t.length;e++)r=r.replace(/%[sd%]/,String(t[e]));return r},Println:(...e)=>e.map(e=>String(e)).join(" ")+"\n",Errorf:(e,...t)=>{let r=e;for(let e=0;e<t.length;e++)r=r.replace(/%[sd%]/,String(t[e]));return log34.error("Template Error:",r),""},Erroridf:(e,t,...r)=>{let i=t;for(let e=0;e<r.length;e++)i=i.replace(/%[sd%]/,String(r[e]));return log34.error("Template Error:",i),""},Warnf:(e,...t)=>{let r=e;for(let e=0;e<t.length;e++)r=r.replace(/%[sd%]/,String(t[e]));return log34.error("Template Warning:",r),""},Warnidf:(e,t,...r)=>{let i=t;for(let e=0;e<r.length;e++)i=i.replace(/%[sd%]/,String(r[e]));return log34.error("Template Warning:",i),""}}))}registerReflectFunctions(e){e.set("reflect",()=>({IsMap:e=>{if(null==e)return!1;if("object"!=typeof e||Array.isArray(e))return!1;if(e instanceof Map)return!0;if(e.constructor===Object)return!0;const t=Object.getPrototypeOf(e);return t===Object.prototype||null===t},IsSlice:e=>Array.isArray(e)}))}registerPathFunctions(e){e.set("path",()=>({Base:e=>{if(!e)return".";if(!(e=(e=e.replace(/\\/g,"/")).replace(/\/+$/,"")))return"/";const t=e.split("/");return t[t.length-1]||"/"},Clean:e=>{if(!e)return".";const t=(e=e.replace(/\\/g,"/")).startsWith("/"),r=e.split("/").filter(e=>e&&"."!==e),i=[];for(const e of r)".."===e?i.length>0&&".."!==i[i.length-1]?i.pop():t||i.push(".."):i.push(e);return e=i.join("/"),t&&(e="/"+e),e||(t?"/":".")},Dir:e=>{if(!e)return".";if(!(e=e.replace(/\/+$/,"")))return"/";const t=e.split("/");return t.pop(),t.join("/")||"."},Ext:e=>{const t=e.split("/").pop()||"",r=t.lastIndexOf(".");return-1===r||0===r?"":t.substring(r)},IsAbs:e=>e.startsWith("/"),Join:(...e)=>{if(0===e.length)return".";let t=e.filter(e=>e).map(e=>e.replace(/^\/+|\/+$/g,"")).join("/");return e[0]&&e[0].startsWith("/")&&(t="/"+t),t||"."},Split:e=>{if(!e)return[".",""];const t=e.lastIndexOf("/");return-1===t?["",e]:[e.substring(0,t),e.substring(t+1)]}}))}registerTransformFunctions(e){e.set("transform",()=>({Unmarshal:(...e)=>{if(e.length<1||e.length>2)throw new Error("unmarshal takes 1 or 2 arguments");let t,r,i={};if(1===e.length)t=e[0];else{const r=e[0];if(!r||"object"!=typeof r)throw new Error("first argument must be a map");i=r,t=e[1]}if(t&&"object"==typeof t&&"function"==typeof t.Content)try{const e=t.Content();return this.unmarshalContent(e,i)}catch(e){throw new Error(`failed to get content from resource: ${e.message}`)}if("string"==typeof t)r=t;else{if(!t||"function"!=typeof t.toString)throw new Error(`type ${typeof t} not supported`);r=t.toString()}return r&&""!==r.trim()?this.unmarshalContent(r,i):null},Plainify:e=>{const t=String(e);return this.stripHTML(t)}})),e.set("unmarshal",(...t)=>e.get("transform")().Unmarshal(...t)),e.set("plainify",e=>{const t=String(e);return this.stripHTML(t)})}stripHTML(e){if(!e.includes("<")&&!e.includes(">"))return e;let t=e.replace(/\n/g," ").replace(/<\/p>/gi,"\n").replace(/<br\s*\/?>/gi,"\n").replace(/<\/div>/gi,"\n").replace(/<\/h[1-6]>/gi,"\n").replace(/<\/li>/gi,"\n").replace(/<\/tr>/gi,"\n").replace(/<\/blockquote>/gi,"\n");t=t.replace(/<[^>]*>/g,"");const r=t.split("\n");return t=r.map(e=>e.trim().replace(/\s+/g," ")).filter(e=>e.length>0).join("\n").trim(),t=t.replace(/\n\s*\n/g,"\n"),t}unmarshalContent(e,t={}){const r=e.trim();if(!r)return null;let i=t.format;i||(i=this.detectFormat(r));try{switch(i.toLowerCase()){case"json":return JSON.parse(r);case"yaml":case"yml":return this.parseYAML(r);case"toml":return this.parseTOML(r);case"csv":return this.parseCSV(r);default:throw new Error(`format "${i}" not supported`)}}catch(e){throw new Error(`failed to unmarshal ${i}: ${e.message}`)}}detectFormat(e){const t=e.trim();if(t.startsWith("{")&&t.endsWith("}")||t.startsWith("[")&&t.endsWith("]"))try{return JSON.parse(t),"json"}catch{}return t.startsWith("---")||/^[a-zA-Z_][a-zA-Z0-9_]*\s*:\s*.+/m.test(t)?"yaml":/^\[.*\]$/m.test(t)||/^[a-zA-Z_][a-zA-Z0-9_]*\s*=\s*.+/m.test(t)?"toml":/^[^,\n]*,[^,\n]*/.test(t)?"csv":"json"}parseYAML(e){const t=e.split("\n"),r={};for(const e of t){const t=e.trim();if(!t||t.startsWith("#")||"---"===t)continue;const i=t.indexOf(":");if(i>0){const e=t.substring(0,i).trim();let s=t.substring(i+1).trim();(s.startsWith('"')&&s.endsWith('"')||s.startsWith("'")&&s.endsWith("'"))&&(s=s.slice(1,-1)),"true"===s?r[e]=!0:"false"===s?r[e]=!1:/^\d+$/.test(s)?r[e]=parseInt(s,10):/^\d*\.\d+$/.test(s)?r[e]=parseFloat(s):r[e]=s}}return r}parseTOML(e){const t=e.split("\n"),r={};let i="";for(const e of t){const t=e.trim();if(!t||t.startsWith("#"))continue;if(t.startsWith("[")&&t.endsWith("]")){i=t.slice(1,-1),r[i]||(r[i]={});continue}const s=t.indexOf("=");if(s>0){const e=t.substring(0,s).trim();let n,a=t.substring(s+1).trim();(a.startsWith('"')&&a.endsWith('"')||a.startsWith("'")&&a.endsWith("'"))&&(a=a.slice(1,-1)),n="true"===a||"false"!==a&&(/^\d+$/.test(a)?parseInt(a,10):/^\d*\.\d+$/.test(a)?parseFloat(a):a),i?r[i][e]=n:r[e]=n}}return r}parseCSV(e){const t=e.trim().split("\n");if(0===t.length)return[];const r=this.parseCSVLine(t[0]),i=[];for(let e=1;e<t.length;e++){const s=this.parseCSVLine(t[e]),n={};for(let e=0;e<r.length;e++){const t=r[e],i=e<s.length?s[e]:"";/^\d+$/.test(i)?n[t]=parseInt(i,10):/^\d*\.\d+$/.test(i)?n[t]=parseFloat(i):n[t]="true"===i||"false"!==i&&i}i.push(n)}return i}parseCSVLine(e){const t=[];let r="",i=!1;for(let s=0;s<e.length;s++){const n=e[s];'"'===n?i&&'"'===e[s+1]?(r+='"',s++):i=!i:","!==n||i?r+=n:(t.push(r.trim()),r="")}return t.push(r.trim()),t}getNestedValue(e,t){if(!e||!t)return;const r=t.replace(/^\\.+/,"").split(".");let i=e;for(let e=0;e<r.length;e++){const t=r[e];if(null==i)return;if("object"==typeof i){if(i.hasOwnProperty(t)){i=i[t];continue}const e=Object.keys(i).find(e=>e.toLowerCase()===t.toLowerCase());if(e){i=i[e];continue}const r=t.toLowerCase();if("function"==typeof i[r])try{i=i[r]();continue}catch(e){return}return}return}return i}}}});var log35,PageBuilder,Taxonomy2,init_template2=__esm({"internal/domain/template/factory/template.ts"(){init_type8(),init_template(),init_executor(),init_parser(),init_lookup(),init_namespace(),init_baseof(),init_registry(),Factory2=class{async create(e){return this.createWithConfig(e,{})}async createWithConfig(e,t){try{const r=(new Builder).withFs(e).withNamespaces(new RegularTemplateNamespace,new PartialTemplateNamespace,new ShortcodeTemplateNamespace);t.services?r.withServices(t.services):t.funcMap?r.withFuncMap(t.funcMap):r.withFuncMap(function(){const e=new Map;return newTemplateRegistry().registerCoreFunctions(e),e}());const i=await r.buildLookup().buildParser().buildExecutor().build();return await i.markReady(),i}catch(e){const t=e instanceof Error?e.message:String(e);throw new TemplateError(`Failed to create template engine: ${t}`,"FACTORY_CREATE_FAILED")}}async createWithServices(e,t){return this.createWithConfig(e,{services:t})}},Builder=class{funcMap=new Map;services;fs;templateNamespace;partialNamespace;shortcodeNamespace;lookup;parser;executor;withFs(e){return this.fs=e,this}withNamespaces(e,t,r){return this.templateNamespace=e,this.partialNamespace=t,this.shortcodeNamespace=r,this}withFuncMap(e){return this.funcMap=new Map([...this.funcMap,...e]),this}withServices(e){return this.services=e,this.funcMap=function(e){const t=new Map;return newTemplateRegistry().registerAllFunctions(t,e),t}(e),this}buildLookup(){const e=new BaseOf;return this.lookup=function(e,t){return new Lookup(e,t)}(e,this.funcMap),this}buildParser(){return this.parser=function(e=new Map){return new Parser(e)}(this.funcMap),this}buildExecutor(){return this.executor=new Executor,this}async build(){if(!this.fs)throw new TemplateError("File system is required","BUILDER_FS_REQUIRED");if(!this.templateNamespace)throw new TemplateError("Template namespace is required","BUILDER_TEMPLATE_NAMESPACE_REQUIRED");if(!this.partialNamespace)throw new TemplateError("Partial namespace is required","BUILDER_PARTIAL_NAMESPACE_REQUIRED");if(!this.shortcodeNamespace)throw new TemplateError("Shortcode namespace is required","BUILDER_SHORTCODE_NAMESPACE_REQUIRED");if(!this.lookup)throw new TemplateError("Lookup is required","BUILDER_LOOKUP_REQUIRED");if(!this.parser)throw new TemplateError("Parser is required","BUILDER_PARSER_REQUIRED");if(!this.executor)throw new TemplateError("Executor is required","BUILDER_EXECUTOR_REQUIRED");const e=(t=this.executor,r=this.lookup,i=this.parser,s=this.templateNamespace,n=this.partialNamespace,a=this.shortcodeNamespace,o=this.fs,new TemplateEngine(t,r,i,s,n,a,o));var t,r,i,s,n,a,o;!function(e){for(const t of engineDependentFunctions)try{t.updateEngine(e)}catch(e){log34.error(`❌ Failed to update function ${t.getFunctionName()}:`,e)}}(e);try{await e.loadTemplates()}catch(e){const t=e instanceof Error?e.message:String(e);throw new TemplateError(`Failed to load templates: ${t}`,"BUILDER_LOAD_TEMPLATES_FAILED")}return e}}}}),init_template3=__esm({"internal/domain/template/index.ts"(){init_type8(),init_type8(),init_baseof(),init_info(),init_namespace(),init_executor(),init_parser(),init_lookup(),init_template(),init_template2()}}),init_pagebuilder=__esm({"internal/domain/content/entity/pagebuilder.ts"(){init_pagecontent(),init_frontmatter(),init_kind(),init_section(),init_standalone(),init_log(),init_page(),init_pagemeta(),init_pagelayout(),init_paginator(),init_shortcode2(),init_template3(),log35=getDomainLogger("content",{component:"pagebuilder"}),PageBuilder=class{urlSvc;langSvc;taxonomySvc;templateSvc;pageMapper;taxonomy;term;section;standalone;converter;contentHub;source;sourceByte;kind;singular;term_;langIdx;fm;fmParser;c;renderableDocument=null;constructor(e,t,r,i,s,n,a,o,l,c,h){this.urlSvc=e,this.langSvc=t,this.taxonomySvc=r,this.templateSvc=i,this.pageMapper=null,this.taxonomy=n,this.term=a,this.section=o,this.standalone=l,this.converter=c,this.contentHub=h,this.source=null,this.sourceByte=new Uint8Array,this.kind="",this.singular="",this.term_="",this.langIdx=-1,this.fm=null,this.fmParser=null,this.c=null}withSource(e){const t=Object.assign(Object.create(Object.getPrototypeOf(this)),this);return t.reset(),t.source=e,t}withLangIdx(e){return this.langIdx=e,this}reset(){this.c=null,this.kind="",this.langIdx=-1}async build(){if(!this.source)throw new Error("source for page builder is nil");const e=await this.source.contentSource();this.sourceByte=e,await this.parse(e);const t=await this.buildInternal();return await this.render(t),t}async kindBuild(){if(!this.source)throw new Error("source for page builder is nil");return await this.parseKind(),-1===this.langIdx?await this.parseLanguageByDefault():await this.parseLanguageByIdx(this.langIdx),this.fm={path:"",lang:"",kind:"",title:"",description:"",weight:999,terms:{},params:{}},this.c=newContent(new Uint8Array),await this.buildInternal()}async buildInternal(){switch(this.kind){case getKindMain("home"):return await this.buildHome();case getKindMain("section"):return await this.buildSection();case getKindMain("page"):return await this.buildPage();case getKindMain("taxonomy"):return await this.buildTaxonomy();case getKindMain("term"):return await this.buildTerm();case getKindMain("404"):return await this.build404();case getKindMain("sitemap"):return await this.buildSitemap();default:throw new Error(`unknown kind "${this.kind}"`)}}async buildPage(){const e=await this.newPage(this.source,this.c);return await this.applyFrontMatter(e),e.pageMap=this.pageMapper,await this.buildOutput(e),await this.adaptPagination(e),e}async buildPageWithKind(e){const t=await this.newPage(this.source,this.c);if(await this.applyFrontMatter(t),t.pageMap=this.pageMapper,t.kind_=e,e===getKindMain("sitemap")||e===getKindMain("404")){const e=t.meta;e&&(e.list="never")}return await this.buildOutput(t),t}async applyFrontMatter(e){if(this.fm){e.title_=this.fm.title,e.description_=this.fm.description;const t=e.meta;t&&(t.weight=this.fm.weight,t.parameters=this.fm.params||{},this.fm.date&&(t.date=this.fm.date),void 0!==this.fm.organization&&(t.org=this.fm.organization),void 0!==this.fm.author&&(t.authorInfo=this.fm.author),void 0!==this.fm.menu&&(t.menuConfig=this.fm.menu))}}async buildHome(){const e=await this.buildPageWithKind(getKindMain("home"));return await this.buildPagination(e),e}async buildSection(){const e=await this.buildPageWithKind(getKindMain("section"));return await this.buildPagination(e),e}async build404(){const e=await this.buildPageWithKind(getKindMain("404"));return await this.adaptPagination(e),e}async buildSitemap(){const e=await this.buildPageWithKind(getKindMain("sitemap"));return await this.adaptPagination(e),e}async buildTaxonomy(){const e=this.taxonomy.getTaxonomy(this.source.file.paths().path()),t=e?e.singular():"",r=await this.newTaxonomy(this.source,this.c,t);return r.pageMap=this.pageMapper,await this.buildOutput(r),await this.buildPagination(r),r}async buildTerm(){const e=this.source.file.paths(),t=this.taxonomy.getTaxonomy(e.path()),r=t?t.singular():"",i=e.unnormalized().baseNameNoIdentifier(),s=await this.newTerm(this.source,this.c,r,i);return s.pageMap=this.pageMapper,await this.buildOutput(s),await this.buildPagination(s),s}async render(e){if(this.c?.lazyRendered)return void(this.c.lazyRender=async()=>{const t=await(this.renderableDocument?.render({maxSummaryLength:300,wordsPerMinute:200,shortcodeRenderer:this.createShortcodeRenderer(e)}));this.c?.updateWithContentResult(t)});log35.info(`Lazy rendering not enabled, rendering immediately for page: ${e.path()}`);const t=await(this.renderableDocument?.render({maxSummaryLength:300,wordsPerMinute:200,shortcodeRenderer:this.createShortcodeRenderer(e)}));this.c?.updateWithContentResult(t)}async parse(e){this.renderableDocument=await this.converter.prepareRender(e),this.c=newContent(e),this.c.toc=this.renderableDocument.toc(),this.fmParser=new FrontMatterParserImpl(this.renderableDocument.frontMatter(),this.langSvc,this.taxonomySvc),await this.parseFrontMatter(),await this.parseLanguage(),await this.parseKind(),await this.parseTerms()}async parseTerms(){this.fm&&this.fm.terms&&(this.term.terms=this.fm.terms)}async parseKind(){const e=this.source.file.paths();let t="";if(this.fm&&(t=this.fm.kind||""),""===t)switch(t=getKindMain("page"),e.baseNoLeadingSlash()){case PAGE_HOME_BASE:case"":t=getKindMain("home");break;case STANDALONE_PAGE_404_BASE:t=getKindMain("404");break;case STANDALONE_PAGE_SITEMAP_BASE:t=getKindMain("sitemap");break;default:if(this.source.file.isBranchBundle()){t=getKindMain("section");const r=this.taxonomy.getTaxonomy(e.path());this.taxonomy.isZero(r)||(t=this.taxonomy.isTaxonomyPath(e.path())?getKindMain("taxonomy"):getKindMain("term"))}}this.kind=t}async parseLanguageByDefault(){const e=this.langSvc.defaultLanguage(),t=await this.langSvc.getLanguageIndex(e);this.source.identity.lang=e,this.source.identity.langIdx=t}async parseLanguageByIdx(e){const t=this.langSvc.getLanguageByIndex(e);this.source.identity.lang=t,this.source.identity.langIdx=e}async parseLanguage(){const[e,t]=this.langSvc.getSourceLang(this.source.file.fileInfo().root());if(t){const t=this.langSvc.getLanguageIndex(e);return this.source.identity.lang=e,void(this.source.identity.langIdx=t)}await this.parseLanguageByDefault()}async parseFrontMatter(){this.fmParser?this.fm=await this.fmParser.parse(this.urlSvc.baseUrl()):this.fm={path:"",lang:"",kind:"",title:"",description:"",weight:999,terms:{},params:{}}}createShortcodeRenderer(e){return async t=>{if(!this.templateSvc)return log35.warn(`Template service not available for shortcode: ${t.name}`),"";try{return t.name?await this.doRenderShortcode(t,null,0,e):(log35.warn("Shortcode missing name"),"")}catch(e){return log35.error(`Error rendering shortcode "${t.name}":`,e),""}}}async doRenderShortcode(e,t,r,i){if(e.inline)return log35.warn("Inline shortcodes are not supported yet."),"";let s=new ShortcodeWithPage(e.params||{},"",i,t,e.name,"object"==typeof e.params&&!Array.isArray(e.params),e.ordinal||0,e.indentation||"",e.pos||0);if(e.inner&&e.inner.length>0){let n="";for(const t of e.inner)if("string"==typeof t)n+=t;else{if("object"!=typeof t||!("name"in t))return log35.error(`Illegal state on shortcode rendering of "${e.name}". Illegal type in inner data: ${typeof t}`),"";n+=await this.doRenderShortcode(t,s,r+1,i)}if(e.doMarkup)try{const r=await this.renderShortcodeMarkdown(i,n);s=new ShortcodeWithPage(e.params||{},r,i,t,e.name,"object"==typeof e.params&&!Array.isArray(e.params),e.ordinal||0,e.indentation||"",e.pos||0)}catch(e){throw new Error(`Failed to process inner content: ${e}`)}else s=new ShortcodeWithPage(e.params||{},n,i,t,e.name,"object"==typeof e.params&&!Array.isArray(e.params),e.ordinal||0,e.indentation||"",e.pos||0)}try{let t=await(this.templateSvc?.execute(e.name,s));if(!e.inner?.length&&e.indentation){const r=t?.split("\n");t=r?.map((t,r)=>0===r?t:e.indentation+t).join("\n")}return t||""}catch(t){if(t instanceof TemplateError&&"SHORTCODE_NOT_FOUND"===t.code)return e.rawContent;throw new Error(`Failed to process shortcode: ${t instanceof Error?t.message:String(t)}`)}}async renderShortcodeMarkdown(e,t){try{const r={document:e,documentID:e.path(),documentName:e.name(),filename:e.pageFile().filename()},i={ctx:{},src:(new TextEncoder).encode(t),renderTOC:!1,getRenderer:()=>null},s=await this.converter.convert(r,i);let n=(new TextDecoder).decode(s.bytes());return n.includes("\n")||(n=n.replace(/^<p>(.*)<\/p>\n$/,"$1")),n}catch(e){return log35.error("Error rendering shortcode markdown:",e),""}}async buildPagination(e){const t=new PaginatorManagerImpl({pageSize:()=>10,globalRegularPages:async()=>this.contentHub?await this.contentHub.globalRegularPages():[]},e);e.pagerManager=t}async adaptPagination(e){const t={current:()=>new PaginatorImpl([],0,10,e.path()).pagers()[0],setCurrent:t=>{throw new Error(`pagination not supported for this page: ${e.path()}`)},paginator:async()=>{throw new Error(`pagination not supported for this page: ${e.path()}`)},paginate:async t=>{throw new Error(`pagination not supported for this page: ${e.path()}`)}};e.pagerManager=t}async buildOutput(e){}async newPage(e,t){const r=new Meta(this.urlSvc.baseUrl(),"always",{},999,e.file.fileInfo().modTime()),i=new Layout;return new PageImpl(e,t,r,i,"",getKindMain("page"),this.pageMapper)}async newTaxonomy(e,t,r){const i=new Meta(this.urlSvc.baseUrl(),"always",{},999,e.file.fileInfo().modTime()),s=new Layout;return new TaxonomyPageImpl(e,t,i,s,r,r,getKindMain("taxonomy"),this.pageMapper)}async newTerm(e,t,r,i){const s=new Meta(this.urlSvc.baseUrl(),"always",{},999,e.file.fileInfo().modTime()),n=new Layout;return new TermPageImpl(e,t,s,n,r,i,i,getKindMain("term"),this.pageMapper)}}}});import*as path20 from"path";import*as filepath from"path";var log36,Term,init_taxonomy3=__esm({"internal/domain/content/entity/taxonomy.ts"(){init_pagetrees(),init_fileinfo2(),init_pagesource(),Taxonomy2=class{views;fsSvc;constructor(e,t){this.views=e,this.fsSvc=t}async assemble(e,t,r){for(const i of this.views){const s=this.pluralTreeKey(i.plural()),n=(e.get(s),newPageSource(newFileInfo2(this.fsSvc.newFileMetaInfo(s+"/_index.md")))),a=await t.withSource(n).withLangIdx(r).kindBuild();e.insertIntoValuesDimension(s,newPageTreesNode2(a))}}isTaxonomyPath(e){const t=this.getTaxonomy(e);return!!t&&e===path20.join(this.pluralTreeKey(t.plural()),"_index.md")}pluralTreeKey(e){return function(...e){let t="";return e.length>0&&(t=e[0],e.length>1&&(t=path20.join(...e))),t=t.replace(/^[\.\/ \s]+|[\.\/ \s]+$/g,""),t=filepath.posix.normalize(t.toLowerCase().replace(/[^\w\-_\/]/g,"")),""===t||"/"===t?"":("/"!==t[0]&&(t="/"+t),t)}(e)}getTaxonomy(e){for(const t of this.views)if(e.startsWith(this.pluralTreeKey(t.plural())))return t;return null}isZero(e){return!e||""===e.singular()}}}});function toStringSlicePreserveString(e){return e?Array.isArray(e)?e.map(e=>String(e)):"string"==typeof e?[e]:[String(e)]:null}function toInt(e){if("number"==typeof e)return Math.floor(e);if("string"==typeof e){const t=parseInt(e,10);if(isNaN(t))throw new Error(`cannot convert "${e}" to int`);return t}throw new Error(`cannot convert ${typeof e} to int`)}var SitePager,log38,Page2,init_term=__esm({"internal/domain/content/entity/term.ts"(){init_pagetrees(),init_fileinfo2(),init_pagesource(),init_frontmatter(),init_doctree(),init_log(),log36=getDomainLogger("content",{component:"term"}),Term=class{terms;fsSvc;constructor(e){this.terms={},this.fsSvc=e}async assemble(e,t,r,i){const s=new NodeShiftTreeWalker({tree:e,lockType:2,handle:async(s,n,a)=>{const[o,l]=n.getPage();if(!l)return[!1,null];for(const n of r.taxonomy.views){const a=toStringSlicePreserveString(getParam(o.params(),n.plural(),!1));if(!a)continue;const l=getParamToLower(o.params(),n.plural()+"_weight");let c=0;if(null==l||""===l)c=0;else try{c=toInt(l)}catch(e){log36.warn(`Unable to convert taxonomy weight ${l} to int for "${o.paths().path()}"`)}for(let l=0;l<a.length;l++){const h=a[l];if(""===h)continue;const u="/"+n.plural()+"/"+h;try{const a=newFileInfo2(this.fsSvc.newFileMetaInfo(u+"/_index.md")),g=a.paths(),d=newPageSource(a),p=await r.withSource(d).withLangIdx(i).kindBuild();e.insertIntoValuesDimension(g.base(),newPageTreesNode2(p));const m=e.get(g.base());if(m){const[e,t]=m.getPage();if(!t)return[!1,null];const r=e;r.term=h,r.singular=n.singular()}let f=s;""===f&&(f="/");const y=g.base()+f,[w,S]=m.getPage();if(!S)return[!1,null];t.insert(y,new WeightedTermTreeNode(newPageTreesNode2(o),{page:w,ordinal:l,weight:c,Weight:()=>c,Ordinal:()=>l}))}catch(e){return[!1,e]}}}return[!1,null]}});try{return await s.walk(),null}catch(e){return e}}}}}),init_content3=__esm({"internal/domain/content/index.ts"(){init_type4(),init_hub(),init_kind(),init_identity(),init_fileinfo2(),init_sort(),init_frontmatter(),init_classifier(),init_content2(),init_converter(),init_pagebuilder(),init_pagetrees(),init_pagemap(),init_taxonomy3(),init_term(),init_section(),init_standalone(),init_translator()}}),init_pager=__esm({"internal/domain/site/entity/pager.ts"(){init_log(),getDomainLogger("site",{component:"pager"}),SitePager=class e{page;pager;constructor(e,t){this.page=e,this.pager=t}pageNumber(){return this.pager.pageNumber()}totalPages(){return this.pager.totalPages()}url(){return this.pager.url()}pages(){return this.pager.pages()}allPages(){return this.pager.allPages()}pagers(){return this.pager.pagers()}first(){return this.pager.first()}last(){return this.pager.last()}hasPrev(){return this.pager.hasPrev()}prev(){return this.pager.prev()}hasNext(){return this.pager.hasNext()}next(){return this.pager.next()}get PageNumber(){return this.pageNumber()}get TotalPages(){return this.totalPages()}get URL(){let e=this.url();return e.startsWith("/")&&(e=e.slice(1)),this.page.Site.getURL().relURL(e)}get HasPrev(){return this.hasPrev()}get HasNext(){return this.hasNext()}get First(){const t=this.first();return t?new e(this.page,t):null}get Last(){const t=this.last();return t?new e(this.page,t):null}get Prev(){const t=this.prev();return t?new e(this.page,t):null}get Next(){const t=this.next();return t?new e(this.page,t):null}get Pagers(){return this.pagers().map(t=>new e(this.page,t))}get Pages(){const e=this.pages();return this.page.sitePages(e)}get AllPages(){const e=this.pager.allPages();return this.page.sitePages(e)}}}});import path21 from"path";var BaseURL,URL2,log39,WeightedPage,WeightedPages,Taxonomy3,OrderedTaxonomyEntry,OrderedTaxonomy,TaxonomyList,TaxonomiesBuilder,init_page2=__esm({"internal/domain/site/entity/page.ts"(){init_log(),init_pager(),log38=getDomainLogger("site",{component:"page"}),Page2=class e{tmplSvc;langSvc;publisher;contentPage;pageOutput=null;site;resources=[];_paginator=null;_processedContent=null;_precomputedData={backlinks:null,tableOfContents:null,summary:null};constructor(e,t,r,i,s){this.tmplSvc=e,this.langSvc=t,this.publisher=r,this.contentPage=i,this.site=s}async precomputeTemplateData(){try{await Promise.all([this.precomputeBacklinks(),this.precomputeTableOfContents(),this.precomputeSummary()])}catch(e){log38.warn(`Failed to precompute data for ${this.paths().path()}: ${e}`)}}async precomputeBacklinks(){try{this._precomputedData.backlinks=await this.Backlinks()}catch(e){log38.debug(`Failed to precompute backlinks: ${e}`)}}async precomputeTableOfContents(){try{this._precomputedData.tableOfContents=this.TableOfContents}catch(e){log38.debug(`Failed to precompute TOC: ${e}`)}}async precomputeSummary(){try{this._precomputedData.summary=await this.Summary()}catch(e){log38.debug(`Failed to precompute summary: ${e}`)}}async processResources(e){this.resources=e}async render(){try{await this.renderResources(),await this.renderPage()}catch(e){log38.error(`Failed to render page ${this.paths().path()}: ${e}`)}}getPageOutput(){return this.pageOutput||(this.pageOutput=this.output()),this.pageOutput}async renderPage(){const e=this.layouts(),{preparer:t,found:r}=await this.tmplSvc.lookupLayout(e);if(!r)return void log38.warn(`Failed to find layout: ${e.join(",")} for page ${this.paths().path()}`);const i=[];let s=this.getPageOutput().targetPrefix();s=this.site.getLanguage().getCurrentLanguage()===s&&s===this.langSvc.defaultLanguage()?"":this.site.getLanguage().getCurrentLanguage(),i.push(path21.join(s,this.getPageOutput().targetFilePath())),await this.renderAndWritePage(t,i);const n=await this.current();if(n){let e=n.next();for(;e;){this.setCurrent(e);const r=[path21.join(s,e.url(),this.getPageOutput().targetFileBase())];await this.renderAndWritePage(t,r),e=e.next()}}}async renderAndWritePage(e,t){try{const r=await this.tmplSvc.executeWithContext(e,this);await this.publisher.publishSource(r,...t)}catch(e){throw this.errorf(e,"failed to publish page")}}async renderResources(){for(const e of this.resources){const t=[];let r=this.getPageOutput().targetPrefix();r=this.site.getLanguage().getCurrentLanguage()===r&&r===this.langSvc.defaultLanguage()?"":this.site.getLanguage().getCurrentLanguage();let i=e.path();t.push(path21.join(r,i));let s=null;try{const r=()=>e.pageFile().open();if(s=await r(),!s)throw new Error("Failed to open resource stream");let i;i="function"==typeof s.read?new ReadableStream({async start(e){try{const t=new Uint8Array(8192);for(;;){const r=await s.read(t);if(0===r.bytesRead)break;e.enqueue(t.slice(0,r.bytesRead))}e.close()}catch(t){e.error(t)}}}):new ReadableStream({start(e){e.close()}}),await this.publisher.publishFiles(i,...t)}catch(e){throw this.errorf(e,"failed to publish page resources")}finally{if(s)try{await s.close()}catch(e){log38.warn(`Failed to close resource stream: ${e}`)}}}}errorf(e,t,...r){const i=[this.pageIdentity().pageLanguage(),this.paths().path(),...r],s=`[%s] page "%s": ${t}: %s`,n=this.sprintf(s,...i,e.message||e);return new Error(n)}sprintf(e,...t){let r=0;return e.replace(/%s/g,()=>t[r++]||"")}clone(){const t=new e(this.tmplSvc,this.langSvc,this.publisher,this.contentPage,this.site);return t.resources=[...this.resources],t.pageOutput=this.pageOutput,t}pageIdentity(){return this.contentPage.pageIdentity()}pageFile(){return this.contentPage.pageFile()}staleVersions(){return this.contentPage.staleVersions()}section(){return this.contentPage.section()}paths(){return this.contentPage.paths()}path(){return this.contentPage.path()}slug(){return this.contentPage.slug()}file(){return this.contentPage.file()}name(){return this.contentPage.name()}title(){return this.contentPage.title()}kind(){return this.contentPage.kind()}scratch(){return this.contentPage.scratch()}get Scratch(){return this.contentPage.scratch()}IsAncestor(e){return this.contentPage.isAncestor(e.contentPage)}get Title(){return this.title()}get Section(){return this.contentPage.section()}get LinkTitle(){return this.title()}get IsSection(){return this.contentPage.isSection()}get IsPage(){return this.contentPage.isPage()}get Content(){return this.getPageOutput().content()}async WikilinkContent(){if(null!==this._processedContent)return this._processedContent;const e=await this.getPageOutput().content();return e?(this._processedContent=await this.site.ProcessWikilinks(this.slug(),e),this._processedContent):e}async Summary(){if(null!==this._precomputedData.summary)return this._precomputedData.summary;const e=await this.contentPage.output().summary();return this._precomputedData.summary=e,e}async ReadingTime(){return await this.getPageOutput().readingTime()}async WordCount(){return await this.getPageOutput().wordCount()}async Backlinks(){if(null!==this._precomputedData.backlinks)return this._precomputedData.backlinks;const e=this.site.GetBacklinks(this.slug()),t=[],r=await this.site.RegularPages();for(const i of e){const e=r.find(e=>e.slug()===i);e&&t.push(e)}return this._precomputedData.backlinks=t,t}OutgoingLinks(){const e=this.site.getPageGraph();return e?e.getOutgoingLinks(this.slug()):[]}get Description(){return this.description()}get Date(){return this.pageDate()}get LocalDate(){return this.pageDate().toLocaleDateString()}get RelPermalink(){let e;if(this.pageIdentity().pageLanguage()===this.langSvc.defaultLanguage())e=this.getPageOutput().targetFilePath();else{const t=this.getPageOutput().targetPrefix(),r=this.getPageOutput().targetFilePath();e=this.pathJoin(t,r)}return e.startsWith("/")&&(e=e.slice(1)),this.site.getURL().relURL(e)}get GitInfo(){return{}}get File(){return{BaseFileName:this.contentPage.file().baseFileName(),OriginalBaseName:this.contentPage.file().originalBaseFileName(),Dir:this.contentPage.file().dir()}}isHome(){return this.contentPage.isHome()}get IsHome(){return this.isHome()}isPage(){return this.contentPage.isPage()}isSection(){return this.contentPage.isSection()}isAncestor(e){return this.contentPage.isAncestor(e)}eq(e){return this.contentPage.eq(e)}isBundled(){return this.contentPage.isBundled()}layouts(){return this.contentPage.layouts()}output(){return this.contentPage.output()}pageOutputs(){return[this.contentPage.output()]}truncated(){return this.contentPage.truncated()}get Truncated(){return this.contentPage.truncated()}parent(){return this.contentPage.parent()}pages(){return this.contentPage.pages()}isStale(){return this.contentPage.pageIdentity().isStale()}clearStale(){this.contentPage.pageIdentity().clearStale()}prevInSection(){return this.contentPage.prevInSection()}nextInSection(){return this.contentPage.nextInSection()}sections(e){return this.contentPage.sections(e)}regularPages(){return this.contentPage.regularPages()}regularPagesRecursive(){return this.contentPage.regularPagesRecursive()}terms(e,t){return this.contentPage.terms(e,t)}isTranslated(){return this.contentPage.isTranslated()}translations(){return this.contentPage.translations()}rawContent(){return this.contentPage.rawContent()}description(){return this.contentPage.description?this.contentPage.description():""}params(){return this.contentPage.params?this.contentPage.params():{}}pageBaseUrl(){return this.contentPage.pageBaseUrl()?this.contentPage.pageBaseUrl():""}pageWeight(){return this.contentPage.pageWeight?this.contentPage.pageWeight():0}pageDate(){return this.contentPage.pageDate?this.contentPage.pageDate():new Date}publishDate(){return this.contentPage.publishDate?this.contentPage.publishDate():new Date}get PublishDate(){return this.publishDate()}async relatedKeywords(e){return this.contentPage.relatedKeywords?await this.contentPage.relatedKeywords(e):[]}shouldList(e){return!this.contentPage.shouldList||this.contentPage.shouldList(e)}shouldListAny(){return!this.contentPage.shouldListAny||this.contentPage.shouldListAny()}noLink(){return!!this.contentPage.noLink&&this.contentPage.noLink()}organization(){return this.contentPage.organization?this.contentPage.organization():void 0}author(){return this.contentPage.author?this.contentPage.author():void 0}menu(){return this.contentPage.menu?this.contentPage.menu():void 0}current(){return this.contentPage.current()}setCurrent(e){this.contentPage.setCurrent(e)}posOffset(e){return this.contentPage.posOffset(e)}paginator(){return this.contentPage.paginator()}async paginate(e){return this.contentPage.paginate(e)}get Plain(){return this.rawContent()}get TableOfContents(){if(null!==this._precomputedData.tableOfContents)return this._precomputedData.tableOfContents;const e=this.getPageOutput().tableOfContents();return this._precomputedData.tableOfContents=e,e}get Params(){return this.params()}get Site(){return this.site}get Sites(){return{First:this.site,Default:this.site}}get Lastmod(){return this.contentPage.pageDate?this.contentPage.pageDate():null}get Sitemap(){return{ChangeFreq:"weekly",Priority:.5,Filename:"sitemap.xml"}}get IsTranslated(){return this.isTranslated()}async Paginator(){return this._paginator||await this.setupCurrentPaginator(),this._paginator}async Paginate(e){try{const t=e.map(e=>e.contentPage),r=await this.contentPage.paginate(t);return r&&(this._paginator=new SitePager(this,r)),this._paginator}catch(e){return log38.error("Error during pagination:",e),null}}async setupCurrentPaginator(){try{const e=await this.contentPage.paginator();this._paginator=e?new SitePager(this,e):null}catch(e){log38.error("Error initializing Paginator:",e),this._paginator=null}}get Language(){return{Lang:this.pageIdentity().pageLanguage(),LanguageName:this.langSvc.getLanguageName(this.pageIdentity().pageLanguage()),Title:this.title(),Weight:this.pageWeight()}}get Permalink(){return this.RelPermalink}sitePages(e){const t=[];for(const r of e){const e=this.sitePage(r);e&&t.push(e)}return t}sitePage(t){try{return null===t?(log38.warn(`Invalid content page provided: ${t}`),null):new e(this.tmplSvc,this.langSvc,this.publisher,t,this.site)}catch(e){return log38.error(`Error creating site page: ${e}`),null}}pathJoin(...e){return e.filter(e=>e&&e.length>0).map(e=>e.replace(/^\/+|\/+$/g,"")).filter(e=>e.length>0).join("/")}joinURL(e,t){return e?t?(e.endsWith("/")&&(e=e.slice(0,-1)),t.startsWith("/")||(t="/"+t),e+t):e:t}async Translations(){const e=await this.translations();return Array.isArray(e)?e.map(e=>this.sitePage(e)).filter(e=>null!==e):[]}async GetTerms(e){const t=await this.terms(this.site.getLanguage().currentLanguageIndex(),e);return Array.isArray(t)?t.map(e=>this.sitePage(e)).filter(e=>null!==e):[]}async Pages(){return await this.getSitePages()}get Page(){return this.contentPage}get Kind(){return this.kind()}get Type(){if("home"===this.kind())return"page";if("page"===this.kind()){const e=this.section();if(e&&e.length>0)return e}return"page"}get Parent(){return this.sitePage(this.contentPage.parent())}async getSitePages(){const e=await this.contentPage.pages();return!e||Array.isArray(e)&&0===e.length?[]:this.sitePages(e)}}}}),init_baseurl=__esm({"internal/domain/site/valueobject/baseurl.ts"(){BaseURL=class e{url;withPath;withPathNoTrailingSlash;withoutPath;basePath;basePathNoTrailingSlash;isRelative;constructor(e,t=!1){if(this.url=e,this.isRelative=t,this.withPath=e.toString(),this.withPathNoTrailingSlash=this.withPath.replace(/\/$/,""),t)this.withoutPath="/";else{const t=new URL(e.toString());t.pathname="",this.withoutPath=t.toString().replace(/\/$/,"")}this.basePath=e.pathname,this.basePathNoTrailingSlash=this.basePath.replace(/\/$/,"")}static fromString(t){try{t&&"/"!==t||(t="/");const r=t.trim();if(r.startsWith("/")&&!r.startsWith("//")){const t=new URL(r,"http://localhost");return t.pathname.endsWith("/")||(t.pathname+="/"),new e(t,!0)}if(r.startsWith("//")){const t=new URL("https:"+r);return t.pathname.endsWith("/")||(t.pathname+="/"),new e(t)}if(r.includes("://")){const t=new URL(r);if(!["http:","https:"].includes(t.protocol))throw new Error(`Unsupported protocol: ${t.protocol}. Only http and https are supported.`);return t.pathname.endsWith("/")||(t.pathname+="/"),new e(t)}if(r.includes(":")&&!r.includes("/")){const e=r.indexOf(":"),t=r.substring(0,e+1);throw new Error(`Unsupported protocol: ${t}. Only http and https are supported.`)}const i=new URL("https://"+r);return i.pathname.endsWith("/")||(i.pathname+="/"),new e(i)}catch(e){throw new Error(`Invalid URL: ${e?.message||"Unknown error"}`)}}getRoot(e){return this.isRelative?this.basePath:e.startsWith("/")?this.withoutPath:this.withPath}toString(){return this.isRelative?this.basePath:this.withPath}path(){return this.url.pathname}port(){return this.url.port?parseInt(this.url.port):0}hostURL(){return this.isRelative?"/":this.toString().replace(this.path(),"")}protocol(){return this.url.protocol}host(){return this.url.host}hostname(){return this.url.hostname}getURL(){return new URL(this.url.toString())}withProtocol(t){if(this.isRelative)throw new Error("Cannot change protocol of relative URL");const r=this.getURL();let i=t;const s=i.endsWith("://"),n=i.endsWith(":");if(s?i=i.slice(0,-3):n&&(i=i.slice(0,-1)),n&&!r.pathname)throw new Error(`cannot determine BaseURL for protocol ${t}`);return r.protocol=i,e.fromString(r.toString())}withPort(t){if(this.isRelative)throw new Error("Cannot set port on relative URL");const r=this.getURL();return r.port=t.toString(),e.fromString(r.toString())}isRelativeURL(){return this.isRelative}isAbsoluteURL(){return!this.isRelative}}}}),init_text=__esm({"pkg/text/index.ts"(){}}),init_url=__esm({"internal/domain/site/entity/url.ts"(){init_baseurl(),init_paths2(),init_text(),URL2=class e{base;canonical;baseURL=null;constructor(e,t=!1){this.base=e,this.canonical=t,this.setup()}setup(){try{this.baseURL=BaseURL.fromString(this.base)}catch(e){throw new Error(e?.message||"Failed to setup URL")}}isAbsURL(e){return e.startsWith("http://")||e.startsWith("https://")?[!0,null]:[/^[a-zA-Z][a-zA-Z\d+\-.]*:/.test(e),null]}startWithBaseUrlRoot(e){return!!this.baseURL&&e.startsWith(this.baseURL.getRoot(e))}isProtocolRelPath(e){return e.startsWith("//")}trimBaseUrlRoot(e){if(!this.baseURL)return e;const t=this.baseURL.getRoot(e);return e.endsWith(t)?e.slice(0,-t.length):e}addContextRoot(e){if(!this.baseURL)return e;let t=e;return this.canonical||(r=this.baseURL.getRoot(e),i=e,t=!r||i.startsWith(r)?i:function(...e){return e.filter(Boolean).join("/").replace(/\/+/g,"/").replace(/\/$/,"")}(r,i)),t;var r,i}handleRootSuffix(e,t){return this.baseURL?(""===e&&this.baseURL.getRoot(e).endsWith("/")&&(t+="/"),t):t}handlePrefix(e){return e.startsWith("/")||(e="/"+e),e}relURL(e){if(!e)return this.baseURL?this.baseURL.basePath:"";const[t,r]=this.isAbsURL(e);if(r)return e;if(t||this.isProtocolRelPath(e))return e;if(!this.baseURL)return e;let i=e;if(e.startsWith("/"))return this.baseURL.isRelativeURL()?e:this.baseURL.withoutPath+e;if(i=this.baseURL.isRelativeURL()?(this.baseURL.basePath.endsWith("/")?this.baseURL.basePath:this.baseURL.basePath+"/")+e:(this.baseURL.withPath.endsWith("/")?this.baseURL.withPath:this.baseURL.withPath+"/")+e,i.includes("://")){const e=i.indexOf("://"),t=i.substring(0,e+3),r=i.substring(e+3);i=t+r.replace(/\/+/g,"/")}else i=i.replace(/\/+/g,"/");return i}absURL(e,t=!1,r=""){const[i,s]=this.isAbsURL(e);if(s)return e;if(i||this.isProtocolRelPath(e))return e;if(!this.baseURL)return e;const n=this.baseURL.getRoot(e);if(t&&r){let t=!1,i=e;if(e.startsWith("/")&&(i=e.slice(1)),t=i===r||i.startsWith(r+"/"),!t){const t=""===e||e.endsWith("/");e=this.joinPaths(r,e),t&&(e+="/")}}return function(e,t){const r=`${e.replace(/\/$/,"")}/${t.replace(/^\//,"")}`;try{return new URL(r)}catch{return new URL("http://"+r)}}(n,e).toString()}urlize(e){return this.urlEscape(this.makePathSanitized(e))}makePathSanitized(e){return this.makePath(e).toLowerCase()}urlEscape(t){try{if(/^[a-zA-Z][a-zA-Z\d+\-.]*:/.test(t))return new e(t).toString();const r=t.match(/^([^?#]*)(\?[^#]*)?(#.*)?$/);if(!r)return encodeURI(t);const[,i="",s="",n=""]=r;return encodeURI(i)+(s||"")+(n||"")}catch{return encodeURI(t)}}makePath(e){let t=function(e){return e.replace(/[\s\t\n\r]+/g,"-").replace(/[^\w\-_]/g,"").replace(/-+/g,"-").replace(/^-|-$/g,"")}(e);return t=t.normalize("NFD").replace(/[\u0300-\u036f]/g,""),t}basePathNoSlash(){return this.baseURL?this.baseURL.basePathNoTrailingSlash:""}joinPaths(...e){return e.filter(Boolean).join("/").replace(/\/+/g,"/").replace(/\/$/,"")}}}}),taxonomies_builder_exports={};__export(taxonomies_builder_exports,{OrderedTaxonomy:()=>OrderedTaxonomy,OrderedTaxonomyEntry:()=>OrderedTaxonomyEntry,TaxonomiesBuilder:()=>TaxonomiesBuilder,Taxonomy:()=>Taxonomy3,TaxonomyList:()=>TaxonomyList,WeightedPage:()=>WeightedPage,WeightedPages:()=>WeightedPages});var Menu2,Menus,init_taxonomies_builder=__esm({"internal/domain/site/entity/taxonomies-builder.ts"(){init_log(),log39=getDomainLogger("site",{component:"taxonomies-builder"}),WeightedPage=class{page;ordinalWeightPage;constructor(e,t){this.page=e,this.ordinalWeightPage=t}get Page(){return this.page}weight(){return this.ordinalWeightPage.weight()}ordinal(){return this.ordinalWeightPage.ordinal()}owner(){return this.ordinalWeightPage.owner()}get Permalink(){return this.page.Permalink}get RelPermalink(){return this.page.RelPermalink}get Title(){return this.page.Title}},WeightedPages=class extends Array{page(){return 0===this.length?(log39.error("Page called on empty WeightedPages"),null):this[0]}get Page(){return this.page()}pages(){return Array.from(this)}sortByWeight(){this.stableSort((e,t)=>e.weight()-t.weight())}count(){return this.length}get Count(){return this.count()}stableSort(e){const t=this.map((e,t)=>({item:e,index:t}));t.sort((t,r)=>{const i=e(t.item,r.item);return 0!==i?i:t.index-r.index}),this.splice(0,this.length,...t.map(e=>e.item))}},Taxonomy3=class{terms=new Map;get(e){return this.terms.get(e)}set(e,t){this.terms.set(e,t)}has(e){return this.terms.has(e)}keys(){return Array.from(this.terms.keys())}values(){return Array.from(this.terms.values())}get Values(){return this.terms}entries(){return Array.from(this.terms.entries())}size(){return this.terms.size}byCount(){const e=this.taxonomyArray();return e.sort((e,t)=>{const r=e.weightedPages.length,i=t.weightedPages.length;return r===i?e.name.localeCompare(t.name):i-r}),new OrderedTaxonomy(e)}taxonomyArray(){const e=[];for(const[t,r]of this.terms.entries())e.push(new OrderedTaxonomyEntry(t,r));return e}},OrderedTaxonomyEntry=class{name;weightedPages;constructor(e,t){this.name=e,this.weightedPages=t}count(){return this.weightedPages.count()}term(){return this.name}},OrderedTaxonomy=class extends Array{constructor(e){super(),e&&this.push(...e)}getOneOPage(){return 0===this.length?null:this[0].weightedPages.page()}},TaxonomyList=class{taxonomies=new Map;get(e){return this.taxonomies.get(e)}set(e,t){this.taxonomies.set(e,t)}has(e){return this.taxonomies.has(e)}keys(){return Array.from(this.taxonomies.keys())}values(){return Array.from(this.taxonomies.values())}get Values(){return this.taxonomies}entries(){return Array.from(this.taxonomies.entries())}size(){return this.taxonomies.size}},TaxonomiesBuilder=class{contentService;constructor(e){this.contentService=e}async buildTaxonomiesForLanguage(e,t){const r=new TaxonomyList;try{return await this.contentService.walkTaxonomies(e,async(e,i,s)=>{r.has(e)||r.set(e,new Taxonomy3);const n=r.get(e);n.has(i)||n.set(i,new WeightedPages);const a=await t.siteWeightedPage(s);n.get(i).push(a)}),r}catch(e){throw log39.error(`Failed to create taxonomies: ${e}`),e}}}}});function newEmptyMenus(){return new Menus({})}var init_menu=__esm({"internal/domain/site/valueobject/menu.ts"(){init_log(),getDomainLogger("site",{component:"menu"}),Menu2=class e{_title;_url;_children;_weight;_identifier;constructor(e){this._title=e.title,this._url=e.url,this._children=e.children||[],this._weight=e.weight||0,this._identifier=e.identifier||this._url}title(){return this._title}get Title(){return this.title()}url(){return this._url}get URL(){return this.url()}children(){return[...this._children]}get Children(){return this.children()}weight(){return this._weight}identifier(){return this._identifier}hasChildren(){return this._children.length>0}get HasChildren(){return this.hasChildren()}addChild(t){const r=[...this._children,t];return new e({title:this._title,url:this._url,children:r,weight:this._weight,identifier:this._identifier})}toJSON(){return{title:this._title,url:this._url,weight:this._weight,children:this._children.map(e=>e.toJSON())}}withChildren(t){return new e({title:this._title,url:this._url,children:t,weight:this._weight,identifier:this._identifier})}},Menus=class{_nav;_footer;constructor(e={}){this._nav=e.nav?this.sortMenus([...e.nav]):[],this._footer=e.footer?this.sortMenus([...e.footer]):[]}nav(){return[...this._nav]}get Nav(){return this.nav()}footer(){return[...this._footer]}get Footer(){return this.footer()}sortMenus(e){return e.sort((e,t)=>{if(e.weight()!==t.weight())return 0===t.weight()?-1:0===e.weight()?1:e.weight()-t.weight();const r=e.title().localeCompare(t.title());return 0!==r?r:e.identifier().localeCompare(t.identifier())})}toJSON(){return{nav:this._nav.map(e=>e.toJSON()),footer:this._footer.map(e=>e.toJSON())}}}}});import{slug as slugAnchor}from"github-slugger";function splitAnchor2(e){let[t,r]=e.split("#",2);return t.endsWith(".pdf")?[t,void 0===r?"":`#${r}`]:(r=void 0===r?"":"#"+slugAnchor(r),[t,r])}function simplifySlug(e){const t=stripSlashes2((endsWith2(r=e,"index")&&(r=r.slice(0,-5)),r),!0);var r;return 0===t.length?"/":t}function pathToRoot(e){let t=e.split("/").filter(e=>""!==e).slice(0,-1).map(e=>"..").join("/");return 0===t.length&&(t="."),t}function joinSegments(...e){if(0===e.length)return"";let t=e.filter(e=>""!==e&&"/"!==e).map(e=>stripSlashes2(e)).join("/");return e[0].startsWith("/")&&(t="/"+t),e[e.length-1].endsWith("/")&&(t+="/"),t}function transformLink(e,t,r){let i=function(e){let[t,r]=splitAnchor2(decodeURI(e));const i=isFolderPath(t);let s=t.split("/").filter(e=>e.length>0),n=s.filter(isRelativeSegment).join("/");const a=simplifySlug(function(e){let t=(r=e=stripSlashes2(e),r.match(/\.[A-Za-z0-9]+$/)?.[0]);var r;const i=e.replace(new RegExp(t+"$"),"");[".md",".html",void 0].includes(t)&&(t="");let s=function(e){return e.split("/").map(e=>e.replace(/\s/g,"-").replace(/&/g,"-and-").replace(/%/g,"-percent").replace(/\?/g,"").replace(/#/g,"")).join("/").replace(/\/$/,"")}(i);return endsWith2(s,"_index")&&(s=s.replace(/_index$/,"index")),s+t}(s.filter(e=>!isRelativeSegment(e)&&""!==e).join("/"))),o=i?"/":"";return""===(l=joinSegments(stripSlashes2(n),stripSlashes2(a)))&&(l="."),l.startsWith(".")||(l=joinSegments(".",l)),l+o+r;var l}(t);if("relative"===r.strategy)return i;{const t=isFolderPath(i)?"/":"",s=stripSlashes2(i.slice(1));let[n,a]=splitAnchor2(s);if("shortest"===r.strategy){const t=r.allSlugs.filter(e=>{const t=e.split("/").at(-1);return n.toLowerCase()===t?.toLowerCase()});if(1===t.length)return function(e,t){return joinSegments(pathToRoot(e),simplifySlug(t))}(e,t[0])+a}return joinSegments(pathToRoot(e),s)+t}}function isFolderPath(e){return e.endsWith("/")||endsWith2(e,"index")||endsWith2(e,"index.md")||endsWith2(e,"index.html")}function endsWith2(e,t){return e===t||e.endsWith("/"+t)}function isRelativeSegment(e){return/^\.{0,2}$/.test(e)}function stripSlashes2(e,t){return e.startsWith("/")&&(e=e.substring(1)),!t&&e.endsWith("/")&&(e=e.slice(0,-1)),e}var log41,PageGraph,log42,defaultOptions,HtmlLinkProcessor,init_path3=__esm({"internal/domain/site/valueobject/path.ts"(){}}),init_pagegraph=__esm({"internal/domain/site/entity/pagegraph.ts"(){init_path3(),init_log(),log41=getDomainLogger("site",{component:"PageGraph"}),PageGraph=class{allSlugs;outgoingLinks=new Map;constructor(e){this.allSlugs=[...e],log41.info(`PageGraph initialized with ${e.length} items (pages + resources)`)}registerOutgoingLinks(e,t){const r=simplifySlug(e);this.outgoingLinks.set(r,t)}getBacklinks(e){const t=simplifySlug(e),r=[];for(const[e,i]of this.outgoingLinks.entries())i.includes(t)&&r.push(e);return r}getAllSlugs(){return[...this.allSlugs]}hasSlug(e){return this.allSlugs.includes(e)}resolveLink(e,t,r){return transformLink(e,t,{strategy:r,allSlugs:this.allSlugs})}getOutgoingLinks(e){const t=simplifySlug(e);return this.outgoingLinks.get(t)||[]}getAllOutgoingLinks(){return new Map(this.outgoingLinks)}getStats(){return{totalPages:this.allSlugs.length,slugs:[...this.allSlugs]}}}}});import{unified}from"unified";import rehypeParse from"rehype-parse";import rehypeStringify from"rehype-stringify";import{visit}from"unist-util-visit";import isAbsoluteUrl from"is-absolute-url";import path22 from"path";var log43,pageFilter,init_html_link_processor=__esm({"internal/domain/site/service/html-link-processor.ts"(){init_path3(),init_log(),log42=getDomainLogger("site",{component:"HtmlLinkProcessor"}),defaultOptions={markdownLinkResolution:"shortest",prettyLinks:!0,openLinksInNewTab:!1,lazyLoad:!1,externalLinkIcon:!0},HtmlLinkProcessor=class{constructor(e,t={}){this.graph=e,this.options={...defaultOptions,...t}}options;async processLinks(e,t){if(!t||"string"!=typeof t)return log42.error("[HtmlLinkProcessor] Invalid HTML input: "+typeof t),{html:t||"",outgoingLinks:[]};const r=this.options,i=simplifySlug(e),s=new Set,n=unified().use(rehypeParse,{fragment:!0}).use(()=>t=>{visit(t,"element",t=>{if("a"===t.tagName&&t.properties){const n=t.properties.dataWikilink||t.properties.dataSlug,a="string"==typeof t.properties.href;if(!a&&!n)return;let o;o=!a&&n?t.properties.dataWikilink||t.properties.dataSlug:t.properties.href;const l=t.properties.className??[],c=isAbsoluteUrl(o,{httpOnly:!1});l.includes("external")||l.includes("internal")||l.push(c?"external":"internal"),c&&r.externalLinkIcon&&t.children.push({type:"element",tagName:"svg",properties:{"aria-hidden":"true",class:"external-icon",style:"max-width:0.8em;max-height:0.8em",viewBox:"0 0 512 512"},children:[{type:"element",tagName:"path",properties:{d:"M320 0H288V64h32 82.7L201.4 265.4 178.7 288 224 333.3l22.6-22.6L448 109.3V192v32h64V192 32 0H480 320zM32 32H0V64 480v32H32 456h32V480 352 320H424v32 96H64V96h96 32V32H160 32z"},children:[]}]}),1===t.children.length&&"text"===t.children[0].type&&t.children[0].value!==o&&l.push("alias"),t.properties.className=l,c&&r.openLinksInNewTab&&(t.properties.target="_blank");const h=!(isAbsoluteUrl(o,{httpOnly:!1})||o.startsWith("#"));if(h){const n=transformLink(e,o,{strategy:r.markdownLinkResolution,allSlugs:this.graph.getAllSlugs()}),a=new URL(n,"https://base.com/"+stripSlashes2(i,!0)).pathname;let[l,c]=splitAnchor2(a);l.endsWith("/")&&(l+="index");const h=decodeURIComponent(stripSlashes2(l,!0)),u=simplifySlug(h);s.add(u);let g=n;if(g.startsWith("./")&&(g=g.slice(2)),g.startsWith("../")){const t=(g.match(/\.\.\//g)||[]).length,r=e.split("/").filter(e=>e).slice(0,-1),i=g.replace(/\.\.\//g,""),s=r.slice(0,r.length-t);i&&s.push(i),g=s.join("/")}g=r.baseURL?`${r.baseURL}/${g}`:`/${g}`;const[d,p]=splitAnchor2(g);let m=d;m.endsWith(".html")||m.endsWith("/")||(m+=".html"),g=m+p,o=t.properties.href=g,t.properties["data-slug"]=h}r.prettyLinks&&h&&1===t.children.length&&"text"===t.children[0].type&&!t.children[0].value.startsWith("#")&&(t.children[0].value=path22.basename(t.children[0].value))}if(["img","video","audio","iframe"].includes(t.tagName)&&t.properties&&"string"==typeof t.properties.src&&(r.lazyLoad&&(t.properties.loading="lazy"),!isAbsoluteUrl(t.properties.src,{httpOnly:!1}))){let i=t.properties.src;i=t.properties.src=transformLink(e,i,{strategy:r.markdownLinkResolution,allSlugs:this.graph.getAllSlugs()}),t.properties.src=i}})}).use(rehypeStringify),a=await n.process(t);return{html:String(a),outgoingLinks:Array.from(s)}}}}});function shouldProcessPage(e,t){return pageFilter.shouldProcess(e,t)}var log44,Site,Publisher,MultiWriter,init_page_filter=__esm({"pkg/page-filter/index.ts"(){init_log(),log43=getDomainLogger("pkg",{component:"page-filter"}),pageFilter=new class{filterSet=null;currentLanguage=null;setFilter(e){this.filterSet=new Set;for(const t of e){const e=`${t.language}:${t.pagePath}`;this.filterSet.add(e)}log43.debug(`Page filter set: ${e.length} tasks`)}setCurrentLanguage(e){this.currentLanguage=e}clearFilter(){this.filterSet=null,this.currentLanguage=null,log43.debug("Page filter cleared")}shouldProcess(e,t){if(!this.filterSet)return!0;const r=`${e}:${t}`;return this.filterSet.has(r)}getFilterSize(){return this.filterSet?.size??0}}}}),init_site=__esm({"internal/domain/site/entity/site.ts"(){init_page2(),init_url(),init_log(),init_taxonomies_builder(),init_menu(),init_pagegraph(),init_html_link_processor(),init_page_filter(),log44=getDomainLogger("site",{component:"site"}),Site=class{configSvc;contentSvc;translationSvc;languageSvc;sitemap;staticCopySvc;publisher;template=null;author;organization;compiler;url;ref=null;language;navigation=null;title;home=null;pageGraph=null;backlinksCache=null;get Title(){return this.title}get Description(){return this.home?.description()||""}get Compiler(){return this.compiler}get IsGoogleAnalyticsEnabled(){return this.configSvc.isGoogleAnalyticsEnabled()}get GoogleAnalyticsID(){return this.configSvc.googleAnalyticsID()}get IsGoogleAnalyticsRespectDoNotTrack(){return this.configSvc.isGoogleAnalyticsRespectDoNotTrack()}get IsDisqusEnabled(){return this.configSvc.isDisqusEnabled()}get DisqusShortname(){return this.configSvc.disqusShortname()}get IsXRespectDoNotTrack(){return this.configSvc.isXRespectDoNotTrack()}get IsXDisableInlineCSS(){return this.configSvc.isXDisableInlineCSS()}get ConfiguredSocialPlatforms(){return this.configSvc.getConfiguredSocialPlatforms()}GetSocialLink(e){return this.configSvc.getSocialLink(e)}GetSocialTitle(e){return this.configSvc.getSocialTitle(e)}async Pages(){const e=this.languageSvc.getLanguageIndex(this.language.getCurrentLanguage()),t=await this.contentSvc.globalPages(e);return this.sitePages(t)}async RegularPages(){const e=await this.contentSvc.globalRegularPages();return this.sitePages(e)}constructor(e,t,r,i,s,n,a,o,l,c,h,u,g,d,p){this.configSvc=e,this.contentSvc=t,this.translationSvc=r,this.languageSvc=i,this.sitemap=s,this.staticCopySvc=n,this.publisher=a,this.author=o,this.organization=l,this.compiler=c,this.url=h,this.ref=u,this.language=g,this.navigation=d,this.title=p}async build(e){try{this.template=e,await this.setup(),await this.copyStaticFiles();const t=this.languageSvc.languageKeys();for(const e of t)this.language.setCurrentLanguage(e),await this.generateNavigations(),await this.render()}catch(e){const t=e instanceof Error?e.message:String(e);throw log44.error(`❌ Site build failed: ${t}`),e}}async renderAllLanguages(){const e=this.languageSvc.languageKeys();for(const t of e)this.language.setCurrentLanguage(t),await this.generateNavigations(),await this.render()}async buildWithProgress(e,t){try{this.template=e,await this.setup(),await this.copyStaticFiles();const r=this.languageSvc.languageKeys();for(const e of r)this.language.setCurrentLanguage(e),await this.generateNavigations(),await this.renderWithProgress(t)}catch(e){const t=e instanceof Error?e.message:String(e);throw log44.error(`❌ Site build failed: ${t}`),e}}async setup(){try{await this.buildPageGraph()}catch(e){const t=e instanceof Error?e.message:String(e);throw log44.error(`❌ Setup failed: ${t}`),e}}async render(){try{await this.renderPages()}catch(e){throw e}}async renderWithProgress(e){try{await this.renderPagesWithProgress(e)}catch(e){throw e}}async renderPages(){const e=this.language.getCurrentLanguage(),t=this.languageSvc.getLanguageIndex(e),r=[];await this.contentSvc.walkPages(t,async e=>{const t=await this.sitePage(e);r.push(t);const i=await this.contentSvc.getPageSources(e);await t.processResources(i),e.isHome()&&(this.home=t)}),log44.info(`📊 Processing wikilinks for ${r.length} pages...`);for(const e of r)try{await e.WikilinkContent()}catch(t){const r=t instanceof Error?t.message:String(t);log44.warn(`⚠️ Failed to process wikilinks for ${e.slug()}: ${r}`)}log44.info("✅ Wikilink processing complete");const i=r.filter(t=>{const r=t.file().paths().base();return!!shouldProcessPage(e,r)&&t.isStale()}),s=i.filter(e=>e.isHome()),n=i.filter(e=>!e.isHome());log44.info(`📄 Rendering ${s.length} home page(s) first...`);for(const e of s)await e.render(),e.clearStale();log44.info(`✅ Home page(s) rendered, now rendering ${n.length} other pages in parallel...`);for(let e=0;e<n.length;e+=10){const t=n.slice(e,e+10);await Promise.all(t.map(async e=>{try{await e.render(),e.clearStale()}catch(t){const r=t instanceof Error?t.message:String(t);log44.error(`❌ Failed to render page ${e.slug()}: ${r}`)}}))}}async renderPagesWithProgress(e){const t=this.language.getCurrentLanguage(),r=this.languageSvc.getLanguageIndex(t),i=[];await this.contentSvc.walkPages(r,async e=>{const t=await this.sitePage(e);i.push(t);const r=await this.contentSvc.getPageSources(e);await t.processResources(r),e.isHome()&&(this.home=t)}),log44.info(`📊 Processing wikilinks for ${i.length} pages...`);for(const e of i)try{await e.WikilinkContent()}catch(t){const r=t instanceof Error?t.message:String(t);log44.warn(`⚠️ Failed to process wikilinks for ${e.slug()}: ${r}`)}log44.info("✅ Wikilink processing complete");const s=i.filter(e=>{const r=e.file().paths().base();return!!shouldProcessPage(t,r)&&e.isStale()}),n=s.filter(e=>e.isHome()),a=s.filter(e=>!e.isHome()),o=i.length;let l=0;log44.info(`📄 Rendering ${n.length} home page(s) first...`);for(const t of n)await t.render(),l++,e?.({currentPage:l,totalPages:o});log44.info(`✅ Home page(s) rendered, now rendering ${a.length} other pages in parallel...`);for(let t=0;t<a.length;t+=10){const r=a.slice(t,t+10);await Promise.all(r.map(async e=>{try{await e.render()}catch(t){const r=t instanceof Error?t.message:String(t);log44.error(`❌ Failed to render page ${e.slug()}: ${r}`)}})),l+=r.length,e?.({currentPage:l,totalPages:o})}log44.info("✅ All pages rendered successfully")}async pageOutput(e){return e.output()}clearSiteCache(){}translate(e){return this.translationSvc.translate(this.language.getCurrentLanguage(),e)}get Home(){return this.home}get Params(){return this.configSvc.configParams()}get Taxonomies(){return this.navigation&&this.navigation.getTaxonomies(this.language.getCurrentLanguage())||new TaxonomyList}get Menus(){return this.navigation?this.navigation.getMenus(this.language.getCurrentLanguage()):new Menus}getTitle(){return this.title}setTitle(e){this.title=e}getConfigService(){return this.configSvc}getContentService(){return this.contentSvc}getLanguageService(){return this.languageSvc}baseURL(){return this.url.base}get BaseURL(){return this.baseURL()}getURL(){return this.url}getRef(){return this.ref?this.ref:{}}getLanguage(){return this.language}get Language(){return this.getLanguage()}get LanguageCode(){return this.language.lang()}get Languages(){return this.language.languages()}getNavigation(){return this.navigation?this.navigation:{}}getPublisher(){return this.publisher}getTemplate(){return this.template}get Author(){return this.author.author(this.home?.author())}get Organization(){return this.organization.organization(this.home?.organization())}getCompiler(){return this.compiler}getSitemap(){return this.sitemap}isMultipleLanguage(){return this.language.isMultipleLanguage()}get IsMultilingual(){return this.isMultipleLanguage()}getCurrentLanguage(){return this.language.lang()}languagePrefix(){return this.language.languagePrefix()}async sitePage(e){return new Page2(this.template,this.languageSvc,this.publisher,e,this)}sitePages(e){const t=[];for(let r=0;r<e.length;r++){const i=e[r];try{const e=this.sitePageSync(i);t.push(e)}catch(e){log44.error(`❌ [Site.sitePages] Failed to convert page ${r}:`,e)}}return t}sitePageSync(e){return new Page2(this.template,this.languageSvc,this.publisher,e,this)}async generateNavigations(){const e=this.language.getCurrentLanguage(),t=this.languageSvc.getLanguageIndex(e);this.navigation&&(await this.navigation.generateMenusForLanguage(e,t),await this.navigation.generateTaxonomiesForLanguage(e,t,this))}GetPage(...e){if(e.length>1)throw new Error(`too many arguments to .Site.GetPage: ${e}. Use lookups on the form {{ .Site.GetPage "/posts/mypage-md" }}`);let t=e[0];t=t.replace(/\\/g,"/"),t.startsWith("/")||(t="/"+t);try{const e=this.languageSvc.getLanguageIndex(this.language.getCurrentLanguage()),r=this.contentSvc.getPageFromPathSync(e,t);return r?this.sitePageSync(r):(log44.warn(`⚠️ GetPage: No page found for key "${t}"`),null)}catch(e){return log44.error(`❌ Error getting page "${t}": ${e}`),null}}async copyStaticFiles(){try{await this.staticCopySvc.copyStaticFiles(this.staticCopySvc.staticFs(),this.staticCopySvc.publishFs())}catch(e){throw log44.error("❌ Static file copy failed:",e),e}}async siteWeightedPage(e){const t=await this.sitePage(e.page()),{WeightedPage:r}=await Promise.resolve().then(()=>(init_taxonomies_builder(),taxonomies_builder_exports));return new r(t,e)}async buildPageGraph(){if(!this.pageGraph)try{const e=[],t=this.languageSvc.languageKeys();for(const r of t){const t=this.languageSvc.getLanguageIndex(r);await this.contentSvc.walkPages(t,async t=>{e.push(t)})}const r=e.map(e=>e.slug());log44.info(`📄 Collected ${r.length} page slugs`);const i=await this.collectResourceSlugs(e);log44.info(`🖼️ Collected ${i.length} resource slugs`);const s=[...r,...i];this.pageGraph=new PageGraph(s),log44.info(`✅ PageGraph built: ${r.length} pages + ${i.length} resources = ${s.length} total`),this.buildBacklinksCache(e)}catch(e){const t=e instanceof Error?e.message:String(e);throw log44.error(`❌ Failed to build PageGraph: ${t}`),e}}async collectResourceSlugs(e){const t=[],r=new Set;try{for(const i of e)try{const e=await this.contentSvc.getPageSources(i);for(const i of e){const e=i.slug();r.has(e)||(r.add(e),t.push(e))}}catch(e){const t=e instanceof Error?e.message:String(e);log44.error(`⚠️ Failed to get resources for page ${i.slug()}: ${t}`)}}catch(e){const t=e instanceof Error?e.message:String(e);log44.warn(`⚠️ Failed to collect resource slugs: ${t}`)}return t}async ProcessWikilinks(e,t){if(!this.pageGraph)return log44.warn("⚠️ PageGraph not built yet, returning original HTML"),t;try{let i="";if(this.url&&this.url.base){if(i=this.url.base.replace(/\/$/,""),i.startsWith("/"));else if(i)try{i=new URL2(i).pathname.replace(/\/$/,"")}catch(e){log44.warn(`Failed to parse baseURL as URL: ${i}, treating as path`)}"/"===i&&(i="")}const s=(r=this.pageGraph,new HtmlLinkProcessor(r,{markdownLinkResolution:"shortest",prettyLinks:!0,openLinksInNewTab:!1,lazyLoad:!0,externalLinkIcon:!0,baseURL:i})),n=await s.processLinks(e,t);return this.pageGraph.registerOutgoingLinks(e,n.outgoingLinks),n.html}catch(r){const i=r instanceof Error?r.message:String(r);return log44.error(`❌ Failed to process wikilinks for ${e}: ${i}`),t}var r}getPageGraph(){return this.pageGraph}GetBacklinks(e){if(this.backlinksCache&&this.backlinksCache.has(e))return this.backlinksCache.get(e);if(!this.pageGraph)return log44.warn(`⚠️ PageGraph not built yet, cannot get backlinks for ${e}`),[];const t=this.pageGraph.getBacklinks(e);return this.backlinksCache&&this.backlinksCache.set(e,t),t}async buildBacklinksCache(e){this.pageGraph?this.backlinksCache=new Map:log44.warn("⚠️ PageGraph not built, skipping backlinks cache")}async GetContentIndex(){if(!this.pageGraph)return log44.warn("⚠️ PageGraph not built yet, cannot generate content index"),new Map;const e=new Map,t=await this.RegularPages();for(const r of t){const t=r.slug(),i=this.pageGraph.getOutgoingLinks(t),s=(r.Plain||"").substring(0,1e3);e.set(t,{slug:t,title:r.Title||r.File.OriginalBaseName,links:i,tags:r.Params?.tags||[],content:s})}return e}}}});import path23 from"path";async function openFileForWriting(e,t){const r=path23.normalize(t);try{return await e.create(r)}catch(t){if(!function(e){return e&&("ENOENT"===e.code||"FILE_NOT_FOUND"===e.code||e.message?.includes("not found")||e.message?.includes("no such file"))}(t))throw t;const i=path23.dirname(r);return await e.mkdirAll(i,511),await e.create(r)}}var log46,Ref,CollatorWrapper,Language2,Author2,Organization2,Compiler,log49,Navigation,log50,MenuBuilder,log51,NavigationFactory,init_publisher=__esm({"internal/domain/site/entity/publisher.ts"(){init_log(),getDomainLogger("site",{component:"publisher"}),Publisher=class{fs;constructor(e){this.fs=e}async publishSource(e,...t){const r=await this.openFilesForWriting(...t);try{const t="string"==typeof e?(new TextEncoder).encode(e):e;await this.copyToWriter(r,t)}finally{await r.close()}}async publishFiles(e,...t){const r=await this.openFilesForWriting(...t);try{await this.copyStreamToWriter(r,e)}finally{await r.close()}}async openFilesForWriting(...e){const t=[];for(const r of e){const e=await openFileForWriting(this.fs,r);t.push(e)}return new MultiWriter(t)}async copyToWriter(e,t){await e.write(t)}async copyStreamToWriter(e,t){const r=t.getReader();try{for(;;){const{done:t,value:i}=await r.read();if(t)break;await e.write(i)}}finally{r.releaseLock()}}},MultiWriter=class{files;constructor(e){this.files=e}async write(e){const t=this.files.map(t=>t.write(e));await Promise.all(t)}async close(){const e=this.files.map(e=>e.close());await Promise.all(e)}}}}),init_ref=__esm({"internal/domain/site/entity/ref.ts"(){init_log(),log46=getDomainLogger("site",{component:"ref"}),Ref=class{site;contentSvc;notFoundURL;constructor(e,t,r="#ZgotmplZ"){this.site=e,this.contentSvc=t,this.notFoundURL=r}async relRefFrom(e,t){return this.relRef(e,t)}async relRef(e,t){try{const r=this.decodeRefArgs(e);return r.path?this.refLink(r.path,t,!0,r.outputFormat):""}catch(e){throw new Error(`Invalid arguments to Ref: ${e}`)}}decodeRefArgs(e){return{path:e.path||"",outputFormat:e.outputFormat||""}}async refLink(e,t,r,i){const s=t;if(!s||"function"!=typeof s.unwrapPage)throw new Error("source is not a PageWrapper");const n=s.unwrapPage();let a;const o=e.replace(/\\/g,"/");try{a=new globalThis.URL(o,"http://example.com")}catch(e){return log46.error(`Failed to parse ref URL: ${e}`),this.notFoundURL}let l=null,c="";if(""!==a.pathname)try{l=await this.contentSvc.getPageRef(n,a.pathname,this.site.home.page);let e=null;if(l||this.isPositioner(t)&&(e=t.position()),!l)return this.logNotFound(a.pathname,"page not found",n,e),this.notFoundURL;const i=await this.site.sitePage(l);c=r?i.relPermalink():i.permalink()}catch(t){return log46.error(`[${n.pageIdentity().pageLanguage()}] REF_NOT_FOUND: Ref "${e}": ${t}`),this.notFoundURL}return a.hash&&(c=c+"#"+a.hash),c}isPositioner(e){return e&&"function"==typeof e.position}logNotFound(e,t,r,i){const s=r.pageIdentity().pageLanguage();i&&i.isValid()?log46.error(`[${s}] REF_NOT_FOUND: Ref "${e}": ${i.toString()}: ${t}`):r?log46.error(`[${s}] REF_NOT_FOUND: Ref "${e}" from page "${r.path()}": ${t}`):log46.error(`[${s}] REF_NOT_FOUND: Ref "${e}": ${t}`)}}}}),init_language3=__esm({"internal/domain/site/entity/language.ts"(){init_log(),getDomainLogger("site",{component:"language"}),CollatorWrapper=class{collator;constructor(e){this.collator=e}compare(e,t){return this.collator.compare(e,t)}},Language2=class e{langSvc;currentLocation;currentLanguage;collator=null;constructor(e){this.langSvc=e,this.currentLocation="UTC",this.currentLanguage=""}currentLanguageIndex(){try{return this.langSvc.getLanguageIndex(this.currentLanguage)}catch(e){throw new Error(`language "${this.currentLanguage}" not found`)}}async setup(){this.currentLocation="UTC"}languages(){const t=[];for(const r of this.langSvc.languageKeys()){const i=new e(this.langSvc);i.currentLocation=this.currentLocation,i.currentLanguage=r,i.collator=this.collator,t.push(i)}return t}getCollator(){if(!this.collator)try{const e=new Intl.Collator(this.currentLanguage||"en");this.collator=new CollatorWrapper({compare:(t,r)=>e.compare(t,r)})}catch(e){const t=new Intl.Collator("en");this.collator=new CollatorWrapper({compare:(e,r)=>t.compare(e,r)})}return this.collator}location(){return this.currentLocation}isMultipleLanguage(){return this.langSvc.languageKeys().length>1}languagePrefix(){return this.currentLanguage===this.langSvc.defaultLanguage()?"":this.currentLanguage}lang(){return this.currentLanguage}get Lang(){return this.lang()}languageName(){return this.langSvc.getLanguageName(this.currentLanguage)}get LanguageName(){return this.languageName()}defaultLanguageName(){return this.langSvc.getLanguageName(this.langSvc.defaultLanguage())}languageCode(){return this.currentLanguage}get LanguageCode(){return this.languageCode()}get LanguageDirection(){return"ltr"}languageDirection(){return"ltr"}setCurrentLanguage(e){this.currentLanguage=e}getCurrentLanguage(){return this.currentLanguage}setCurrentLocation(e){this.currentLocation=e}}}}),init_author=__esm({"internal/domain/site/valueobject/author.ts"(){Author2=class{_name;_email;_homeAuthor;constructor(e,t){this._name=e,this._email=t}name(){return this._name}email(){return this._email}author(e){return this._homeAuthor=e,this}get Name(){return this._homeAuthor?.name||this.name()}get Description(){return this._homeAuthor?.description||""}get Avatar(){return this._homeAuthor?.avatar||""}get Twitter(){return this._homeAuthor?.social?.twitter||""}get Socials(){const e=[];if(!this._homeAuthor?.social)return e;for(const[t,r]of Object.entries(this._homeAuthor.social))r&&e.push({ID:t,Link:r});return e}}}}),init_organization=__esm({"internal/domain/site/valueobject/organization.ts"(){init_log(),getDomainLogger("site",{component:"organization"}),Organization2=class{_name;_description;_website;_logo;_email;_address;_vision;_homeOrganization;constructor(){this._name="MDFriday",this._description="Turn markdown to website, in minutes.",this._website="https://mdfriday.com",this._logo="https://gohugo.net/mdfriday.svg",this._email="support@mdfriday.com",this._address="Cang long Street, Wuhan, China",this._vision="Make site generation easy and accessible for everyone."}name(){return this._name}description(){return this._description}website(){return this._website}organization(e){return this._homeOrganization=e,this}get Name(){return this._homeOrganization?.name||this.name()}get Description(){return this._homeOrganization?.description||this.description()}get Website(){return this._homeOrganization?.website||this.website()}get Vision(){return this._homeOrganization?.vision||this._vision}get Logo(){return this._homeOrganization?.logo||this._logo}get Address(){return this._homeOrganization?.contact?.address||this._address}get Email(){return this._homeOrganization?.contact?.email||this._email}get Social(){return this._homeOrganization?.social}SocialById(e){return this._homeOrganization?.social?.[e]||""}get Socials(){const e=[];if(!this._homeOrganization?.social)return e;for(const[t,r]of Object.entries(this._homeOrganization.social))r&&e.push({ID:t,Link:r});return e}}}}),init_version=__esm({"internal/domain/site/valueobject/version.ts"(){Compiler=class{ver;constructor(e){this.ver=e}version(){return this.ver}environment(){return"production"}}}}),init_navigation=__esm({"internal/domain/site/entity/navigation.ts"(){init_log(),init_menu(),log49=getDomainLogger("site",{component:"navigation"}),Navigation=class{taxonomies;taxonomiesBuilder=null;taxonomiesCache=new Map;menus;menuBuilder=null;menuCache=new Map;constructor(e){this.taxonomies=new Map,this.menus=new Map;for(const t of e.languageKeys())this.menus.set(t,newEmptyMenus()),this.menuCache.set(t,!1)}setMenuBuilder(e){this.menuBuilder=e}setTaxonomiesBuilder(e){this.taxonomiesBuilder=e}async generateMenusForLanguage(e,t){if(this.menuBuilder){if(!0!==this.menuCache.get(e))try{const r=await this.menuBuilder.buildMenusForLanguage(t);this.menus.set(e,r),this.menuCache.set(e,!0)}catch(t){log49.error(`Failed to generate menus for language ${e}: ${t}`)}}else log49.error("Menu builder not set, cannot generate menus")}async generateTaxonomiesForLanguage(e,t,r){if(this.taxonomiesBuilder){if(!0!==this.taxonomiesCache.get(e))try{const i=await this.taxonomiesBuilder.buildTaxonomiesForLanguage(t,r);this.taxonomies.set(e,i),this.taxonomiesCache.set(e,!0)}catch(t){log49.error(`Failed to generate taxonomies for language ${e}: ${t}`)}}else log49.error("Taxonomies builder not set, cannot generate taxonomies")}getMenus(e){let t=this.menus.get(e);return void 0===t&&(t=newEmptyMenus()),t}getTaxonomies(e){return this.taxonomies.get(e)}}}}),init_menu_builder=__esm({"internal/domain/site/entity/menu-builder.ts"(){init_log(),init_menu(),log50=getDomainLogger("site",{component:"menu-builder"}),MenuBuilder=class{contentService;site;constructor(e,t){this.contentService=e,this.site=t}async buildMenusForLanguage(e){const t=new Map;return await this.contentService.walkPages(e,async e=>{await this.processPage(e,t)}),this.convertToMenus(t)}async processPage(e,t){try{const r=e.menu();if(!r)return;const i=await this.generatePageUrl(e);for(const[s,n]of Object.entries(r))await this.processMenuSection(s,n,i,e,t)}catch(e){log50.error(`Error processing page for menu: ${e}`)}}async processMenuSection(e,t,r,i,s){if(!(!1===t||Array.isArray(t)&&0===t.length))if(Array.isArray(t))await this.processMenuItems(e,t,r,i,s);else if(t&&"object"==typeof t){let n=0;for(const[a,o]of Object.entries(t))if(!(!1===o||Array.isArray(o)&&0===o.length)&&Array.isArray(o)){const t=`${e}.${a}`;if(await this.processMenuItems(t,o,r,i,s),"footer"===e){const e=`${t}::__subsection__`;s.has(e)||s.set(e,{title:a,url:"",children:new Map,weight:1e3,level:0,menuName:t,order:n})}n++}}}async processMenuItems(e,t,r,i,s){for(let n=0;n<t.length;n++){const a=t[n];if(!a||"object"!=typeof a)continue;if(!a.title||"string"!=typeof a.title)continue;let o=a.url||"";o=""===o?r:await this.processMenuItemUrl(o);const l="number"==typeof a.weight?a.weight:1e3,c=`${e}::${a.title}`;let h=s.get(c);h?l<h.weight&&(h.weight=l,h.url=o):(h={title:a.title,url:o,children:new Map,weight:l,level:0,menuName:e||void 0,order:n},s.set(c,h)),Array.isArray(a.children)&&await this.processChildrenItems(c,a.children,r,i,s,h)}}async processChildrenItems(e,t,r,i,s,n){for(let a=0;a<t.length;a++){const o=t[a];if(!o||"object"!=typeof o)continue;if(!o.title||"string"!=typeof o.title)continue;let l=o.url||"";l=""===l?r:await this.processMenuItemUrl(l);const c="number"==typeof o.weight?o.weight:1e3,h=`${e}::${o.title}`,u={title:o.title,url:l,children:new Map,weight:c,level:n.level+1,menuName:n.menuName||void 0,order:a};s.set(h,u),n.children.set(h,u),Array.isArray(o.children)&&await this.processChildrenItems(h,o.children,r,i,s,u)}}async generatePageUrl(e){try{return(await this.site.sitePage(e)).RelPermalink}catch(t){return log50.error(`Error generating page URL for ${e.path()}: ${t}`),this.fallbackUrlFromPath(e.path())}}async processMenuItemUrl(e){try{return this.site.getURL().relURL(e)}catch(t){return log50.error(`Error processing menu item URL ${e}: ${t}`),e}}fallbackUrlFromPath(e){let t=e.replace(/\.md$/,"");return t.startsWith("/")||(t="/"+t),t.endsWith("/")||t.includes(".")||(t+="/"),t}convertToMenus(e){const t=new Map;for(const[r,i]of e.entries())if(!r.includes("::__subsection__")&&0===i.level){const e=i.menuName||"main";t.has(e)||t.set(e,[]),t.get(e).push(i)}const r=this.buildMenuItems(t.get("nav")||[],e),i=[],s=new Map,n=new Map;for(const[r,i]of t.entries())if(r.startsWith("footer.")){const t=r.substring(7),a=this.buildMenuItems(i,e,!1);s.set(t,a);const o=`${r}::__subsection__`,l=e.get(o);l&&n.set(t,l.order)}const a=Array.from(s.entries()).sort((e,t)=>(n.get(e[0])||0)-(n.get(t[0])||0));for(let e=0;e<a.length;e++){const[t,r]=a[e];if(r.length>0){const s=new Menu2({title:this.capitalizeFirstLetter(t),url:"",children:r,weight:e+1,identifier:`footer-${t}`});i.push(s)}}const o={};return r.length>0&&(o.nav=r),i.length>0&&(o.footer=i),new Menus(o)}capitalizeFirstLetter(e){return e.charAt(0).toUpperCase()+e.slice(1)}buildMenuItems(e,t,r=!0){const i=[];for(const s of e){const e=Array.from(s.children.values()),n=e.length>0?this.buildMenuItems(e,t,r):[],a=new Menu2({title:s.title,url:s.url,children:n,weight:s.weight,identifier:s.url});i.push(a)}return r?i.sort((e,t)=>e.weight()!==t.weight()?e.weight()-t.weight():e.title().localeCompare(t.title())):i.sort((t,r)=>{const i=e.find(e=>e.title===t.title()),s=e.find(e=>e.title===r.title());return(i?.order||0)-(s?.order||0)})}}}}),init_navigation_factory=__esm({"internal/domain/site/factory/navigation-factory.ts"(){init_navigation(),init_menu_builder(),init_taxonomies_builder(),init_log(),log51=getDomainLogger("site",{component:"navigation-factory"}),NavigationFactory=class{langService;contentService;site;constructor(e,t,r){this.langService=e,this.contentService=t,this.site=r}createNavigation(){try{const t=(e=this.langService,new Navigation(e)),r=new MenuBuilder(this.contentService,this.site);t.setMenuBuilder(r);const i=new TaxonomiesBuilder(this.contentService);return t.setTaxonomiesBuilder(i),t}catch(e){throw log51.error(`Failed to create Navigation entity: ${e}`),e}var e}}}});var log53,ResourceHash,PublishOnce,ResourceImpl,init_site2=__esm({"internal/domain/site/factory/site.ts"(){init_site(),init_publisher(),init_url(),init_ref(),init_language3(),init_author(),init_organization(),init_version(),init_navigation_factory(),init_log(),getDomainLogger("site",{component:"factory"})}}),init_type9=__esm({"internal/domain/resources/type.ts"(){}});import{createHash as createHash3}from"crypto";import{PassThrough}from"stream";import{pipeline}from"stream/promises";import{Readable}from"stream";var MinifierClient,MinifyTransformation,init_resource=__esm({"internal/domain/resources/entity/resource.ts"(){init_resources2(),init_paths(),init_log(),log53=getDomainLogger("resources",{component:"publisher"}),ResourceHash=class{value="";size=0;resource=null;async setup(e){if(this.value)return;this.resource=e;const t=await e.readSeekCloser(),r=createHash3("sha256");let i=0;const s=[];t.on("data",e=>{r.update(e),i+=e.length,s.push(e)}),await new Promise((e,s)=>{t.on("end",()=>{this.value=r.digest("hex"),this.size=i,e()}),t.on("error",s)}),await t.close()}},PublishOnce=class{hasPublished=!1;publishPromise=null;async do(e){if(!this.hasPublished)return this.publishPromise||(this.publishPromise=e().then(()=>{this.hasPublished=!0})),this.publishPromise}},ResourceImpl=class e{h;openReadSeekCloser;_mediaType;paths;_data;publisher;publishOnce;constructor(e,t,r,i={},s){this.h=new ResourceHash,this.openReadSeekCloser=e,this._mediaType=t,this.paths=r,this._data=i,this.publisher=s,this.publishOnce=new PublishOnce}name(){return this.paths.pathFile()}nameNormalized(){return this.paths.targetPath().replace(/\\/g,"/")}mediaType(){return this._mediaType}resourceType(){return this._mediaType.mainType}relPermalink(){return this.publish(),this.paths.targetLink()}permalink(){return this.publish(),this.paths.targetPath()}async publish(){const e=this.targetPath();this.publisher?await this.publishOnce.do(async()=>{let t=null,r=null;try{t=await this.publisher.openPublishFileForWriting(this.paths.targetPath()),r=await this.readSeekCloser(),await this.copyStreamToFile(r,t)}catch(t){throw log53.errorf("❌ [Resource.publish] Error publishing %s: %s",e,t),t}finally{if(r)try{await r.close()}catch(t){log53.errorf("❌ [Resource.publish] Failed to close ReadSeekCloser %s: %s",e,t)}if(t)try{await t.file.close()}catch(t){log53.errorf("❌ [Resource.publish] Failed to close public writer %s: %s",e,t)}}}):log53.error("⚠️ [Resource.publish] No publisher for: %s",e)}async copyStreamToFile(e,t){const r=this.targetPath();try{await pipeline(e,t)}catch(e){throw log53.errorf("❌ [copyStreamToFile] Error during pipeline for %s: %s",r,e),e}}targetPath(){return this.paths.targetPath()}data(){return this._data}async readSeekCloser(){const e=await this.openReadSeekCloser();if(e&&"function"==typeof e.read){const t=e.read();if(t){const r=new Readable;let i;for(r.push(t);null!==(i=e.read());)i&&r.push(i);return r.push(null),Object.assign(r,{seek:async(e,t)=>0,close:async()=>Promise.resolve()})}}return e}async content(e){const t=await this.readSeekCloser();return new Promise((e,r)=>{let i="";t.on("data",e=>{i+=e.toString()}),t.on("end",()=>{e(i)}),t.on("error",r)})}async hash(){return await this.h.setup(this),this.h.value}async size(){return await this.h.setup(this),this.h.size}cloneTo(e){const t=this.clone();return t.paths=t.paths.fromTargetPath(e),t}clone(){const t=new e(this.openReadSeekCloser,this._mediaType,this.paths,{...this._data},this.publisher);return t.h=this.h,t}key(){return this.paths.targetLink()}get RelPermalink(){return this.relPermalink()}get Permalink(){return this.permalink()}get Name(){return this.name()}get MediaType(){return this.mediaType()}get ResourceType(){return this.resourceType()}get TargetPath(){return this.targetPath()}get Data(){return this.data()}get Content(){return this.content()}get Hash(){return()=>this.hash()}get Size(){return()=>this.size()}meta(){return new ResourceMetadataImpl(this.paths.targetPath(),this._mediaType.type,this._data)}mergeData(e){if(e&&0!==Object.keys(e).length)for(const[t,r]of Object.entries(e))t in this._data||(this._data[t]=r)}async transform(...e){let t=this;for(let r=0;r<e.length;r++){const i=e[r];try{const e=await t.readSeekCloser(),r=new PassThrough;let s="";const n=[],a={source:{from:e,inPath:t.targetPath(),inMediaType:t.mediaType()},target:{to:r},data:{...t.data()},addOutPathIdentifier:e=>{const r=t.targetPath(),i=PathDomain.parseBasic(r);let s=i.dir;s=s.replace(/\/+$/,"");let n="";s&&(n=s+"/"),n+=i.nameWithoutExt+e+i.ext,a.data.targetPath=n},updateBuffer:()=>{},updateSource:()=>{},close:()=>{e.close()}};r.on("data",e=>{n.push(e)});const o=new Promise((e,t)=>{r.on("end",()=>{s=Buffer.concat(n).toString(),e()}),r.on("error",e=>{t(e)})});await i.transform(a),await o;const l=a.data.targetPath||t.targetPath(),c=this.createTransformedResource(s,l,t.mediaType(),a.data);t=c,a.close()}catch(e){throw e}}return t}createTransformedResource(t,r,i,s){const n=this.paths.fromTargetPath(r);return new e(async()=>{const e=new PassThrough;return e.end(t),Object.assign(e,{seek:async(e,t)=>0,close:async()=>Promise.resolve()})},i,n,s,this.publisher)}}}});import{minify as terserMinify}from"terser";var IntegrityClient,FingerprintTransformation,init_minifier=__esm({"internal/domain/resources/entity/minifier.ts"(){init_resources2(),MinifierClient=class{minifiers=new Map;minifyOutput;constructor(e=!1){this.minifyOutput=e,this.setupMinifiers()}setupMinifiers(){this.minifiers.set("text/css",this.minifyCSS.bind(this)),this.minifiers.set("text/javascript",this.minifyJS.bind(this)),this.minifiers.set("application/javascript",this.minifyJS.bind(this)),this.minifiers.set("application/json",this.minifyJSON.bind(this)),this.minifiers.set("text/html",this.minifyHTML.bind(this)),this.minifiers.set("image/svg+xml",this.minifySVG.bind(this)),this.minifiers.set("application/xml",this.minifyXML.bind(this)),this.minifiers.set("text/xml",this.minifyXML.bind(this))}async minify(e){const t=new MinifyTransformation(this);return e.transform(t)}getMinifier(e){return this.minifiers.get(e)||null}async minifyCSS(e){return e}async minifyJS(e){try{return(await terserMinify(e,{compress:{drop_console:!1,drop_debugger:!0,passes:2},mangle:{toplevel:!1},format:{comments:!1}})).code||e}catch(t){return e}}async minifyJSON(e){try{return JSON.stringify(JSON.parse(e))}catch{return e}}async minifyHTML(e){return e}async minifySVG(e){return e}async minifyXML(e){return e}},MinifyTransformation=class{constructor(e){this.minifierClient=e}key(){return ResourceTransformationKey.newResourceTransformationKey("minify")}async transform(e){e.addOutPathIdentifier(".min");const t=e.source.inMediaType.type,r=this.minifierClient.getMinifier(t);if(!r)return void e.source.from.pipe(e.target.to);let i="";e.source.from.on("data",e=>{i+=e.toString()}),await new Promise((t,s)=>{e.source.from.on("end",async()=>{try{const s=await r(i);e.target.to.write(s),e.target.to.end(),t()}catch(e){s(e)}}),e.source.from.on("error",s)})}}}});import{createHash as createHash4}from"crypto";var ExecuteAsTemplateTransform,TemplateClient,log54,Publisher2,FileWritable,init_integrity=__esm({"internal/domain/resources/entity/integrity.ts"(){init_resources2(),IntegrityClient=class{async fingerprint(e,t="sha256"){const r=new FingerprintTransformation(t);return e.transform(r)}generateIntegrity(e){return`sha256-${createHash4("sha256").update(e,"utf8").digest("base64")}`}generateSHA384(e){return`sha384-${createHash4("sha384").update(e,"utf8").digest("base64")}`}generateSHA512(e){return`sha512-${createHash4("sha512").update(e,"utf8").digest("base64")}`}verifyIntegrity(e,t){const[r,i]=t.split("-",2);let s;switch(r){case"sha256":s=createHash4("sha256").update(e,"utf8").digest("base64");break;case"sha384":s=createHash4("sha384").update(e,"utf8").digest("base64");break;case"sha512":s=createHash4("sha512").update(e,"utf8").digest("base64");break;default:return!1}return s===i}},FingerprintTransformation=class{constructor(e){this.algo=e}key(){return ResourceTransformationKey.newResourceTransformationKey("fingerprint",this.algo)}async transform(e){const t=this.newHash(this.algo);let r="";const i=[];e.source.from.on("data",e=>{t.update(e),i.push(e),r+=e.toString()}),await new Promise((r,s)=>{e.source.from.on("end",()=>{try{const s=t.digest(),n=s.toString("hex");e.data.Integrity=this.integrity(this.algo,s);const a=n.substring(0,12);e.addOutPathIdentifier("."+a);for(const t of i)e.target.to.write(t);e.target.to.end(),r()}catch(e){s(e)}}),e.source.from.on("error",s)})}newHash(e){switch(e){case"md5":return createHash4("md5");case"sha256":return createHash4("sha256");case"sha384":return createHash4("sha384");case"sha512":return createHash4("sha512");default:throw new Error(`Unsupported hash algorithm: "${e}", use either md5, sha256, sha384 or sha512`)}}integrity(e,t){return`${e}-${t.toString("base64")}`}}}}),init_template4=__esm({"internal/domain/resources/entity/template.ts"(){init_resources2(),ExecuteAsTemplateTransform=class{templateExecutor;_targetPath;data;constructor(e,t,r){this.templateExecutor=e,this._targetPath=t,this.data=r}key(){return ResourceTransformationKey.newResourceTransformationKey("execute-as-template",this._targetPath)}async transform(e){try{e.data.targetPath=this._targetPath;let t="";if("function"==typeof e.source.from.read){let r;const i=[];for(;null!==(r=e.source.from.read());)r&&i.push(r);if(i.length>0)t=Buffer.concat(i).toString();else if(e.source.from._readableState&&e.source.from._readableState.buffer){const r=e.source.from._readableState.buffer,i=[];for(const e of r)e&&e.chunk&&i.push(e.chunk);i.length>0&&(t=Buffer.concat(i).toString())}}if(!t)return new Promise((t,r)=>{const i=[];e.source.from.on("data",e=>{i.push(e)}),e.source.from.on("end",async()=>{try{const s=Buffer.concat(i).toString();await this.executeTemplate(s,e,t,r)}catch(t){r(new Error(`failed to parse Resource "${e.source.inPath}" as Template: ${t}`))}}),e.source.from.on("error",e=>{r(e)}),"function"==typeof e.source.from.resume&&e.source.from.resume()});await this.executeTemplateSync(t,e)}catch(t){throw new Error(`failed to parse Resource "${e.source.inPath}" as Template: ${t}`)}}async executeTemplateSync(e,t){const r=await this.templateExecutor.executeTemplate(t.source.inPath,e,this.data);t.target.to.write(r),t.target.to.end()}async executeTemplate(e,t,r,i){try{await this.executeTemplateSync(e,t),r()}catch(e){i(e instanceof Error?e:new Error(String(e)))}}},TemplateClient=class{templateExecutor;constructor(e){this.templateExecutor=e}async executeAsTemplate(e,t,r){try{if(!e)throw new Error("Resource is null or undefined");if("function"!=typeof e.transform)throw new Error("Resource does not implement Transformer interface. Resource type: "+typeof e);const i=new ExecuteAsTemplateTransform(this.templateExecutor,t.replace(/\\/g,"/").replace(/^\/+/,""),r);return await e.transform(i)}catch(e){throw e}}}}});import*as path24 from"path";import{Writable as Writable2}from"stream";var log55,HttpClient4,init_publisher2=__esm({"internal/domain/resources/entity/publisher.ts"(){init_log(),log54=getDomainLogger("resources",{component:"publisher"}),Publisher2=class{pubFs;urlSvc;constructor(e,t){this.pubFs=e,this.urlSvc=t}async openPublishFileForWriting(e){const t=e.replace(/^\/+/,"");try{const e=await this.pubFs.create(t);return new FileWritable(e)}catch(e){if("ENOENT"===e.code||e.message.includes("ENOENT")){const e=path24.dirname(t);await this.pubFs.mkdirAll(e,511);const r=await this.pubFs.create(t),i=r.close.bind(r);return r.close=async()=>{try{await i()}catch(e){throw log54.errorf("❌ [Publisher.File.close] Error closing publish file (retry) %s, $s",t,e),e}},new FileWritable(r)}throw e}}async openFilesForWriting(...e){if(0===e.length)throw new Error("No filenames provided");const t=e[0];return await this.openFileForWriting(t)}async openFileForWriting(e){const t=path24.normalize(e);try{return await this.pubFs.create(t)}catch(e){if(!this.isFileNotFoundError(e))throw e;const r=path24.dirname(t);return await this.pubFs.mkdirAll(r,511),await this.pubFs.create(t)}}isFileNotFoundError(e){return e&&("ENOENT"===e.code||e.message?.includes("no such file or directory")||e.message?.includes("not found"))}},FileWritable=class extends Writable2{file;constructor(e){super(),this.file=e}_write(e,t,r){this.file.write(e).then(()=>r()).catch(r)}_final(e){this.file.sync?.().then(()=>this.file.close()).then(()=>e()).catch(e)}}}});import*as http2 from"http";import*as https2 from"https";var log56,Resources,init_http2=__esm({"internal/domain/resources/entity/http.ts"(){init_log(),log55=getDomainLogger("resources",{component:"http-client"}),HttpClient4=class{defaultTimeout=3e4;defaultHeaders={"User-Agent":"MDFriday-Resources/1.0.0"};async fromRemote(e,t){return new Promise(r=>{try{const i=new URL(e),s="https:"===i.protocol,n=s?https2:http2,a={...this.defaultHeaders,...t?.headers},o={hostname:i.hostname,port:i.port||(s?443:80),path:i.pathname+i.search,method:"GET",headers:a,timeout:t?.timeout||this.defaultTimeout},l=n.request(o,i=>{if(i.statusCode&&i.statusCode>=300&&i.statusCode<400&&i.headers.location)return log55.infof("🔄 [HttpClient.fromRemote] Redirecting from %s to %s",e,i.headers.location),void this.fromRemote(i.headers.location,t).then(r);if(!i.statusCode||i.statusCode<200||i.statusCode>=300)return log55.errorf("❌ [HttpClient.fromRemote] HTTP error %d when fetching %s: %s",i.statusCode||0,e,i.statusMessage||"Unknown error"),void r(null);const s=[];i.on("data",e=>{s.push(e)}),i.on("end",()=>{try{const t=Buffer.concat(s).toString("utf8");log55.infof("✅ [HttpClient.fromRemote] Successfully fetched %d bytes from %s",t.length,e),r(t)}catch(t){log55.errorf("❌ [HttpClient.fromRemote] Error converting response to string from %s: %s",e,t),r(null)}}),i.on("error",t=>{log55.errorf("❌ [HttpClient.fromRemote] Response error when fetching %s: %s",e,t.message),r(null)})});l.on("error",t=>{log55.errorf("❌ [HttpClient.fromRemote] Request error when fetching %s: %s",e,t.message),r(null)}),l.on("timeout",()=>{l.destroy(),log55.errorf("❌ [HttpClient.fromRemote] Request timeout when fetching %s",e),r(null)}),l.end()}catch(t){log55.errorf("❌ [HttpClient.fromRemote] Error fetching content from %s: %s",e,t),r(null)}})}}}});import*as path25 from"path";import{createHash as createHash5}from"crypto";import{Readable as Readable2}from"stream";var ResourcePaths,init_resources=__esm({"internal/domain/resources/entity/resources.ts"(){init_resource(),init_resources2(),init_minifier(),init_integrity(),init_template4(),init_publisher2(),init_http2(),init_type6(),init_log(),log56=getDomainLogger("resources",{component:"resources"}),Resources=class{cache=new Map;workspace;fsSvc;urlSvc;templateSvc;publisher;minifierClient;integrityClient;templateClient=null;httpClient;constructor(e){this.workspace=e,this.fsSvc=e,this.urlSvc=e,this.templateSvc=e,this.publisher=new Publisher2(e.publishFs(),e),this.minifierClient=new MinifierClient,this.integrityClient=new IntegrityClient,this.templateClient=new TemplateClient(this.templateSvc),this.httpClient=new HttpClient4}setTemplateSvc(e){this.templateSvc=e,this.templateClient=new TemplateClient(e)}async getResource(e){const t=path25.posix.normalize(e),r=`${t}__get`;if(this.cache.has(r))return this.cache.get(r)||null;try{const e=this.workspace.assetsFs();if(!await e.stat(t))return null;const i=async()=>{const r=await e.open(t);return await this.createReadSeekCloser(r)},s=await this.buildResource(t,i);return s&&this.cache.set(r,s),s}catch(e){return log56.errorf("❌ [Resources.getResource] Error getting resource %s, %s",t,e),null}}async getResourceWithOpener(e,t){const r=path25.posix.normalize(e),i=`${r}__get_with_opener`;if(this.cache.has(i))return this.cache.get(i)||null;try{const e=await this.buildResource(r,t);return e&&this.cache.set(i,e),e}catch(e){return log56.errorf("❌ [Resources.getResourceWithOpener] Error getting resource with opener %s, %s",r,e),null}}async executeAsTemplate(e,t,r){if(!this.templateClient)throw new Error("Template client not available. Please set template client first.");const i=e.key()+"-template-"+t,s=this.cacheKey(i);if(this.cache.has(s))return this.cache.get(s);try{const i=await this.templateClient.executeAsTemplate(e,t,r);return i?this.cache.set(s,i):log56.warnf("⚠️ [Resources.executeAsTemplate] Template execution returned null for resource %s",e.key()),i}catch(t){throw log56.errorf("❌ [Resources.executeAsTemplate] Error executing template %s, %s",e.key(),t),t}}async minify(e){if(!this.minifierClient)throw new Error("Minifier client not available. Please set minifier client first.");const t=e.key()+"-minify",r=this.cacheKey(t);if(this.cache.has(r))return this.cache.get(r);try{const t=await this.minifierClient.minify(e);return t?this.cache.set(r,t):log56.warnf("⚠️ [Resources.minify] Minification returned null for resource %s",e.key()),t}catch(t){throw log56.errorf("❌ [Resources.minify] Error minifying resource %s, %s",e.key(),t),t}}async fingerprint(e){const t=e.key()+"-fingerprint",r=this.cacheKey(t);if(this.cache.has(r))return this.cache.get(r);try{const t=await this.integrityClient.fingerprint(e);return t?this.cache.set(r,t):log56.warnf("⚠️ [Resources.fingerprint] Fingerprint operation returned null for resource %s",e.key()),t}catch(t){throw log56.errorf("❌ [Resources.fingerprint] Error fingerprinting resource %s, %s",e.key(),t),t}}async getRemote(e){const t=`${e}__remote`;if(this.cache.has(t))return this.cache.get(t)||null;try{const r=await this.httpClient.fromRemote(e);if(!r)return null;const i=async()=>this.newReadSeekerNoOpCloserFromString(r),s=await this.buildResource(e,i);return s&&this.cache.set(t,s),s}catch(t){return log56.errorf("❌ [Resources.fromRemote] Error getting remote resource %s, %s",e,t),null}}cacheKey(e){return createHash5("sha256").update(e).digest("hex").substring(0,16)}getMinifierClient(){return this.minifierClient}getIntegrityClient(){return this.integrityClient}setTemplateClient(e){this.templateClient=e}async buildResource(e,t){try{const r=path25.extname(e),i=this.getMediaTypeFromExtension(r),s=ResourcePaths.newResourcePaths(e,this.workspace);return new ResourceImpl(t,i,s,{},this.publisher)}catch(t){return log56.errorf("❌ [Resources.buildResource] Error building resource for %s, %s",e,t),null}}getMediaTypeFromExtension(e){const t={".js":{type:"text/javascript",mainType:"text",subType:"javascript"},".css":{type:"text/css",mainType:"text",subType:"css"},".html":{type:"text/html",mainType:"text",subType:"html"},".json":{type:"application/json",mainType:"application",subType:"json"},".svg":{type:"image/svg+xml",mainType:"image",subType:"svg+xml"},".xml":{type:"application/xml",mainType:"application",subType:"xml"},".txt":{type:"text/plain",mainType:"text",subType:"plain"}},r=e?t[e]||t[".txt"]:t[".html"],i=e?e.substring(1):"html",s=e||".html";return new MediaType({type:r.type,mainType:r.mainType,subType:r.subType,delimiter:".",firstSuffix:{suffix:i,fullSuffix:s},mimeSuffix:"",suffixesCSV:i})}async createReadSeekCloser(e){try{const t=[];let r=0;try{for(;;){const i=new Uint8Array(8192),s=await e.read(i);if(0===s.bytesRead)break;r+=s.bytesRead,t.push(i.slice(0,s.bytesRead))}}finally{await e.close()}let i="";if(t.length>0){const e=new Uint8Array(r);let s=0;for(const r of t)e.set(r,s),s+=r.length;i=(new TextDecoder).decode(e)}return this.newReadSeekerNoOpCloserFromString(i)}catch(t){try{await e.close()}catch(t){log56.warnf("❌ [Resources.createReadSeekCloser] Error closing file after read error %s, %s",e.path,t)}return this.newReadSeekerNoOpCloserFromString("")}}newReadSeekerNoOpCloserFromString(e){const t=new Readable2({read(){}});return t.push(e),t.push(null),Object.assign(t,{seek:async(e,t)=>0,close:async()=>Promise.resolve()})}}}});import*as path26 from"path";var ResourceTransformationKey,init_resourcepaths=__esm({"internal/domain/resources/valueobject/resourcepaths.ts"(){ResourcePaths=class e{dir;baseDirTarget;baseDirLink;targetBasePaths;file;baseUrl="";constructor(e="",t="",r="",i="",s=[],n=""){this.dir=e,this.file=t,this.baseDirTarget=r,this.baseDirLink=i,this.targetBasePaths=s,this.baseUrl=n}static newResourcePaths(t,r){const i=t.replace(/\\/g,"/"),s=path26.posix.parse(i);let n=s.dir;return"/"===n&&(n=""),new e(n,s.base,r.baseUrl(),r.baseUrl(),[],r.baseUrl())}join(...e){let t="";for(let r=0;r<e.length;r++){const i=e[r];if(i)if(""===t)t=i;else{const e=!t.endsWith("/")&&!i.startsWith("/"),r=t.endsWith("/")&&i.startsWith("/");t+=r?i.substring(1):e?"/"+i:i}}return t.startsWith("/")&&(t=t.substring(1)),t.endsWith("/")&&t.length>1&&(t=t.substring(0,t.length-1)),t}targetLink(){let e=this.join(this.baseDirLink,this.dir,this.file);return e.startsWith("http://")||e.startsWith("https://")||e.startsWith("/")||(e="/"+e),e}targetPath(){return this.join(this.dir,this.file)}fromTargetPath(t){const r=t.replace(/\\/g,"/"),i=path26.posix.parse(r);let s=i.dir;return"/"===s&&(s=""),new e(s,i.base,this.baseUrl,this.baseUrl,this.targetBasePaths,this.baseUrl)}pathDir(){return this.dir}pathBaseDirTarget(){return this.baseDirTarget}pathBaseDirLink(){return this.baseDirLink}pathTargetBasePaths(){return this.targetBasePaths}pathFile(){return this.file}}}});import{createHash as createHash6}from"crypto";var ResourceMetadataImpl,log57,configCache,modulesCache,fsCache,contentCache,resourcesCache,siteCache,createDomainInstances,tasks,init_transformation=__esm({"internal/domain/resources/valueobject/transformation.ts"(){ResourceTransformationKey=class e{constructor(e,t=[]){this.name=e,this.elements=t}static newResourceTransformationKey(t,...r){return new e(t,r)}value(){if(0===this.elements.length)return this.name;const e=this.hashElements(...this.elements);return`${this.name}_${e}`}hashElements(...e){const t=e.map(e=>String(e)).join("|");return createHash6("sha256").update(t).digest("hex").substring(0,16)}}}}),init_resourcemetadata=__esm({"internal/domain/resources/valueobject/resourcemetadata.ts"(){ResourceMetadataImpl=class e{constructor(e,t,r){this.target=e,this.mediaType=t,this.metaData=r}marshal(){return JSON.stringify({Target:this.target,MediaType:this.mediaType,Data:this.metaData})}static unmarshal(t){const r=JSON.parse(t);return new e(r.Target,r.MediaType,r.Data||{})}}}}),init_resource2=__esm({"internal/domain/resources/factory/resource.ts"(){init_resources()}}),init_resources2=__esm({"internal/domain/resources/index.ts"(){init_type9(),init_resources(),init_resource(),init_minifier(),init_integrity(),init_template4(),init_resourcepaths(),init_transformation(),init_resourcemetadata(),init_resource2()}}),ssg_exports={};__export(ssg_exports,{collectAllPageTasks:()=>collectAllPageTasks,generateStaticSite:()=>generateStaticSite,generateStaticSiteWithProgress:()=>generateStaticSiteWithProgress,processSSG:()=>processSSG,processSSGWithProgress:()=>processSSGWithProgress,serveSSG:()=>serveSSG});import path27 from"path";function setDomainInstances(e,t,r,i,s,n,a){siteCache=e,contentCache=t,fsCache=r,configCache=i,modulesCache=s,resourcesCache=n}async function loadConfiguration(e,t){const r=new OsFs,i=path27.join(e,"config.json");return await loadConfigWithParams(r,i,e,t)}async function createFileSystem(e,t){const r={path:e.getDir().getWorkingDir(),publish:e.getDir().getPublishDir(),osFs:e.fs()};return await createFs(r,t)}async function createContentEngine(e,t,r,i){const s={baseUrl:()=>t.getRoot().baseUrl(),markdown:()=>i,useInternalRenderer:()=>t.getMarkdown().useInternalRenderer(),isWikilinkEnabled:()=>t.getMarkdown().isWikilinkEnabled(),isTagEnabled:()=>t.getMarkdown().isTagEnabled(),isCalloutEnabled:()=>t.getMarkdown().isCalloutEnabled(),isLatexEnabled:()=>t.getMarkdown().isLatexEnabled(),isMermaidEnabled:()=>t.getMarkdown().isMermaidEnabled(),newFileMetaInfo:t=>e.newFileMetaInfo(t),newFileMetaInfoWithContent:t=>e.newFileMetaInfoWithContent(t),contentFs:()=>e.contentFs(),walkContent:(t,r,i,s)=>e.walkContent(t,r,i,s),walkI18n:(t,r,i)=>e.walkI18n(t,r,i),isLanguageValid:e=>t.getLanguage().isLanguageValid(e),getSourceLang:e=>r.getSourceLang(e),getLanguageIndex:e=>t.getLanguage().getLanguageIndex(e),getLanguageByIndex:e=>t.getLanguage().getLanguageByIndex(e),defaultLanguage:()=>t.getLanguage().defaultLanguage(),languageIndexes:()=>t.getLanguage().languageIndexes(),views:()=>t.getTaxonomy().getViews().map(e=>{const t=e.singular,r=e.plural;return{singular:()=>t||"",plural:()=>r||""}})};return await createContent(s)}function createResourcesEngine(e,t){return new Resources({assetsFs:()=>t.assetsFs(),publishFs:()=>t.publishFs(),baseUrl:()=>e.getProvider().getString("baseURL")||"http://localhost",executeTemplate:async(e,t,r)=>{throw new Error("Template execution not initialized. Please call resources.setTemplateSvc() first.")}})}async function createTemplateEngineFromFs(e,t,r,i){const s=function(e,t,r){const i=e.getProvider().getString("baseURL")||"http://localhost";return{relURL:e=>t.getURL().relURL(e),absURL:e=>t.getURL().absURL(e,t.isMultipleLanguage(),t.languagePrefix()),urlize:e=>t.getURL().urlize(e),translate:e=>t.translate(e),relRefFrom:async(e,t)=>[e.path||"",null],title:()=>e.getProvider().getString("title")||"My Site",baseURL:()=>i,params:()=>e.getProvider().getParams("params"),menus:()=>({}),isMultiLanguage:()=>e.getLanguage().languageKeys().length>1,version:()=>"0.1.0",environment:()=>"development",generator:()=>"AuPro Static Site Generator",defaultLanguage:()=>e.getLanguage().defaultLanguage(),languageKeys:()=>e.getLanguage().languageKeys(),Get:async function(e){try{return await r.getResource(e)}catch(t){return log57.warn(`Resource not found: ${e}`,t),Promise.resolve(null)}},GetRemote:async function(e){return await r.getRemote(e)},Minify:async function(e){return await r.minify(e)},Fingerprint:async function(e){return await r.fingerprint(e)},ExecuteAsTemplate:async function(e,t,i){return await r.executeAsTemplate(i,e,t)}}}(t,r,i),n={walk:e.walkLayouts.bind(e)};return await async function(e,t){return(new Factory2).createWithServices(e,t)}(n,s)}async function createTemplateAdapter(e,t){return{async lookupLayout(t){const[r,i,s,n]=await e.findFirst(t);return n?{preparer:null,found:!1}:s&&r&&i?{preparer:{name:()=>i,execute:async e=>{const[t,i]=await r.Execute(e);if(i)throw log57.errorf("template exec error: %s",i),i;return t}},found:!0}:{preparer:null,found:!1}},async executeWithContext(e,t){if(!e)return"<html><body>Default template - no preparer</body></html>";try{return await e.execute(t)}catch(e){return log57.error(`❌ Template execution error: ${e}`),`<html><body>Template execution error: ${e}</body></html>`}}}}function createSiteForSSG(e,t,r){return function(e){const t=new Publisher(e.publishFs()),r=new URL2(e.baseUrl(),!0),i=new Language2(e),s=new Author2("MDFriday","support@mdfriday.com"),n=new Organization2,a=new Compiler("0.1.0"),o=new Site(e,e,e,e,e,e,t,s,n,a,r,null,i,null,e.siteTitle()),l=function(e,t,r){return new NavigationFactory(e,t,r)}(e,e,o);return o.navigation=l.createNavigation(),o.ref=new Ref({home:{page:null},sitePage:async e=>{const t=await o.sitePage(e);return{relPermalink:()=>t.path?t.path():"",permalink:()=>t.path?t.path():""}}},e,"/404.html"),o}({configParams:()=>e.getProvider().getParams("params"),siteTitle:()=>e.getProvider().getString("title")||"My Site",menus:()=>({}),isGoogleAnalyticsEnabled:()=>e.getService().isGoogleAnalyticsEnabled(),googleAnalyticsID:()=>e.getService().googleAnalyticsID(),isGoogleAnalyticsRespectDoNotTrack:()=>e.getService().isGoogleAnalyticsRespectDoNotTrack(),isDisqusEnabled:()=>e.getService().isDisqusEnabled(),disqusShortname:()=>e.getService().disqusShortname(),isXRespectDoNotTrack:()=>e.getService().isXRespectDoNotTrack(),isXDisableInlineCSS:()=>e.getService().isXDisableInlineCSS(),getConfiguredSocialPlatforms:()=>e.getSocial().getConfiguredPlatforms(),getSocialLink:t=>{const r=e.getSocial().getSocialLink(t);return r?r.url:""},getSocialTitle:t=>{const r=e.getSocial().getSocialLink(t);return r?r.title:""},globalPages:async e=>await r.globalPages(e),globalRegularPages:async()=>await r.globalRegularPages(),walkPages:async(e,t)=>{await r.walkPages(e,t)},getPageSources:async e=>r.getPageSources(e),walkTaxonomies:async(e,t)=>{await r.walkTaxonomies(e,t)},searchPage:async(e,t)=>[],getPageFromPath:async(e,t)=>{try{const i=r.getPageFromPath(e,t);return i||log57.error(`⚠️ Application.getPageFromPath: content domain returned null for path: "${t}"`),i}catch(e){return log57.error("❌ Application.getPageFromPath error delegating to content domain:",e),null}},getPageFromPathSync:(e,t)=>{try{const i=r.getPageFromPath(e,t);return i||log57.warn(`⚠️ Application.getPageFromPathSync: content domain returned null for path: ${t}`),i}catch(e){return log57.error("❌ Application.getPageFromPathSync error delegating to content domain:",e),null}},getPageRef:async(e,t,r)=>null,translate:(e,t)=>r.translate(e,t),defaultLanguage:()=>e.getLanguage().defaultLanguage(),languageKeys:()=>e.getLanguage().languageKeys(),getLanguageIndex:t=>e.getLanguage().getLanguageIndex(t),getLanguageName:t=>e.getLanguage().getLanguageName(t),changeFreq:()=>"weekly",priority:()=>.5,generateSitemap:async()=>({urls:[]}),publishFs:()=>t.publishFs(),staticFs:()=>t.staticFs(),copyStaticFiles:(e,r)=>t.copyStatic([e],r),workingDir:()=>e.getProvider().getString("workingDir")||process.cwd(),getResource:async e=>null,getResourceWithOpener:async(e,t)=>({name:()=>e,readSeekCloser:t,targetPath:()=>e}),baseUrl:()=>e.getProvider().getString("baseURL")||"http://localhost"})}async function generateStaticSite(e,t,r){try{let i=performance.now();const s=await loadConfiguration(e,t);let n=performance.now();log57.info(`✅ Configuration loaded in ${(n-i).toFixed(2)} ms`);const a=r;i=performance.now();const o=await async function(e){const t={osFs:()=>e.fs(),projDir:()=>e.getDir().getWorkingDir(),moduleDir:()=>e.getDir().getThemesDir(),moduleCacheDir:()=>e.getDir().getThemesCacheDir(),importPaths:()=>e.getModule().importPaths(),defaultLanguageKey:()=>e.getLanguage().defaultLanguage(),otherLanguageKeys:()=>e.getLanguage().otherLanguageKeys(),getRelDir:(t,r)=>e.getLanguage().getRelDir(t,r)};return await async function(e){try{const t=e.httpClient?.(),r=newHttpClient(e.osFs(),void 0,void 0,t),i=newZipExtractor(e.osFs()),s=newModuleCache(e.osFs(),e.moduleCacheDir()),n=newModules(e,r,i,s);return await n.load(),n}catch(e){const t=e instanceof Error?e.message:String(e);throw log5.error(`Failed to create modules: ${t}`),new ModuleError(`Failed to create modules: ${t}`,"FACTORY_FAILED")}}(t)}(s);n=performance.now(),log57.info(`✅ Modules created in ${(n-i).toFixed(2)} ms`),i=performance.now();const l=await createFileSystem(s,o);n=performance.now(),log57.info(`✅ Filesystem created in ${(n-i).toFixed(2)} ms`);const c=await createContentEngine(l,s,o,a),h=createSiteForSSG(s,l,c),u=createResourcesEngine(s,l),g=await createTemplateEngineFromFs(l,s,h,u);u.setTemplateSvc({executeTemplate:async(e,t,r)=>await g.executeRaw(e,t,r)}),c.setTemplateSvc({execute:async(e,t)=>await g.executeShortcode(e,t)}),i=performance.now(),await c.collectPages(),n=performance.now(),log57.info(`✅ Pages collected in ${(n-i).toFixed(2)} ms`);const d=await createTemplateAdapter(g);i=performance.now(),await h.build(d),n=performance.now(),setDomainInstances(h,c,l,s,o,u),log57.info(`✅ Site built in ${(n-i).toFixed(2)} ms`)}catch(e){const t=e instanceof Error?e.message:String(e);throw log57.error(`❌ Static site generation failed: ${t}`),new Error(`Failed to generate static site: ${t}`)}}async function processSSG(e,t,r){try{const i=process.cwd();process.chdir(e);try{await generateStaticSite(e,t,r)}finally{process.chdir(i)}}catch(e){const t=e instanceof Error?e.message:String(e);throw log57.error(`❌ SSG processing failed: ${t}`),new Error(`Failed to process SSG: ${t}`)}}async function generateStaticSiteWithProgress(e,t,r,i,s){try{i?.({stage:"config",message:"Loading configuration...",percentage:5});const n=await loadConfiguration(e,t),a=r;i?.({stage:"modules",message:"Creating and downloading modules...",percentage:10});const o=await createModuleWithProgress(n,i,s);i?.({stage:"filesystem",message:"Creating filesystem...",percentage:30});const l=await createFileSystem(n,o);i?.({stage:"content",message:"Creating content engine...",percentage:40});const c=await createContentEngine(l,n,o,a);i?.({stage:"site",message:"Creating site...",percentage:50});const h=createSiteForSSG(n,l,c),u=createResourcesEngine(n,l);i?.({stage:"template",message:"Creating template engine...",percentage:60});const g=await createTemplateEngineFromFs(l,n,h,u);u.setTemplateSvc({executeTemplate:async(e,t,r)=>await g.executeRaw(e,t,r)}),c.setTemplateSvc({execute:async(e,t)=>await g.executeShortcode(e,t)}),i?.({stage:"pages",message:"Collecting pages...",percentage:65}),await c.collectPages(),i?.({stage:"build",message:"Building site...",percentage:70});const d=await createTemplateAdapter(g);return await async function(e,t,r){const i=r?e=>{const t=70+Math.floor(e.currentPage/e.totalPages*29);r({stage:"build",message:`Rendering pages (${e.currentPage}/${e.totalPages})...`,percentage:t,pageRender:e})}:void 0;await e.buildWithProgress(t,i)}(h,d,i),i?.({stage:"completion",message:"SSG generation completed",percentage:100}),setDomainInstances(h,c,l,n,o,u),createDomainInstances(siteCache,contentCache,fsCache,configCache,modulesCache,resourcesCache)}catch(e){const t=e instanceof Error?e.message:String(e);throw log57.error(`❌ Static site generation failed: ${t}`),new Error(`Failed to generate static site: ${t}`)}}async function createModuleWithProgress(e,t,r){const i={osFs:()=>e.fs(),projDir:()=>e.getDir().getWorkingDir(),moduleDir:()=>e.getDir().getThemesDir(),moduleCacheDir:()=>e.getDir().getThemesCacheDir(),importPaths:()=>e.getModule().importPaths(),defaultLanguageKey:()=>e.getLanguage().defaultLanguage(),otherLanguageKeys:()=>e.getLanguage().otherLanguageKeys(),getRelDir:(t,r)=>e.getLanguage().getRelDir(t,r),httpClient:r?()=>r:void 0};return await async function(e,t){const r=t?e=>{t({stage:"modules",message:`Downloading module: ${e.modulePath}`,percentage:10+Math.floor(.2*e.downloadPercentage),moduleDownload:{modulePath:e.modulePath,downloadPercentage:e.downloadPercentage}})}:void 0;return await async function(e,t){try{const r=e.httpClient?.(),i=newHttpClient(e.osFs(),void 0,void 0,r),s=newZipExtractor(e.osFs()),n=newModuleCache(e.osFs(),e.moduleCacheDir()),a=newModules(e,i,s,n);return await a.load(t),a}catch(e){const t=e instanceof Error?e.message:String(e);throw log5.error(`Failed to create modules: ${t}`),new ModuleError(`Failed to create modules: ${t}`,"FACTORY_FAILED")}}(e,r)}(i,t)}async function processSSGWithProgress(e,t,r,i,s){try{const n=process.cwd();process.chdir(e);try{await generateStaticSiteWithProgress(e,t,r,i,s)}finally{process.chdir(n)}}catch(e){const t=e instanceof Error?e.message:String(e);throw log57.error(`❌ SSG processing failed: ${t}`),new Error(`Failed to process SSG: ${t}`)}}async function serveSSG(e,t,r,i,s){try{return process.chdir(e),await generateStaticSiteWithProgress(e,t,r,i,s)}catch(e){const t=e instanceof Error?e.message:String(e);throw log57.error(`❌ SSG processing failed: ${t}`),new Error(`Failed to process SSG: ${t}`)}}async function collectAllPageTasks(e,t,r,i,s){if(tasks.length>0)return log57.info("Page tasks already collected, returning cached tasks"),tasks;try{let n=performance.now();const a=await loadConfiguration(e,t);let o=performance.now();log57.info(`✅ Configuration loaded in ${(o-n).toFixed(2)} ms`);const l=r;n=performance.now();const c=await createModuleWithProgress(a,i,s);o=performance.now(),log57.info(`✅ Modules created in ${(o-n).toFixed(2)} ms`),n=performance.now();const h=await createFileSystem(a,c);o=performance.now(),log57.info(`✅ Filesystem created in ${(o-n).toFixed(2)} ms`);const u=await createContentEngine(h,a,c,l),g=createSiteForSSG(a,h,u),d=createResourcesEngine(a,h),p=await createTemplateEngineFromFs(h,a,g,d);d.setTemplateSvc({executeTemplate:async(e,t,r)=>await p.executeRaw(e,t,r)}),u.setTemplateSvc({execute:async(e,t)=>await p.executeShortcode(e,t)}),n=performance.now(),await u.collectPages(),o=performance.now(),log57.info(`✅ Pages collected in ${(o-n).toFixed(2)} ms`),n=performance.now();const m=a.getLanguage().languageKeys();for(const e of m){const t=a.getLanguage().getLanguageIndex(e);await u.walkPages(t,async t=>{const r=t.file().paths().base();tasks.push({language:e,pagePath:r}),t&&t.pageIdentity&&t.pageIdentity().clearStale()}),log57.debug(`Collected pages for language: ${e}`)}o=performance.now(),log57.info(`✅ Page tasks collected in ${(o-n).toFixed(2)} ms`);const f=await createTemplateAdapter(p);return n=performance.now(),await g.build(f),o=performance.now(),log57.info(`✅ Site built in ${(o-n).toFixed(2)} ms`),setDomainInstances(g,u,h,a,c,d),tasks}catch(e){const t=e instanceof Error?e.message:String(e);throw log57.error(`❌ Static site generation failed: ${t}`),new Error(`Failed to generate static site: ${t}`)}}var WorkspaceMetadata,ProjectMetadata,init_ssg=__esm({"internal/application/ssg.ts"(){init_config3(),init_module6(),init_fs3(),init_content3(),init_template3(),init_site2(),init_log(),init_resources2(),log57=getDomainLogger("ssg",{component:"application"}),createDomainInstances=(e,t,r,i,s,n)=>({site:e,content:t,fs:r,config:i,modules:s,resources:n}),tasks=[]}}),init_type10=__esm({"internal/domain/workspace/type.ts"(){}}),init_workspace_metadata=__esm({"internal/domain/workspace/value-object/workspace-metadata.ts"(){WorkspaceMetadata=class e{version;id;name;createdAt;updatedAt;paths;defaults;constructor(e){this.version=e.version,this.id=e.id,this.name=e.name,this.createdAt=e.createdAt,this.updatedAt=e.updatedAt,this.paths={...e.paths},this.defaults=e.defaults?{...e.defaults}:{}}static create(t){if(!t.id||!t.name)throw new Error("Workspace ID and name are required");return new e(t)}update(t){return new e({...this,...t,updatedAt:Date.now()})}toJSON(){const e={version:this.version,id:this.id,name:this.name,createdAt:this.createdAt,updatedAt:this.updatedAt,paths:{...this.paths}};return this.defaults&&Object.keys(this.defaults).length>0&&(e.defaults={...this.defaults}),e}}}}),project_metadata_exports={};__export(project_metadata_exports,{ProjectMetadata:()=>ProjectMetadata});var FolderStructure,log68,Workspace,log69,Project,Authentication,Email,Token2,ServerConfig,License,SyncConfig,Device,User,log71,UserFactory,init_project_metadata=__esm({"internal/domain/workspace/value-object/project-metadata.ts"(){ProjectMetadata=class e{id;name;type;workspaceId;createdAt;updatedAt;buildHistory;previews;contentLinks;staticLink;fileLink;baseURLStructure;constructor(e){this.id=e.id,this.name=e.name,this.type=e.type||"site",this.workspaceId=e.workspaceId||"",this.createdAt=e.createdAt,this.updatedAt=e.updatedAt,this.buildHistory=e.buildHistory||[],this.previews=e.previews||{},this.contentLinks=e.contentLinks||[],this.staticLink=e.staticLink||null,this.fileLink=e.fileLink||null,this.baseURLStructure=e.baseURLStructure||null}static create(t){if(!t.id||!t.name)throw new Error("Project ID and name are required");return new e(t)}update(t){return new e({...this,...t,updatedAt:Date.now()})}toJSON(){const e={id:this.id,name:this.name,type:this.type,createdAt:this.createdAt,updatedAt:this.updatedAt};return this.workspaceId&&(e.workspaceId=this.workspaceId),this.buildHistory&&this.buildHistory.length>0&&(e.buildHistory=this.buildHistory),this.previews&&Object.keys(this.previews).length>0&&(e.previews=this.previews),this.contentLinks&&this.contentLinks.length>0&&(e.contentLinks=this.contentLinks),this.staticLink&&(e.staticLink=this.staticLink),this.fileLink&&(e.fileLink=this.fileLink),this.baseURLStructure&&(e.baseURLStructure=this.baseURLStructure),e}}}}),init_folder_structure=__esm({"internal/domain/workspace/value-object/folder-structure.ts"(){FolderStructure=class e{rootPath;contentFolders;staticFolder;isStructured;constructor(e,t,r,i){this.rootPath=e,this.contentFolders=t,this.staticFolder=r,this.isStructured=i}static fromScanResult(t){return new e(t.rootPath,t.contentFolders,t.staticFolder,t.isStructured)}static createEmpty(t){return new e(t,[],null,!1)}static createSingleContent(t,r,i="en"){return new e(t,[{path:r,languageCode:i,weight:0}],null,!0)}getRootPath(){return this.rootPath}getContentFolders(){return[...this.contentFolders]}getStaticFolder(){return this.staticFolder?{...this.staticFolder}:null}getIsStructured(){return this.isStructured}hasContentFolders(){return this.contentFolders.length>0}hasStaticFolder(){return null!==this.staticFolder}getContentFolderCount(){return this.contentFolders.length}getDefaultContentFolder(){return this.contentFolders.find(e=>0===e.weight)||null}getLanguageContentFolders(){return this.contentFolders.filter(e=>e.weight>0)}getContentFolderByLanguage(e){return this.contentFolders.find(t=>t.languageCode===e)||null}getSupportedLanguages(){return this.contentFolders.map(e=>e.languageCode)}isValid(){return!this.isStructured||this.contentFolders.length>0}isMultilingual(){return this.contentFolders.length>1}getSummary(){if(!this.isStructured)return`Empty structure at ${this.rootPath}`;const e=[];if(e.push(`Structured folder at ${this.rootPath}:`),e.push(` - ${this.contentFolders.length} content folder(s)`),this.isMultilingual()){const t=this.getSupportedLanguages().join(", ");e.push(` Languages: ${t}`)}return this.staticFolder&&e.push(" - static folder"),e.join("\n")}toJSON(){return{rootPath:this.rootPath,contentFolders:this.contentFolders,staticFolder:this.staticFolder,isStructured:this.isStructured}}static fromJSON(t){return e.fromScanResult(t)}}}}),init_file_system=__esm({"internal/domain/workspace/repository/file-system.ts"(){}}),init_repository=__esm({"internal/domain/workspace/repository.ts"(){init_file_system()}}),init_workspace=__esm({"internal/domain/workspace/entity/workspace.ts"(){init_log(),log68=getDomainLogger("workspace",{component:"domain"}),Workspace=class{rootPath;metadata;projects;authentication;fileSystemRepo;constructor(e,t,r,i,s){if(this.rootPath=e,this.metadata=t,this.projects=r,this.authentication=i,this.fileSystemRepo=s,!this.fileSystemRepo)throw new Error("FileSystemRepository is required for Workspace")}getPath(){return this.rootPath}getMetadata(){return this.metadata}getId(){return this.metadata.id}getName(){return this.metadata.name}getModulesDir(){return this.fileSystemRepo.join(this.rootPath,this.metadata.paths.modules)}getProjectsDir(){return this.fileSystemRepo.join(this.rootPath,this.metadata.paths.projects)}updateMetadata(e){this.metadata=this.metadata.update(e),log68.debug("Workspace metadata updated",{workspaceId:this.getId()})}updateName(e){this.updateMetadata({name:e})}getProjects(){return Array.from(this.projects.values())}getProject(e){return this.projects.get(e)}getProjectByName(e){for(const t of this.projects.values())if(t.getName()===e)return t}findProject(e){return this.getProject(e)||this.getProjectByName(e)}hasProject(e){return this.projects.has(e)}addProject(e){if(this.projects.has(e.getId()))throw new Error(`Project ${e.getId()} already exists in workspace`);this.projects.set(e.getId(),e),log68.info(`Project added to workspace: ${e.getName()} (${e.getId()})`)}removeProject(e){const t=this.projects.get(e);return t?(this.projects.delete(e),log68.info(`Project removed from workspace: ${t.getName()} (${e})`),t):null}getProjectCount(){return this.projects.size}getProjectRegistry(){const e=[];for(const t of this.projects.values()){const r=t.getMetadata(),i=t.getPath(),s=this.fileSystemRepo.relative(this.getProjectsDir(),i);e.push({id:r.id,name:r.name,path:s,absolutePath:i,createdAt:r.createdAt,updatedAt:r.updatedAt,status:"active"})}return{version:"1.0",projects:e}}getAuthentication(){return this.authentication}hasAuthentication(){return this.authentication.hasAuth()}getConfigPath(){return this.fileSystemRepo.join(this.rootPath,".mdfriday","config.json")}async getConfig(e){const t=this.getConfigPath();try{const r=await this.fileSystemRepo.readFile(t,"utf-8"),i=JSON.parse(r);return this.getNestedValue(i,e)}catch(e){if(e.message?.includes("Cannot access path"))return;throw e}}async getAllConfig(){const e=this.getConfigPath();try{const t=await this.fileSystemRepo.readFile(e,"utf-8");return JSON.parse(t)}catch(e){if(e.message?.includes("Cannot access path"))return{};throw e}}async setConfig(e,t){const r=this.getConfigPath(),i=this.fileSystemRepo.dirname(r);await this.fileSystemRepo.createDirectory(i,!0);let s={};try{const e=await this.fileSystemRepo.readFile(r,"utf-8");s=JSON.parse(e)}catch(e){if(!e.message?.includes("Cannot access path"))throw e}this.setNestedValue(s,e,t),await this.fileSystemRepo.writeFile(r,JSON.stringify(s,null,2),"utf-8"),log68.debug(`Workspace config updated: ${e}`,{workspaceId:this.getId()})}async unsetConfig(e){const t=this.getConfigPath();try{const r=await this.fileSystemRepo.readFile(t,"utf-8"),i=JSON.parse(r),s=this.deleteNestedValue(i,e);return s&&(await this.fileSystemRepo.writeFile(t,JSON.stringify(i,null,2),"utf-8"),log68.debug(`Workspace config deleted: ${e}`,{workspaceId:this.getId()})),s}catch(e){if(e.message?.includes("Cannot access path"))return!1;throw e}}getNestedValue(e,t){const r=t.split(".");let i=e;for(const e of r){if(null==i||"object"!=typeof i)return;i=i[e]}return i}setNestedValue(e,t,r){const i=t.split(".");let s=e;for(let e=0;e<i.length-1;e++){const t=i[e];t in s&&"object"==typeof s[t]||(s[t]={}),s=s[t]}s[i[i.length-1]]=r}deleteNestedValue(e,t){const r=t.split(".");let i=e;for(let e=0;e<r.length-1;e++){const t=r[e];if(!(t in i)||"object"!=typeof i[t])return!1;i=i[t]}const s=r[r.length-1];return s in i&&(delete i[s],!0)}getInfo(){return{id:this.metadata.id,name:this.metadata.name,path:this.rootPath,createdAt:new Date(this.metadata.createdAt),updatedAt:new Date(this.metadata.updatedAt),modulesDir:this.metadata.paths.modules,projectsDir:this.metadata.paths.projects,projectCount:this.projects.size,hasAuth:this.authentication.hasAuth()}}}}}),init_project=__esm({"internal/domain/workspace/entity/project.ts"(){init_log(),log69=getDomainLogger("project",{component:"domain"}),Project=class{metadata;projectPath;config=null;fileSystemRepo;constructor(e,t,r){if(this.projectPath=e,this.metadata=t,this.fileSystemRepo=r,!this.fileSystemRepo)throw new Error("FileSystemRepository is required for Project")}getPath(){return this.projectPath}getMetadata(){return this.metadata}getId(){return this.metadata.id}getName(){return this.metadata.name}getType(){return this.metadata.type}getWorkspaceId(){return this.metadata.workspaceId}getBuildHistory(){return this.metadata.buildHistory||[]}addBuildHistory(e){const t=[e,...this.metadata.buildHistory||[]],r=t.length>50?t.slice(0,50):t;this.metadata=this.metadata.update({buildHistory:r}),log69.debug(`Added build history entry for project: ${this.metadata.name}`)}getLastBuildTime(){const e=this.getBuildHistory();return e.length>0?e[0].timestamp:void 0}updateName(e){this.metadata=this.metadata.update({name:e})}async loadConfig(){if(this.config)return this.config;try{const e=this.fileSystemRepo.join(this.projectPath,"config.json"),t=await this.fileSystemRepo.readFile(e,"utf-8");return this.config=JSON.parse(t),this.config}catch(e){return log69.warn(`Failed to load config for project ${this.metadata.name}, using defaults`),this.config={contentDir:"content",publishDir:"public",defaultContentLanguage:"zh"},this.config}}getConfig(){return this.config}async getContentDirs(){const e=await this.loadConfig(),t=[],r=e.contentDir||"content";if(t.push(this.fileSystemRepo.join(this.projectPath,r)),e.languages)for(const[i,s]of Object.entries(e.languages))s.contentDir&&s.contentDir!==r&&t.push(this.fileSystemRepo.join(this.projectPath,s.contentDir));return[...new Set(t)]}async getPublishDir(){const e=(await this.loadConfig()).publishDir||"public";return this.fileSystemRepo.join(this.projectPath,e)}getStaticDir(){return this.fileSystemRepo.join(this.projectPath,"static")}async getDefaultLanguage(){return(await this.loadConfig()).defaultContentLanguage||"zh"}async getLanguages(){const e=await this.loadConfig();return e.languages?Object.keys(e.languages):[await this.getDefaultLanguage()]}getConfigPath(){return this.fileSystemRepo.join(this.projectPath,"config.json")}getConfigValue(e){if(!this.config)throw new Error("Configuration not loaded. Call loadConfig() first.");return this.getNestedValue(this.config,e)}setConfigValue(e,t){if(!this.config)throw new Error("Configuration not loaded. Call loadConfig() first.");this.setNestedValue(this.config,e,t),log69.debug(`Project config updated: ${e}`,{projectName:this.metadata.name})}setConfig(e){if(null===this.config)throw new Error("Configuration not loaded. Call loadConfig() first.");this.config=e,log69.debug("Project config replaced entirely",{projectName:this.metadata.name})}unsetConfigValue(e){if(!this.config)throw new Error("Configuration not loaded. Call loadConfig() first.");const t=this.deleteNestedValue(this.config,e);return t&&log69.debug(`Project config deleted: ${e}`,{projectName:this.metadata.name}),t}async saveConfig(){if(!this.config)throw new Error("Configuration not loaded. Call loadConfig() first.");const e=this.getConfigPath();await this.fileSystemRepo.writeFile(e,JSON.stringify(this.config,null,2),"utf-8"),log69.debug(`Project config saved: ${e}`,{projectName:this.metadata.name})}getNestedValue(e,t){const r=t.split(".");let i=e;for(const e of r){if(null==i||"object"!=typeof i)return;i=i[e]}return i}setNestedValue(e,t,r){const i=t.split(".");let s=e;for(let e=0;e<i.length-1;e++){const t=i[e];t in s&&"object"==typeof s[t]&&!Array.isArray(s[t])||(s[t]={}),s=s[t]}s[i[i.length-1]]=r}deleteNestedValue(e,t){const r=t.split(".");let i=e;for(let e=0;e<r.length-1;e++){const t=r[e];if(!(t in i)||"object"!=typeof i[t])return!1;i=i[t]}const s=r[r.length-1];return s in i&&(delete i[s],!0)}async readFile(e,t="utf-8"){const r=this.fileSystemRepo.join(this.projectPath,e);return this.fileSystemRepo.readFile(r,t)}async writeFile(e,t,r="utf-8"){const i=this.fileSystemRepo.join(this.projectPath,e),s=this.fileSystemRepo.dirname(i);await this.fileSystemRepo.exists(s)||await this.fileSystemRepo.createDirectory(s,!0),await this.fileSystemRepo.writeFile(i,t,r),log69.debug(`Project file written: ${e}`,{projectName:this.metadata.name,filePath:i})}async fileExists(e){const t=this.fileSystemRepo.join(this.projectPath,e);return this.fileSystemRepo.exists(t)}getFilePath(e){return this.fileSystemRepo.join(this.projectPath,e)}getInfo(){const e=this.getLastBuildTime(),t={id:this.metadata.id,name:this.metadata.name,path:this.projectPath,createdAt:new Date(this.metadata.createdAt),updatedAt:new Date(this.metadata.updatedAt),buildCount:this.getBuildHistory().length};return e&&(t.lastBuild=new Date(e)),t}getSnapshotsDir(){return this.fileSystemRepo.join(this.projectPath,".mdfriday","snapshots")}hasSourceLinks(){return this.metadata.contentLinks.length>0||null!==this.metadata.staticLink}getContentLinks(){return[...this.metadata.contentLinks]}getStaticLink(){return this.metadata.staticLink?{...this.metadata.staticLink}:null}getFileLink(){return this.metadata.fileLink?{...this.metadata.fileLink}:null}setContentLinks(e){this.metadata=this.metadata.update({contentLinks:e}),log69.debug(`Updated content links for project: ${this.metadata.name}`,{count:e.length})}setStaticLink(e){this.metadata=this.metadata.update({staticLink:e}),log69.debug(`Updated static link for project: ${this.metadata.name}`,{hasLink:null!==e})}addContentLink(e,t,r){const i=[...this.getContentLinks(),{sourcePath:e,languageCode:t,weight:r}];this.setContentLinks(i)}getDefaultContentSource(){const e=this.metadata.contentLinks.find(e=>0===e.weight);return e?e.sourcePath:null}getAllContentSources(){return this.metadata.contentLinks.map(e=>e.sourcePath)}getContentSourceByLanguage(e){const t=this.metadata.contentLinks.find(t=>t.languageCode===e);return t?t.sourcePath:null}getSupportedLanguagesFromLinks(){return this.metadata.contentLinks.map(e=>e.languageCode)}isLinkedProject(){return this.hasSourceLinks()}getLinkDirs(){const e=[],t=this.getFileLink();t&&e.push(t.sourcePath);const r=this.getContentLinks();for(const t of r)e.includes(t.sourcePath)||e.push(t.sourcePath);return e}async getBaseURL(){return(await this.loadConfig()).baseURL||"/"}async setBaseURL(e){const t=await this.loadConfig();t.baseURL=e;const r=this.fileSystemRepo.join(this.projectPath,"config.json");await this.fileSystemRepo.writeFile(r,JSON.stringify(t,null,2),"utf-8"),this.config=t}parseBaseURLPath(e){let t=e.trim();if(t.startsWith("/")&&(t=t.slice(1)),t.endsWith("/")&&(t=t.slice(0,-1)),""===t)return{isRoot:!0,pathParts:[],parentParts:[],finalDirName:"",relativeToPublic:"."};const r=t.split("/").filter(e=>""!==e);if(0===r.length)return{isRoot:!0,pathParts:[],parentParts:[],finalDirName:"",relativeToPublic:"."};const i=r.length,s=1===i?".":"../".repeat(i-1).slice(0,-1);return{isRoot:!1,pathParts:r,parentParts:r.slice(0,-1),finalDirName:r[r.length-1],relativeToPublic:s}}getBaseURLStructure(){return this.metadata.baseURLStructure||null}updateBaseURLStructure(e){this.metadata=this.metadata.update({baseURLStructure:e})}}}}),init_authentication=__esm({"internal/domain/workspace/entity/authentication.ts"(){init_log(),getDomainLogger("workspace-auth",{component:"domain"}),Authentication=class{workspacePath;hasAuthFile=!1;constructor(e,t=!1){this.workspacePath=e,this.hasAuthFile=t}getWorkspacePath(){return this.workspacePath}hasAuth(){return this.hasAuthFile}markAuthExists(){this.hasAuthFile=!0}markAuthDeleted(){this.hasAuthFile=!1}getAuthFilePath(){return".mdfriday/auth-user.json"}getServerConfigPath(){return".mdfriday/server-config.json"}}}}),init_email=__esm({"internal/domain/identity/value-object/email.ts"(){Email=class e{value;constructor(e){this.value=e}static create(t){if(!e.isValid(t))throw new Error(`Invalid email address: ${t}`);return new e(t)}static isValid(e){return!(!e||"string"!=typeof e)&&/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(e)}getValue(){return this.value}getDomain(){return this.value.split("@")[1]}getLocalPart(){return this.value.split("@")[0]}equals(e){return this.value.toLowerCase()===e.value.toLowerCase()}toString(){return this.value}toJSON(){return this.value}}}}),init_token=__esm({"internal/domain/identity/value-object/token.ts"(){Token2=class e{value;expiresAt;constructor(e,t){this.value=e,this.expiresAt=t}static create(t,r){if(!t||"string"!=typeof t||0===t.trim().length)throw new Error("Token value cannot be empty");return new e(t,r)}static fromJSON(t){return e.create(t.token,t.expiresAt)}getValue(){return this.value}getExpiresAt(){return this.expiresAt}isExpired(){return!!this.expiresAt&&Date.now()>this.expiresAt}isValid(){return!this.isExpired()}getRemainingTime(){if(!this.expiresAt)return null;const e=this.expiresAt-Date.now();return e>0?e:0}equals(e){return this.value===e.value}toString(){return this.value}toJSON(){const e={token:this.value};return void 0!==this.expiresAt&&(e.expiresAt=this.expiresAt),e}}}}),init_server_config=__esm({"internal/domain/identity/value-object/server-config.ts"(){ServerConfig=class e{apiUrl;websiteUrl;constructor(e,t){this.apiUrl=e,this.websiteUrl=t}static create(t,r){if(!t||"string"!=typeof t||0===t.trim().length)throw new Error("API URL cannot be empty");if(!e.isValidUrl(t))throw new Error(`Invalid API URL: ${t}`);if(r&&!e.isValidUrl(r))throw new Error(`Invalid website URL: ${r}`);return new e(t,r)}static fromJSON(t){return e.create(t.apiUrl,t.websiteUrl)}static createDefault(){return e.create("https://app.mdfriday.com","https://mdfriday.com")}static isValidUrl(e){try{return new URL(e),!0}catch{return!1}}getApiUrl(){return this.apiUrl}getWebsiteUrl(){return this.websiteUrl}withApiUrl(t){return e.create(t,this.websiteUrl)}withWebsiteUrl(t){return e.create(this.apiUrl,t)}equals(e){return this.apiUrl===e.apiUrl&&this.websiteUrl===e.websiteUrl}toJSON(){const e={apiUrl:this.apiUrl};return void 0!==this.websiteUrl&&(e.websiteUrl=this.websiteUrl),e}}}}),init_license=__esm({"internal/domain/identity/value-object/license.ts"(){License=class e{key;plan;expiresAt;features;activatedAt;activated;firstTime;constructor(e,t,r,i,s,n=!1,a=!1){this.key=e,this.plan=t,this.expiresAt=r,this.features=i,this.activatedAt=s,this.activated=n,this.firstTime=a}static create(t,r,i,s,n,a,o){if(!e.isValidFormat(t))throw new Error(`Invalid license key format: ${t}`);return new e(t.toUpperCase(),r,i,s,n||Date.now(),a||!1,o||!1)}static fromJSON(t){return e.create(t.key,t.plan,t.expiresAt,t.features,t.activatedAt,t.activated,t.firstTime)}static isValidFormat(e){return/^MDF-[A-Z0-9]{4}-[A-Z0-9]{4}-[A-Z0-9]{4}$/i.test(e)}isExpired(){return Date.now()>this.expiresAt}isValid(){return!this.isExpired()}getDaysRemaining(){const e=this.expiresAt-Date.now();return Math.max(0,Math.ceil(e/864e5))}getEmail(){return`${this.key.replace(/^MDF-/i,"").toLowerCase()}@mdfriday.com`}getPassword(){const e=this.key.replace(/^MDF-/i,"").toLowerCase();return"undefined"!=typeof btoa?btoa(e):"undefined"!=typeof Buffer?Buffer.from(e).toString("base64"):this.manualBase64Encode(e)}manualBase64Encode(e){const t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";let r="",i=0;for(;i<e.length;){const s=e.charCodeAt(i++)<<16|(i<e.length?e.charCodeAt(i++):0)<<8|(i<e.length?e.charCodeAt(i++):0);r+=t.charAt(s>>18&63),r+=t.charAt(s>>12&63),r+=i-1<e.length?t.charAt(s>>6&63):"=",r+=i<e.length?t.charAt(63&s):"="}return r}getKey(){return this.key}getMaskedKey(){const e=this.key.split("-");return 4===e.length?`MDF-••••-••••-${e[3]}`:this.key.slice(0,-4).replace(/./g,"•")+this.key.slice(-4)}getPlan(){return this.plan}getFormattedPlan(){return this.plan.charAt(0).toUpperCase()+this.plan.slice(1).toLowerCase()}getExpiresAt(){return this.expiresAt}getFormattedExpiresAt(){return new Date(this.expiresAt).toLocaleDateString("en-US",{year:"numeric",month:"short",day:"numeric"})}getFeatures(){return{...this.features}}getActivatedAt(){return this.activatedAt}isActivated(){return this.activated}isFirstTime(){return this.firstTime}isTrial(){return"free"===this.plan}equals(e){return this.key===e.key}toJSON(){return{key:this.key,plan:this.plan,expiresAt:this.expiresAt,features:{...this.features},activatedAt:this.activatedAt,activated:this.activated,firstTime:this.firstTime}}toStorageFormat(){return{key:this.key,maskedKey:this.getMaskedKey(),plan:this.getFormattedPlan(),expiresAt:this.expiresAt,features:{...this.features},activatedAt:this.activatedAt,activated:this.activated,firstTime:this.firstTime,isValid:this.isValid(),daysRemaining:this.getDaysRemaining()}}}}}),init_sync_config=__esm({"internal/domain/identity/value-object/sync-config.ts"(){SyncConfig=class e{dbEndpoint;dbName;email;dbPassword;userDir;status;constructor(e){this.dbEndpoint=e.dbEndpoint,this.dbName=e.dbName,this.email=e.email,this.dbPassword=e.dbPassword,this.userDir=e.userDir,this.status=e.status||"active"}static create(t){if(!(t.dbEndpoint&&t.dbName&&t.email&&t.dbPassword))throw new Error("Missing required sync configuration fields");return new e(t)}static fromJSON(t){return e.create(t)}getDbEndpoint(){return this.dbEndpoint}getDbName(){return this.dbName}getEmail(){return this.email}getDbPassword(){return this.dbPassword}getUserDir(){return this.userDir}getStatus(){return this.status}isActive(){return"active"===this.status}getCouchDbUri(){return this.dbEndpoint.replace(`/${this.dbName}`,"")}toJSON(){return{dbEndpoint:this.dbEndpoint,dbName:this.dbName,email:this.email,dbPassword:this.dbPassword,userDir:this.userDir,status:this.status}}toObsidianLiveSyncFormat(){return{couchDB_URI:this.getCouchDbUri(),couchDB_DBNAME:this.dbName,couchDB_USER:this.email,couchDB_PASSWORD:this.dbPassword,encrypt:!0,syncOnStart:!0,syncOnSave:!0,liveSync:!0}}equals(e){return this.dbEndpoint===e.dbEndpoint&&this.dbName===e.dbName&&this.email===e.email}}}}),init_device=__esm({"internal/domain/identity/value-object/device.ts"(){Device=class e{id;name;type;constructor(e,t,r){this.id=e,this.name=t,this.type=r}static create(t,r,i){if(!t||0===t.trim().length)throw new Error("Device ID cannot be empty");if(!r||0===r.trim().length)throw new Error("Device name cannot be empty");return new e(t,r,i)}static async createFromEnvironment(){const t=await e.generateFingerprint(),r=e.getDeviceName(),i=e.getDeviceType();return e.create(t,r,i)}static async generateFingerprint(){const e=[],t=globalThis,r=t.screen;r&&(e.push(`${r.width}x${r.height}`),e.push(`${r.colorDepth}`),e.push(`${r.pixelDepth||0}`));const i=t.navigator;i&&(e.push(i.language||""),e.push(i.platform||""),e.push(String(i.hardwareConcurrency||0)),e.push(String(i.maxTouchPoints||0)));const s=t.process;s&&s.versions&&(e.push(s.platform),e.push(s.arch),e.push(s.version));try{"undefined"!=typeof Intl&&e.push(Intl.DateTimeFormat().resolvedOptions().timeZone||"")}catch{e.push("")}if(i){const t=(i.userAgent||"").split(" ").slice(0,3).join(" ");e.push(t)}const n=e.join("|"),a=(new TextEncoder).encode(n),o=t.crypto;if(o&&o.subtle)try{const e=await o.subtle.digest("SHA-256",a);return Array.from(new Uint8Array(e)).map(e=>e.toString(16).padStart(2,"0")).join("")}catch{}let l=0;for(let e=0;e<n.length;e++)l=(l<<5)-l+n.charCodeAt(e),l&=l;return Math.abs(l).toString(16).padStart(8,"0")}static getDeviceName(){const e=globalThis,t=e.process;if(t&&t.versions){const e=t.platform;let r="Unknown OS";switch(e){case"darwin":r="macOS";break;case"win32":r="Windows";break;case"linux":r="Linux";break;default:r=e}return`Node.js on ${r}`}const r=e.navigator;if(!r)return"Unknown Device";const i=r.userAgent||"";let s="Unknown OS";i.includes("Mac")?s="macOS":i.includes("Windows")?s="Windows":i.includes("Linux")?s="Linux":i.includes("iPhone")||i.includes("iPad")?s="iOS":i.includes("Android")&&(s="Android");let n="Browser";return i.includes("Obsidian")?n="Obsidian":i.includes("Electron")&&(n="Electron"),`${n} on ${s}`}static getDeviceType(){const e=globalThis,t=e.process;if(t&&t.versions)return"desktop";const r=e.navigator;if(!r)return"desktop";const i=r.userAgent||"";return i.includes("Mobile")||i.includes("Android")||i.includes("iPhone")?"mobile":i.includes("Tablet")||i.includes("iPad")?"tablet":"desktop"}getId(){return this.id}getName(){return this.name}getType(){return this.type}equals(e){return this.id===e.id}toJSON(){return{id:this.id,name:this.name,type:this.type}}}}}),init_user=__esm({"internal/domain/identity/entity/user.ts"(){User=class{email;token;serverConfig;license;syncConfig;constructor(e,t,r,i=null,s=null){this.email=e,this.token=t,this.serverConfig=r,this.license=i,this.syncConfig=s}getEmail(){return this.email}getToken(){return this.token}getServerConfig(){return this.serverConfig}getLicense(){return this.license}getSyncConfig(){return this.syncConfig}setToken(e){this.token=e}clearToken(){this.token=null}updateServerConfig(e){this.serverConfig=e}setLicense(e){this.license=e}clearLicense(){this.license=null}setSyncConfig(e){this.syncConfig=e}clearSyncConfig(){this.syncConfig=null}isAuthenticated(){return!!this.token&&this.token.isValid()}isTokenExpired(){return!this.token||this.token.isExpired()}hasValidLicense(){return!!this.license&&this.license.isValid()}isTrialAccount(){return!!this.license&&this.license.isTrial()}getStatus(){const e={isAuthenticated:this.isAuthenticated(),email:this.email.getValue(),serverUrl:this.serverConfig.getApiUrl(),tokenExpired:this.isTokenExpired(),hasToken:null!==this.token,hasLicense:null!==this.license,license:this.license?.getKey(),licenseValid:this.hasValidLicense(),isTrial:this.isTrialAccount(),licensePlan:this.license?.getPlan(),licenseExpires:this.license?.getFormattedExpiresAt(),licenseDaysRemaining:this.license?.getDaysRemaining(),hasSyncConfig:null!==this.syncConfig};return this.syncConfig&&(e.syncConfig={dbEndpoint:this.syncConfig.getDbEndpoint(),dbName:this.syncConfig.getDbName(),email:this.syncConfig.getEmail(),userDir:this.syncConfig.getUserDir(),status:this.syncConfig.getStatus(),isActive:this.syncConfig.isActive()}),e}toJSON(){return{email:this.email.toJSON(),token:this.token?.toJSON()||null,serverConfig:this.serverConfig.toJSON(),license:this.license?.toJSON()||null,syncConfig:this.syncConfig?.toJSON()||null}}}}}),init_user_factory=__esm({"internal/domain/identity/factory/user-factory.ts"(){init_user(),init_email(),init_token(),init_server_config(),init_license(),init_sync_config(),init_device(),init_log(),log71=getDomainLogger("user-factory",{component:"domain"}),UserFactory=class{httpClient;storageProvider;constructor(e){this.httpClient=e.httpClient,this.storageProvider=e.storageProvider}createAnonymous(e){const t=e||ServerConfig.createDefault(),r=Email.create("anonymous@localhost.local");return new User(r,null,t)}async load(){try{const e=await this.storageProvider.loadUserData();if(!e)return log71.debug("No user data found in storage"),null;const t=e.serverConfig||ServerConfig.createDefault(),r=e.email?Email.create(e.email):Email.create("anonymous@localhost.local"),i=new User(r,e.token,t);if(e.license&&i.setLicense(e.license),e.syncConfig){const t=SyncConfig.fromJSON(e.syncConfig);i.setSyncConfig(t)}return log71.debug("User loaded from storage",{email:r.getValue(),hasToken:!!e.token,hasLicense:!!e.license,hasSyncConfig:!!e.syncConfig}),i}catch(e){return log71.error("Failed to load user from storage",e),null}}async save(e){try{const t=await this.storageProvider.loadUserData(),r=e.getToken(),i=e.getLicense(),s=e.getSyncConfig(),n=e.getServerConfig(),a=e.getEmail().getValue(),o={...t||{},...r?{token:r}:{},...i?{license:i}:{},...s?{syncConfig:s}:{},...n?{serverConfig:n}:{},email:a};!i&&t?.license&&(o.license=t.license,log71.debug("Preserved existing license data during save")),!s&&t?.syncConfig&&(o.syncConfig=t.syncConfig,log71.debug("Preserved existing syncConfig data during save")),await this.storageProvider.saveUserData(o),log71.debug("User saved to storage (merged)",{email:a,hasToken:!!o.token,hasLicense:!!o.license,hasSyncConfig:!!o.syncConfig,preservedLicense:!i&&!!t?.license,preservedSyncConfig:!s&&!!t?.syncConfig})}catch(e){throw log71.error("Failed to save user to storage",e),e}}async loadServerConfig(){try{const e=await this.storageProvider.loadUserData();return e?.serverConfig||null}catch(e){return log71.debug("No server config found in storage"),null}}async login(e,t,r){const i=Email.create(e),s=r||ServerConfig.createDefault();log71.info("Attempting login",{email:e});try{const r=`${s.getApiUrl()}/api/login`;log71.info(`Sending login request to: ${r}`),log71.debug(`Login credentials: email=${e}, password=***`);const n=await this.httpClient.postForm(r,{email:e,password:t});if(log71.info(`Login response status: ${n.status}`),log71.debug("Login response data:",n.data),201!==n.status){const e=await n.text();throw log71.error(`Login failed with status ${n.status}: ${e}`),new Error("Invalid credentials")}log71.debug("Response structure:",JSON.stringify(n.data,null,2));const a=n.data.data[0];if(!a)throw log71.error("No token in response data:",n.data),new Error("No token received from server");log71.info(`Token received: ${a.substring(0,20)}...`);const o=Token2.create(a),l=new User(i,o,s);return await this.save(l),log71.info("Login successful",{email:e}),l}catch(e){throw log71.error("Login failed",e),new Error(`Login failed: ${e.message}`)}}async register(e,t,r){const i=Email.create(e),s=r||ServerConfig.createDefault();log71.info("Attempting registration",{email:e});try{const r=await this.httpClient.postForm(`${s.getApiUrl()}/api/user`,{email:e,password:t});if(201!==r.status)throw new Error("Registration failed");const n=r.data.data[0];if(!n)throw new Error("No token received from server");const a=Token2.create(n),o=new User(i,a,s);return await this.save(o),log71.info("Registration successful",{email:e}),o}catch(e){throw log71.error("Registration failed",e),new Error(`Registration failed: ${e.message}`)}}async logout(){try{await this.storageProvider.clearUserData(),log71.info("Logout successful")}catch(e){throw log71.error("Logout failed",e),new Error(`Logout failed: ${e.message}`)}}async updateServerConfig(e,t){try{let r=e.getServerConfig();t.apiUrl&&(r=r.withApiUrl(t.apiUrl)),void 0!==t.websiteUrl&&(r=r.withWebsiteUrl(t.websiteUrl)),e.updateServerConfig(r),await this.save(e),log71.info("Server config updated")}catch(e){throw log71.error("Failed to update server config",e),new Error(`Failed to update server config: ${e.message}`)}}async requestTrialLicense(e,t){const r=t||ServerConfig.createDefault();Email.create(e),log71.info("Requesting trial license",{email:e});try{const t=await this.httpClient.postMultipart(`${r.getApiUrl()}/api/license/trial`,{email:e});if(200!==t.status&&201!==t.status)throw new Error("Trial license request failed");const i=t.data;if(i&&i.data&&i.data.length>0){const e=i.data[0];return log71.info("Trial license granted",{email:e.email,licenseKey:e.license_key}),e}throw new Error("Invalid trial response format")}catch(e){throw log71.error("Failed to request trial license",e),new Error(`Trial license request failed: ${e.message}`)}}async loginWithLicense(e,t){if(!License.isValidFormat(e))throw new Error(`Invalid license key format: ${e}`);const r=License.create(e,"free",Date.now()+864e5,{},Date.now()),i=r.getEmail(),s=r.getPassword();log71.info("Logging in with license key",{licenseKey:e,email:i});const n=await this.login(i,s,t);return n._pendingLicenseKey=e,n}async activateLicense(e,t,r){if(!License.isValidFormat(t))throw new Error(`Invalid license key format: ${t}`);const i=r||await Device.createFromEnvironment();log71.info("Activating license",{licenseKey:t,deviceId:i.getId()});try{const r=e.getToken();if(!r)throw new Error("User must be logged in to activate license");const s=await this.httpClient.postMultipart(`${e.getServerConfig().getApiUrl()}/api/license/activate`,{license_key:t,device_id:i.getId(),device_name:i.getName(),device_type:i.getType()},{Authorization:`Bearer ${r.getValue()}`});if(200!==s.status&&201!==s.status)throw new Error("License activation failed");const n=s.data.data?.[0]||s.data;if(!n.success)throw new Error("License activation unsuccessful");const a={maxDevices:n.features.max_devices,maxIps:n.features.max_ips,syncEnabled:n.features.sync_enabled,syncQuota:n.features.sync_quota,publishEnabled:n.features.publish_enabled,maxSites:n.features.max_sites,maxStorage:n.features.max_storage,customDomain:n.features.custom_domain,customSubDomain:n.features.custom_sub_domain,validityDays:n.features.validity_days},o=License.create(n.license_key,n.plan,n.expires_at,a,Date.now(),n.activated,n.first_time);if(e.setLicense(o),n.sync&&n.features.sync_enabled){const t=SyncConfig.create({dbEndpoint:n.sync.db_endpoint,dbName:n.sync.db_name,email:n.sync.email,dbPassword:n.sync.db_password,userDir:n.user.user_dir,status:n.sync.status});e.setSyncConfig(t),log71.info("Sync configuration saved",{dbName:t.getDbName(),email:t.getEmail(),userDir:t.getUserDir(),status:t.getStatus(),isActive:t.isActive()})}return await this.save(e),log71.info("License activated successfully",{licenseKey:n.license_key,plan:o.getPlan(),expires:o.getFormattedExpiresAt(),activated:n.activated,firstTime:n.first_time,syncEnabled:n.features.sync_enabled,hasSyncConfig:null!==e.getSyncConfig()}),e}catch(e){throw log71.error("Failed to activate license",e),new Error(`License activation failed: ${e.message}`)}}async requestAndActivateTrial(e,t){log71.info("Starting trial flow",{email:e});try{const r=await this.requestTrialLicense(e,t),i=await this.loginWithLicense(r.license_key,t);return await this.activateLicense(i,r.license_key),log71.info("Trial flow completed successfully",{email:e,licenseKey:r.license_key}),i}catch(e){throw log71.error("Trial flow failed",e),new Error(`Trial flow failed: ${e.message}`)}}async refreshTokenIfNeeded(e){const t=e.getToken(),r=e.getLicense();if(!t)return log71.debug("No token to refresh"),e;if(t.isValid()&&!t.isExpired())return log71.debug("Token is still valid, no refresh needed"),e;if(log71.info("Token expired or expiring soon, attempting auto-refresh"),r)try{const t=r.getKey(),i=e.getServerConfig();log71.info("Refreshing token using license",{licenseKey:t});const s=await this.loginWithLicense(t,i);return s.setLicense(r),await this.save(s),log71.info("Token refreshed successfully using license"),s}catch(e){throw log71.error("Failed to refresh token with license",e),new Error(`Failed to refresh token: ${e.message}`)}throw log71.warn("Token expired but no license available for auto-refresh"),new Error("Token expired and cannot be auto-refreshed (no license available)")}async requestWithAutoRefresh(e,t){const r=e.getToken();if(!r)throw new Error("User is not authenticated");try{return await t(r.getValue())}catch(r){const i=r?.message||r?.toString?.()||String(r);if(i.includes("401")||i.includes("Unauthorized")||r?.status&&401===r.status){log71.info("Received 401 error, attempting token refresh");try{const r=(await this.refreshTokenIfNeeded(e)).getToken();if(!r)throw new Error("Failed to refresh token - no token returned");return log71.info("Token refreshed, retrying request"),await t(r.getValue())}catch(e){throw log71.error("Failed to refresh token and retry request",e),new Error(`Request failed with 401, and token refresh failed: ${e.message}`)}}throw r}}async getLicenseUsage(e){const t=e.getLicense();if(!t)throw new Error("No license found for user");const r=t.getKey(),i=e.getServerConfig();return log71.info("Getting license usage",{licenseKey:r}),this.requestWithAutoRefresh(e,async e=>{const t=Date.now(),s=`${i.getApiUrl()}/api/license/usage?key=${r}&_t=${t}`,n=await this.httpClient.get(s,{Authorization:`Bearer ${e}`,"Cache-Control":"no-cache",Pragma:"no-cache"});if(200!==n.status){const e=await n.text();throw log71.error("License usage fetch failed",{status:n.status,text:e}),new Error(`License usage fetch failed: ${n.status}`)}const a=n.data;if(a&&a.data&&a.data.length>0)return a.data[0];throw new Error("Invalid usage response format")})}async getLicenseInfo(e,t){let r=t;if(!r){const t=e.getLicense();if(!t)throw new Error("No license found for user and no license key provided");r=t.getKey()}const i=e.getServerConfig();return log71.info("Getting license info",{licenseKey:r}),this.requestWithAutoRefresh(e,async e=>{const t=Date.now(),s=`${i.getApiUrl()}/api/license/info?key=${r}&_t=${t}`,n=await this.httpClient.get(s,{Authorization:`Bearer ${e}`,"Cache-Control":"no-cache",Pragma:"no-cache"});if(200!==n.status){const e=await n.text();throw log71.error("License info fetch failed",{status:n.status,text:e}),new Error(`License info fetch failed: ${n.status}`)}const a=n.data;if(a&&a.data&&a.data.length>0)return a.data[0];throw new Error("Invalid license info response format")})}async resetUsage(e){const t=e.getLicense();if(!t)throw new Error("No license found for user");const r=t.getKey(),i=e.getServerConfig();return log71.info("Resetting license usage",{licenseKey:r}),this.requestWithAutoRefresh(e,async e=>{const t=`${i.getApiUrl()}/api/license/usage/reset?key=${r}`,s=await this.httpClient.post(t,{},{Authorization:`Bearer ${e}`});if(200!==s.status&&201!==s.status){const e=await s.text();throw log71.error("License usage reset failed",{status:s.status,text:e}),new Error(`Reset failed: ${s.status}`)}return{success:!0}})}async getDomains(e){const t=e.getLicense();if(!t)throw new Error("No license found for user");const r=t.getKey(),i=e.getServerConfig();return log71.info("Getting domains",{licenseKey:r}),this.requestWithAutoRefresh(e,async e=>{const t=`${i.getApiUrl()}/api/license/domains?key=${r}`,s=await this.httpClient.get(t,{Authorization:`Bearer ${e}`});if(200!==s.status){const e=await s.text();return log71.error("Get domains failed",{status:s.status,text:e}),null}const n=s.data;return n&&n.data&&n.data.length>0?n.data[0]:null})}async checkSubdomainAvailability(e,t){const r=e.getLicense();if(!r)throw new Error("No license found for user");const i=r.getKey(),s=e.getServerConfig();return log71.info("Checking subdomain availability",{licenseKey:i,subdomain:t}),this.requestWithAutoRefresh(e,async e=>{const r=`${s.getApiUrl()}/api/license/subdomain/check`,n=await this.httpClient.postMultipart(r,{license_key:i,subdomain:t},{Authorization:`Bearer ${e}`});if(200!==n.status){const e=await n.text();return log71.error("Check subdomain failed",{status:n.status,text:e}),null}const a=n.data;return a&&a.data&&a.data.length>0?a.data[0]:null})}async updateSubdomain(e,t){const r=e.getLicense();if(!r)throw new Error("No license found for user");const i=r.getKey(),s=e.getServerConfig();return log71.info("Updating subdomain",{licenseKey:i,newSubdomain:t}),this.requestWithAutoRefresh(e,async e=>{const r=`${s.getApiUrl()}/api/license/subdomain/update`,n=await this.httpClient.postMultipart(r,{license_key:i,new_subdomain:t},{Authorization:`Bearer ${e}`});if(200!==n.status){const e=await n.text();return log71.error("Update subdomain failed",{status:n.status,text:e}),null}const a=n.data;return a&&a.data&&a.data.length>0?a.data[0]:null})}async checkCustomDomain(e,t){const r=e.getLicense();if(!r)throw new Error("No license found for user");const i=r.getKey(),s=e.getServerConfig();return log71.info("Checking custom domain",{licenseKey:i,domain:t}),this.requestWithAutoRefresh(e,async e=>{const r=`${s.getApiUrl()}/api/license/domain/check`,n=await this.httpClient.postMultipart(r,{license_key:i,domain:t},{Authorization:`Bearer ${e}`});if(200!==n.status){const e=await n.text();return log71.error("Check custom domain failed",{status:n.status,text:e}),null}const a=n.data;return a&&a.data&&a.data.length>0?a.data[0]:null})}async addCustomDomain(e,t){const r=e.getLicense();if(!r)throw new Error("No license found for user");const i=r.getKey(),s=e.getServerConfig();return log71.info("Adding custom domain",{licenseKey:i,domain:t}),this.requestWithAutoRefresh(e,async e=>{const r=`${s.getApiUrl()}/api/license/domain/add`,n=await this.httpClient.postMultipart(r,{license_key:i,domain:t},{Authorization:`Bearer ${e}`});if(200!==n.status&&201!==n.status){const e=await n.text();return log71.error("Add custom domain failed",{status:n.status,text:e}),null}const a=n.data;return a&&a.data&&a.data.length>0?a.data[0]:null})}async checkCustomDomainHttpsStatus(e,t){const r=e.getLicense();if(!r)throw new Error("No license found for user");const i=r.getKey(),s=e.getServerConfig();return log71.info("Checking HTTPS status",{licenseKey:i,domain:t}),this.requestWithAutoRefresh(e,async e=>{const r=`${s.getApiUrl()}/api/license/domain/https-status`,n=await this.httpClient.postMultipart(r,{license_key:i,domain:t},{Authorization:`Bearer ${e}`});if(200!==n.status){const e=await n.text();return log71.error("Check HTTPS status failed",{status:n.status,text:e}),null}const a=n.data;return a&&a.data&&a.data.length>0?a.data[0]:null})}}}}),init_type11=__esm({"internal/domain/identity/type.ts"(){}}),identity_exports={};__export(identity_exports,{Device:()=>Device,Email:()=>Email,License:()=>License,ServerConfig:()=>ServerConfig,SyncConfig:()=>SyncConfig,Token:()=>Token2,User:()=>User,UserFactory:()=>UserFactory});var log72,WorkspaceFactory,init_identity2=__esm({"internal/domain/identity/index.ts"(){init_email(),init_token(),init_server_config(),init_license(),init_sync_config(),init_device(),init_user(),init_user_factory(),init_type11()}});function generateProjectId(e){return`${e.toLowerCase().replace(/\s+/g,"-").replace(/[^a-z0-9-]/g,"")}-${Date.now().toString(36)}`}var log73,WorkspaceAppService,log74,PublisherAggregator,PublishManifest,WorkspacePublishConfig,log75,FtpPublisher,init_workspace_factory=__esm({"internal/domain/workspace/factory/workspace-factory.ts"(){init_workspace(),init_project(),init_authentication(),init_workspace_metadata(),init_project_metadata(),init_folder_structure(),init_log(),log72=getDomainLogger("workspace-factory",{component:"domain"}),WorkspaceFactory=class{workspaceRepo;projectRepo;snapshotRepo;fileSystemRepo;constructor(e){if(this.workspaceRepo=e.workspaceRepo,this.projectRepo=e.projectRepo,this.snapshotRepo=e.snapshotRepo,this.fileSystemRepo=e.fileSystemRepo,!this.fileSystemRepo)throw new Error("FileSystemRepository is required")}async load(e){const t=this.fileSystemRepo.resolvePathSync(e);log72.info("Loading workspace",{path:t});const r=await this.workspaceRepo.loadWorkspaceMetadata(t),i=WorkspaceMetadata.create(r),s=await this.workspaceRepo.loadProjectRegistry(t),n=new Map;for(const e of s.projects)try{const t=await this.projectRepo.loadProjectMetadata(e.absolutePath),r=ProjectMetadata.create(t),i=new Project(e.absolutePath,r,this.fileSystemRepo);n.set(e.id,i),log72.debug("Project loaded",{projectId:e.id,name:e.name})}catch(t){log72.warn("Failed to load project, skipping",{projectId:e.id,path:e.absolutePath,error:t.message})}const a=await this.checkAuthFile(t),o=new Authentication(t,a),l=new Workspace(t,i,n,o,this.fileSystemRepo);return log72.info("Workspace loaded",{workspaceId:l.getId(),name:l.getName(),projectCount:l.getProjectCount()}),l}async checkAuthFile(e){const t=this.fileSystemRepo.join(e,".mdfriday","auth-token.json");try{return await this.fileSystemRepo.access(t),!0}catch{return!1}}async create(e,t={}){const r=this.fileSystemRepo.resolvePathSync(e);if(log72.info("Creating workspace",{path:r}),await this.workspaceRepo.isWorkspace(r))throw new Error(`Workspace already exists at ${r}`);const i=t.modulesDir||"modules",s=t.projectsDir||"projects";await this.workspaceRepo.initWorkspaceStructure(r,i,s);const n=Date.now(),a=WorkspaceMetadata.create({version:"1.0",id:`workspace-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,name:t.name||this.fileSystemRepo.basename(r),createdAt:n,updatedAt:n,paths:{modules:i,projects:s},defaults:{modulesDir:i,language:"en"}});await this.workspaceRepo.saveWorkspaceMetadata(r,a.toJSON()),await this.workspaceRepo.saveProjectRegistry(r,{version:"1.0",projects:[]});const o=this.fileSystemRepo.join(r,".mdfriday"),l=this.fileSystemRepo.join(o,"config.json");await this.fileSystemRepo.writeFile(l,"{}","utf-8");const c=this.fileSystemRepo.join(o,"user-data.json");await this.fileSystemRepo.writeFile(c,"{}","utf-8"),log72.debug("Initialized configuration files",{configPath:l,userDataPath:c});const h=new Authentication(r,!1),u=new Workspace(r,a,new Map,h,this.fileSystemRepo);return log72.info("Workspace created",{workspaceId:u.getId(),name:u.getName()}),u}async save(e){const t=e.getPath();log72.info("Saving workspace",{workspaceId:e.getId(),path:t}),await this.workspaceRepo.saveWorkspaceMetadata(t,e.getMetadata().toJSON());const r=e.getProjectRegistry();await this.workspaceRepo.saveProjectRegistry(t,r);for(const t of e.getProjects())await this.projectRepo.saveProjectMetadata(t.getPath(),t.getMetadata().toJSON());log72.info("Workspace saved",{workspaceId:e.getId(),projectCount:e.getProjectCount()})}async findWorkspaceRoot(e){let t=this.fileSystemRepo.resolvePathSync(e);const r=this.fileSystemRepo.parsePath(t).root;for(;t!==r;){if(await this.workspaceRepo.isWorkspace(t))return t;t=this.fileSystemRepo.dirname(t)}return null}async isWorkspace(e){const t=this.fileSystemRepo.resolvePathSync(e);return this.workspaceRepo.isWorkspace(t)}async loadOrFind(e){const t=e||process.cwd(),r=await this.findWorkspaceRoot(t);if(!r)throw new Error('No workspace found. Run "mdf workspace init" to create one.');return this.load(r)}async createProject(e,t,r={}){const i=generateProjectId(t),s=this.fileSystemRepo.join(e.getProjectsDir(),t);if(log72.info("Creating project",{projectId:i,name:t,path:s}),e.findProject(t))throw new Error(`Project ${t} already exists`);const n=r.contentDir||"content",a=r.staticDir||"static",o=r.publishDir||"public";await this.projectRepo.initProjectStructure(s,n,a,o);const l=Date.now(),c=ProjectMetadata.create({id:i,name:t,type:r.type||"site",workspaceId:e.getId(),createdAt:l,updatedAt:l}),h=r.theme||"https://gohugo.net/quartz-theme.zip?version=1.2",u={baseURL:r.baseURL||"/",title:t,contentDir:n,publishDir:o,defaultContentLanguage:r.language||"en",module:{imports:[{path:h}]}};await this.projectRepo.saveProjectMetadata(s,c.toJSON()),await this.projectRepo.saveProjectConfig(s,u);const g=this.fileSystemRepo.join(s,n,"index.md");await this.projectRepo.createSampleContent(g,this.createSampleContent());const d=new Project(s,c,this.fileSystemRepo);return e.addProject(d),await this.save(e),log72.info("Project created",{projectId:i,name:t}),d}async deleteProject(e,t,r={}){const i=e.findProject(t);if(!i)throw new Error(`Project not found: ${t}`);log72.info("Deleting project",{projectId:i.getId(),name:i.getName(),deleteFiles:r.deleteFiles}),e.removeProject(i.getId()),await this.save(e),r.deleteFiles&&(await this.projectRepo.deleteProjectFiles(i.getPath()),log72.info("Project files deleted",{projectId:i.getId()})),log72.info("Project deleted",{projectId:i.getId(),name:i.getName()})}async createProjectFromFolder(e,t,r,i={}){if(!this.fileSystemRepo)throw new Error("FileSystemRepository is required to create project from folder");const s=generateProjectId(t),n=this.fileSystemRepo.join(e.getProjectsDir(),t);if(log72.info("Creating project from folder",{projectId:s,name:t,sourcePath:r,targetPath:n}),e.findProject(t))throw new Error(`Project ${t} already exists`);const a=await this.fileSystemRepo.scanFolderStructure(r),o=FolderStructure.fromScanResult(a);let l;log72.debug("Scanned folder structure",{isStructured:o.getIsStructured(),contentFolders:o.getContentFolderCount(),hasStatic:o.hasStaticFolder()}),o.getIsStructured()&&0!==o.getContentFolderCount()?l=o:(log72.info("No standard structure found, treating source folder as content directory"),l=FolderStructure.createSingleContent(r,r,i.language||"en")),await this.projectRepo.initProjectStructure(n,"content","static","public");const c=[],h=[];for(const e of l.getContentFolders()){const t=0===e.weight?this.fileSystemRepo.join(n,"content"):this.fileSystemRepo.join(n,`content.${e.languageCode}`);c.push({source:e.path,target:t}),h.push({sourcePath:e.path,languageCode:e.languageCode,weight:e.weight})}let u=null;if(l.hasStaticFolder()){const e=l.getStaticFolder();c.push({source:e.path,target:this.fileSystemRepo.join(n,"static")}),u={sourcePath:e.path}}const g=(await this.fileSystemRepo.createSymlinks(c)).filter(e=>!e.success);if(g.length>0)throw log72.error("Some symlinks failed to create",{failed:g}),new Error(`Failed to create symlinks: ${g.map(e=>e.error).join(", ")}`);const d=Date.now(),p=ProjectMetadata.create({id:s,name:t,type:i.type||"site",workspaceId:e.getId(),createdAt:d,updatedAt:d,contentLinks:h,staticLink:u}),m=i.theme||"https://gohugo.net/quartz-theme.zip?version=1.2",f={baseURL:"/",title:t,contentDir:"content",publishDir:"public",defaultContentLanguage:l.getDefaultContentFolder()?.languageCode||i.language||"en",module:{imports:[{path:m}]}};if(l.hasContentFolders()){const e={};for(const t of l.getContentFolders()){const r=0===t.weight?"content":`content.${t.languageCode}`;e[t.languageCode]={contentDir:r,weight:t.weight+1}}f.languages=e}await this.projectRepo.saveProjectMetadata(n,p.toJSON()),await this.projectRepo.saveProjectConfig(n,f);const y=new Project(n,p,this.fileSystemRepo);return e.addProject(y),await this.save(e),log72.info("Project created from folder",{projectId:s,name:t,linkedContentFolders:h.length,hasStaticLink:null!==u}),y}async createProjectFromFile(e,t,r,i={}){if(!this.fileSystemRepo)throw new Error("FileSystemRepository is required to create project from file");const s=generateProjectId(t),n=this.fileSystemRepo.join(e.getProjectsDir(),t);if(log72.info("Creating project from file",{projectId:s,name:t,sourceFile:r,targetPath:n}),e.findProject(t))throw new Error(`Project ${t} already exists`);if(!await this.fileSystemRepo.exists(r))throw new Error(`Source file not found: ${r}`);if(!(await this.fileSystemRepo.stat(r)).isFile())throw new Error(`Source path is not a file: ${r}`);await this.projectRepo.initProjectStructure(n,"content","static","public");const a=this.fileSystemRepo.join(n,"content"),o=this.fileSystemRepo.join(a,"index.md");let l=!1,c=null;try{await this.fileSystemRepo.exists(a)&&await this.fileSystemRepo.remove(a,!0),await this.fileSystemRepo.createDirectory(a,!0);const e=await this.fileSystemRepo.createSymlink(r,o);if(!e.success)throw new Error(e.error||"Failed to create symlink");l=!0,c={source:r,target:o},log72.info("Created symlink for file",{source:r,target:o})}catch(e){log72.warn("Symlink creation failed, falling back to file copy",{error:e});try{await this.fileSystemRepo.copyFile(r,o),l=!1,c={source:r,target:o},log72.info("Copied file as fallback",{source:r,target:o,isSymlink:!1})}catch(e){throw log72.error("Failed to copy file",e),new Error(`Failed to create file link or copy: ${e.message}`)}}const h=Date.now(),u=ProjectMetadata.create({id:s,name:t,type:i.type||"site",workspaceId:e.getId(),createdAt:h,updatedAt:h,fileLink:c?{sourcePath:c.source,targetPath:c.target,isSymlink:l}:null}),g=i.theme||"https://gohugo.net/note.zip?version=1.2",d={baseURL:"/",title:t,contentDir:"content",publishDir:"public",defaultContentLanguage:i.language||"en",module:{imports:[{path:g}]}};await this.projectRepo.saveProjectMetadata(n,u.toJSON()),await this.projectRepo.saveProjectConfig(n,d);const p=new Project(n,u,this.fileSystemRepo);return e.addProject(p),await this.save(e),log72.info("Project created from file",{projectId:s,name:t,sourceFile:r,useSymlink:l}),p}async loadProject(e){const t=this.fileSystemRepo.resolvePathSync(e);if(!await this.projectRepo.isProject(t))throw new Error(`No project found at ${t}`);const r=await this.projectRepo.loadProjectMetadata(t),{ProjectMetadata:i}=await Promise.resolve().then(()=>(init_project_metadata(),project_metadata_exports)),s=i.create(r);return new Project(t,s,this.fileSystemRepo)}async saveProject(e){const t=e.getPath();await this.projectRepo.saveProjectMetadata(t,e.getMetadata().toJSON()),e.getConfig()&&await e.saveConfig(),log72.debug(`Saved project: ${e.getName()}`)}async findProjectRoot(e){let t=this.fileSystemRepo.resolvePathSync(e);const r=this.fileSystemRepo.parsePath(t).root;for(;t!==r;){if(await this.projectRepo.isProject(t))return t;t=this.fileSystemRepo.dirname(t)}return null}async createSnapshot(e,t){const r=e.getPath(),i=await e.getPublishDir(),s=`${(new Date).toISOString().replace(/[:.]/g,"-").split(".")[0]}Z`;log72.info("Creating snapshot",{projectId:e.getId(),snapshotId:s});const n=await this.snapshotRepo.createSnapshot(r,s,i);if(t&&t!==n.id){if(!this.fileSystemRepo)throw new Error("FileSystemRepository is required to update snapshot metadata");n.name=t;const r=this.fileSystemRepo.join(e.getPath(),".mdfriday","snapshots",`${n.id}.json`);await this.fileSystemRepo.writeFile(r,JSON.stringify(n,null,2))}return log72.info("Snapshot created",{snapshotId:s,size:n.size,fileCount:n.fileCount}),n}async listSnapshots(e){return(await this.snapshotRepo.listSnapshots(e.getPath())).sort((e,t)=>t.timestamp-e.timestamp)}async restoreSnapshot(e,t,r){const i=r||await e.getPublishDir();await this.snapshotRepo.restoreSnapshot(e.getPath(),t,i)}async deleteSnapshot(e,t){await this.snapshotRepo.deleteSnapshot(e.getPath(),t)}async getSnapshot(e,t){return await this.snapshotRepo.getSnapshot(e.getPath(),t)}createIdentityStorage(e){const t=e.getPath(),r=e.getAuthentication(),i=this.fileSystemRepo;if(!i)throw new Error("FileSystemRepository is required for identity storage");return{async saveUserData(e){const s=i.join(t,".mdfriday","user-data.json");await i.createDirectory(i.dirname(s),!0);const n={};e.serverConfig&&(n.serverConfig=e.serverConfig.toJSON()),e.token&&(n.token=e.token.toJSON(),r.markAuthExists()),e.license&&(n.license=e.license.toJSON()),e.syncConfig&&(n.syncConfig=e.syncConfig.toJSON()),e.email&&(n.email=e.email),await i.writeFile(s,JSON.stringify(n,null,2))},async loadUserData(){const e=i.join(t,".mdfriday","user-data.json");try{const t=await i.readFile(e,"utf-8"),r=JSON.parse(t),{Token:s,ServerConfig:n,License:a,SyncConfig:o}=await Promise.resolve().then(()=>(init_identity2(),identity_exports)),l={};return r.serverConfig&&(l.serverConfig=n.create(r.serverConfig.apiUrl,r.serverConfig.websiteUrl)),r.token&&(l.token=s.create(r.token.token||r.token.value,r.token.expiresAt)),r.license&&(l.license=a.create(r.license.key,r.license.plan,r.license.expiresAt,r.license.features,r.license.activatedAt,r.license.activated,r.license.firstTime)),r.syncConfig&&(l.syncConfig=o.fromJSON(r.syncConfig)),r.email&&(l.email=r.email),l}catch{return null}},async clearUserData(){const e=i.join(t,".mdfriday","user-data.json");try{await i.unlink(e)}catch{}r.markAuthDeleted()}}}async setupBaseURLStructure(e){if(!this.fileSystemRepo)throw new Error("FileSystemRepository is required for baseURL structure");const t=await e.getBaseURL(),r=e.parseBaseURLPath(t),i=e.getPath(),s=this.fileSystemRepo.join(i,"public");if(r.isRoot)return log72.debug("baseURL is root, no structure needed"),{serverRoot:s,baseURL:"/",symlinkCreated:!1};log72.info("Creating baseURL structure in public/",{baseURL:t,pathParts:r.pathParts});let n=s;for(const e of r.parentParts)n=this.fileSystemRepo.join(n,e),await this.fileSystemRepo.exists(n)||(await this.fileSystemRepo.createDirectory(n,!1),log72.debug(`Created parent directory: ${e}`));const a=this.fileSystemRepo.join(n,r.finalDirName);await this.fileSystemRepo.exists(a)&&(await this.fileSystemRepo.remove(a,!0),log72.debug(`Removed existing symlink: ${a}`));const o=await this.fileSystemRepo.createSymlink(r.relativeToPublic,a);if(!o.success)throw log72.error("Failed to create baseURL symlink",{target:r.relativeToPublic,link:a,error:o.error}),new Error(`Failed to create baseURL structure: ${o.error}`);return log72.info("baseURL structure created successfully",{symlinkPath:r.pathParts.join("/"),target:r.relativeToPublic}),e.updateBaseURLStructure({baseURL:t,createdAt:Date.now(),pathParts:r.pathParts}),await this.projectRepo.saveProjectMetadata(e.getPath(),e.getMetadata().toJSON()),{serverRoot:s,baseURL:t,symlinkCreated:!0}}async cleanBaseURLStructure(e){if(!this.fileSystemRepo)return;const t=e.getBaseURLStructure();if(!t||0===t.pathParts.length)return;const r=e.getPath(),i=this.fileSystemRepo.join(r,"public");log72.info("Cleaning baseURL structure in public/",{pathParts:t.pathParts});for(let e=t.pathParts.length;e>0;e--){const r=this.fileSystemRepo.join(i,...t.pathParts.slice(0,e));if(await this.fileSystemRepo.exists(r)&&(await this.fileSystemRepo.remove(r,!0),log72.debug(`Removed: ${t.pathParts.slice(0,e).join("/")}`)),e>1){const r=this.fileSystemRepo.join(i,...t.pathParts.slice(0,e-1));if(await this.fileSystemRepo.exists(r)&&(await this.fileSystemRepo.readDirectory(r)).length>0)break}}e.updateBaseURLStructure(null),await this.projectRepo.saveProjectMetadata(e.getPath(),e.getMetadata().toJSON()),log72.info("baseURL structure cleaned")}async ensureBaseURLStructure(e){const t=await e.getBaseURL(),r=e.getBaseURLStructure();return r&&r.baseURL===t?{serverRoot:this.fileSystemRepo.join(e.getPath(),"public"),baseURL:t,recreated:!1}:(r&&(log72.info("baseURL changed, recreating structure",{old:r.baseURL,new:t}),await this.cleanBaseURLStructure(e)),{...await this.setupBaseURLStructure(e),recreated:!0})}async scanFolderStructure(e){if(!this.fileSystemRepo)throw new Error("FileSystemRepository is required to scan folder structure");log72.info("Scanning folder structure",{path:e});const t=await this.fileSystemRepo.scanFolderStructure(e),r=FolderStructure.fromScanResult(t);return log72.debug("Folder structure scanned",{isStructured:r.getIsStructured(),contentFolders:r.getContentFolderCount(),hasStatic:r.hasStaticFolder(),languages:r.getSupportedLanguages()}),r}createSampleContent(){return`---\ntitle: Welcome to MDFriday\ndate: ${(new Date).toISOString()}\n---\n\n# Welcome to MDFriday\n\nThis is a sample page. Edit this file to get started!\n\n## Features\n\n- **Markdown Support**: Write content in Markdown\n- **Themes**: Beautiful themes out of the box\n- **Fast**: Static site generation for speed\n- **Flexible**: Customize everything\n\n## Getting Started\n\n1. Edit files in the \`content/\` directory\n2. Run \`mdf serve\` to preview\n3. Run \`mdf build\` to generate your site\n`}}}}),init_workspace2=__esm({"internal/domain/workspace/index.ts"(){init_type10(),init_workspace_metadata(),init_project_metadata(),init_folder_structure(),init_repository(),init_workspace(),init_project(),init_authentication(),init_workspace_factory()}}),init_workspace3=__esm({"internal/application/workspace.ts"(){init_log(),log73=getDomainLogger("workspace-app",{component:"application"}),WorkspaceAppService=class{workspaceFactory;constructor(e){this.workspaceFactory=e.workspaceFactory}async loadWorkspace(e){return e?this.workspaceFactory.load(e):this.workspaceFactory.loadOrFind()}async createWorkspace(e,t){return this.workspaceFactory.create(e,t)}async saveWorkspace(e){return this.workspaceFactory.save(e)}async findWorkspaceRoot(e){return this.workspaceFactory.findWorkspaceRoot(e||process.cwd())}async createProject(e,t,r){return this.workspaceFactory.createProject(e,t,r)}async createProjectFromFolder(e,t,r,i){return this.workspaceFactory.createProjectFromFolder(e,t,r,i)}async createProjectFromFile(e,t,r,i){return this.workspaceFactory.createProjectFromFile(e,t,r,i)}async deleteProject(e,t,r){return this.workspaceFactory.deleteProject(e,t,r)}async loadWorkspaceAndProject(e,t){const r=await this.loadWorkspace(t);let i;if(e){if(i=r.findProject(e),!i){const t=r.getProjects(),s=this.workspaceFactory.fileSystemRepo;if(s){const r=s.resolvePathSync(e);for(const e of t){const t=e.getPath();if(r.startsWith(t)||t===r){i=e;break}try{const n=await s.resolvePath(r),a=await s.resolvePath(t);if(n.startsWith(a)||a===n){i=e;break}}catch(e){}}}else i=void 0;if(!i)throw new Error(`Project not found: ${e}`)}}else{const e=process.cwd(),t=r.getProjects(),s=this.workspaceFactory.fileSystemRepo;if(s)for(const r of t){const t=r.getPath();if(e.startsWith(t)){i=r;break}try{const n=await s.resolvePath(e),a=await s.resolvePath(t);if(n.startsWith(a)){i=r;break}}catch(e){}}if(i||1!==t.length||(i=t[0]),!i){if(0===t.length)throw new Error("No projects found in workspace");throw new Error(`Project not found in current directory: ${e}\nPlease specify a project name with --project <name>`)}}return log73.debug("Loaded workspace and project",{workspaceId:r.getId(),projectId:i.getId(),projectName:i.getName()}),{workspace:r,project:i}}async createSnapshot(e,t){return this.workspaceFactory.createSnapshot(e,t)}async listSnapshots(e){return this.workspaceFactory.listSnapshots(e)}async restoreSnapshot(e,t,r){return this.workspaceFactory.restoreSnapshot(e,t,r)}async deleteSnapshot(e,t){return this.workspaceFactory.deleteSnapshot(e,t)}async getSnapshot(e,t){return this.workspaceFactory.getSnapshot(e,t)}async loadProject(e){return this.workspaceFactory.loadProject(e)}async saveProject(e){return this.workspaceFactory.saveProject(e)}async findProjectRoot(e){return this.workspaceFactory.findProjectRoot(e)}async scanFolderStructure(e){return this.workspaceFactory.scanFolderStructure(e)}createIdentityStorage(e){return this.workspaceFactory.createIdentityStorage(e)}async setupProjectBaseURLStructure(e){return this.workspaceFactory.setupBaseURLStructure(e)}async cleanProjectBaseURLStructure(e){return this.workspaceFactory.cleanBaseURLStructure(e)}async ensureProjectBaseURLStructure(e){return this.workspaceFactory.ensureBaseURLStructure(e)}}}}),init_type12=__esm({"internal/domain/publish/type.ts"(){}}),init_publisher3=__esm({"internal/domain/publish/entity/publisher.ts"(){init_log(),log74=getDomainLogger("publisher-aggregator",{component:"domain"}),PublisherAggregator=class{constructor(e,t,r,i,s){this.projectId=e,this.projectPath=t,this.config=r,this.strategy=i,this.manifestRepo=s}async publish(e,t){const r=Date.now(),i=!1!==t?.incremental&&!t?.force;log74.info(`Publishing project: ${this.projectId}`,{type:this.config.type,incremental:i,force:t?.force});try{t?.onProgress?.({phase:"scanning",percentage:5,message:"Scanning files..."});const s=await this.manifestRepo.generateManifest(this.projectId,e,this.config.type,this.getRemoteConfig());log74.debug(`Scanned ${s.getFileCount()} files`);const n=i?await this.manifestRepo.loadManifest(this.projectPath,this.config.type):null;let a=[],o=[];if(n){if(a=n.getChangedFiles(s),o=n.getDeletedFiles(s),log74.info(`Incremental: ${a.length} changed, ${o.length} deleted`),0===a.length&&0===o.length)return log74.info("No changes detected"),{success:!0,filesUploaded:0,bytesTransferred:0,duration:Date.now()-r}}else a=s.getAllFiles(),log74.info(`Full publish: ${a.length} files`);const l=await this.strategy.publish(e,{...t,incremental:null!==n});return l.success&&(await this.manifestRepo.saveManifest(this.projectPath,s),log74.info("Manifest saved")),l}catch(e){throw log74.error("Publish failed",e),e}}async testConnection(){return this.strategy.testConnection?await this.strategy.testConnection():{success:!0}}getConfig(){return this.config}getType(){return this.config.type}getProjectId(){return this.projectId}getProjectPath(){return this.projectPath}getRemoteConfig(){if("ftp"===this.config.type)return{host:this.config.host,remotePath:this.config.remotePath}}}}}),init_publish_manifest=__esm({"internal/domain/publish/value-object/publish-manifest.ts"(){PublishManifest=class e{projectId;publishMethod;lastPublishTime;files;remoteConfig;constructor(e){this.projectId=e.projectId,this.publishMethod=e.publishMethod,this.lastPublishTime=e.lastPublishTime,this.remoteConfig=e.remoteConfig,e.files instanceof Map?this.files=e.files:this.files=new Map(Object.entries(e.files))}getProjectId(){return this.projectId}getPublishMethod(){return this.publishMethod}getLastPublishTime(){return this.lastPublishTime}getRemoteConfig(){return this.remoteConfig}getAllFiles(){return Array.from(this.files.keys())}getFile(e){return this.files.get(e)}hasFile(e){return this.files.has(e)}getFileCount(){return this.files.size}getChangedFiles(e){const t=[];for(const[r,i]of e.files.entries()){const e=this.files.get(r);e&&e.hash===i.hash||t.push(r)}return t}getDeletedFiles(e){const t=[];for(const r of this.files.keys())e.files.has(r)||t.push(r);return t}toJSON(){const e={};for(const[t,r]of this.files.entries())e[t]=r;return{projectId:this.projectId,publishMethod:this.publishMethod,lastPublishTime:this.lastPublishTime,remoteConfig:this.remoteConfig,files:e}}static fromJSON(t){return new e({projectId:t.projectId,publishMethod:t.publishMethod,lastPublishTime:t.lastPublishTime,remoteConfig:t.remoteConfig,files:t.files||{}})}static create(t){return new e({...t,lastPublishTime:Date.now()})}}}}),init_publish_config=__esm({"internal/domain/publish/value-object/publish-config.ts"(){WorkspacePublishConfig=class e{ftp;netlify;mdfriday;constructor(e){e.ftp&&(this.ftp=e.ftp),e.netlify&&(this.netlify=e.netlify),e.mdfriday&&(this.mdfriday=e.mdfriday)}hasFTP(){return!!this.ftp&&!!this.ftp.host&&!!this.ftp.username}hasNetlify(){return!!this.netlify&&!!this.netlify.accessToken&&!!this.netlify.siteId}hasMDFriday(){return!!this.mdfriday&&!0===this.mdfriday.enabled}getFTPConfig(){return this.hasFTP()?this.ftp:null}getNetlifyConfig(){return this.hasNetlify()?this.netlify:null}getMDFridayConfig(){return this.hasMDFriday()?this.mdfriday:null}static fromGlobalConfig(t){const r=t?.publish||{};return new e({ftp:r.ftp,netlify:r.netlify,mdfriday:r.mdfriday})}merge(t,r){const i={};switch(this.ftp&&(i.ftp=this.ftp),this.netlify&&(i.netlify=this.netlify),this.mdfriday&&(i.mdfriday=this.mdfriday),r){case"ftp":this.ftp&&(i.ftp={...this.ftp,...t});break;case"netlify":this.netlify&&(i.netlify={...this.netlify,...t});break;case"mdfriday":this.mdfriday&&(i.mdfriday={...this.mdfriday,...t})}return new e(i)}}}});import*as ftp from"basic-ftp";import path32 from"path";import{promises as fs5}from"fs";var log76,NetlifyPublisher,init_ftp_publisher=__esm({"internal/domain/publish/value-object/ftp-publisher.ts"(){init_log(),log75=getDomainLogger("ftp-publisher",{component:"domain"}),FtpPublisher=class{constructor(e,t,r,i){this.config=e,this.manifestRepo=t,this.projectId=r,this.projectPath=i}async publish(e,t){const r=Date.now();let i=0,s=0;const n=new ftp.Client;n.ftp.ipFamily=4,n.ftp.verbose=!1;try{t?.onProgress?.({phase:"scanning",percentage:0,message:"Connecting to FTP server..."});const a=await this.connectWithFallback(n);if(log75.info(`Connected to FTP: ${this.config.host} (${a.usedSecure?"FTPS":"FTP"})`),this.config.remotePath&&"/"!==this.config.remotePath)try{await n.cd(this.config.remotePath)}catch(e){await n.ensureDir(this.config.remotePath),await n.cd(this.config.remotePath)}const{changedFiles:o,deletedFiles:l}=await this.getFileLists(e,t?.incremental),c=o.length+l.length;let h=0;t?.onProgress?.({phase:"uploading",percentage:10,message:`Uploading ${o.length} file(s)...`,filesCompleted:0,filesTotal:c});const u=new Set;for(const r of o){const a=path32.join(e,r),o=this.config.remotePath&&"/"!==this.config.remotePath?`${this.config.remotePath}/${r}`.replace(/\\/g,"/"):r.replace(/\\/g,"/");try{const e=path32.dirname(o).replace(/\\/g,"/");if(e&&"."!==e&&"/"!==e&&!u.has(e))try{await n.ensureDir(e),u.add(e)}catch(t){log75.warn(`Failed to ensure directory ${e}`,t),log75.warn("Will attempt upload anyway...")}await this.uploadFileWithRetry(n,a,o,r,2),s+=(await fs5.stat(a)).size,i++,h++;const l=10+Math.floor(h/c*80);t?.onProgress?.({phase:"uploading",percentage:l,message:"Uploading files...",currentFile:r,filesCompleted:h,filesTotal:c,bytesTransferred:s}),log75.debug(`Uploaded: ${r}`)}catch(e){throw log75.error(`Failed to upload: ${r}`,e),new Error(`Failed to upload ${r}: ${e.message}`)}}if(l.length>0){t?.onProgress?.({phase:"uploading",percentage:90,message:`Deleting ${l.length} file(s)...`,filesCompleted:h,filesTotal:c});for(const e of l){const r=this.config.remotePath&&"/"!==this.config.remotePath?`${this.config.remotePath}/${e}`.replace(/\\/g,"/"):e.replace(/\\/g,"/");try{await n.remove(r),h++,t?.onProgress?.({phase:"uploading",percentage:90+Math.floor((h-o.length)/l.length*10),message:"Deleting files...",currentFile:e,filesCompleted:h,filesTotal:c}),log75.debug(`Deleted: ${e}`)}catch(t){log75.warn(`Failed to delete: ${e}`,t)}}}t?.onProgress?.({phase:"complete",percentage:100,message:"Upload complete!",filesCompleted:h,filesTotal:c});const g=Date.now()-r;return{success:!0,url:`${this.config.secure?"ftps":"ftp"}://${this.config.host}${this.config.remotePath}`,filesUploaded:i,bytesTransferred:s,duration:g}}catch(e){return log75.error("FTP publish failed",e),{success:!1,filesUploaded:i,bytesTransferred:s,duration:Date.now()-r,error:e.message}}finally{n.close()}}async testConnection(){const e=new ftp.Client;e.ftp.ipFamily=4,e.ftp.verbose=!1;try{return await this.connectWithFallback(e),e.close(),{success:!0}}catch(e){return{success:!1,error:e.message}}}getConfig(){return this.config}getType(){return"ftp"}async connectWithFallback(e){try{return await e.access({host:this.config.host,port:this.config.port,user:this.config.username,password:this.config.password,secure:!1}),{usedSecure:!1}}catch(t){log75.warn("Plain FTP failed, trying FTPS...");try{e.close();const t=new ftp.Client;return t.ftp.ipFamily=4,t.ftp.verbose=!1,await t.access({host:this.config.host,port:this.config.port,user:this.config.username,password:this.config.password,secure:!0,secureOptions:{rejectUnauthorized:!this.config.secure}}),Object.assign(e,t),{usedSecure:!0}}catch(e){throw log75.error("Both plain FTP and FTPS failed"),t}}}async uploadFileWithRetry(e,t,r,i,s=2){let n=null;for(let a=1;a<=s;a++)try{try{await e.remove(r)}catch(e){}return void await e.uploadFrom(t,r)}catch(e){if(n=e,!(a<s))throw log75.error(`All upload attempts failed for ${i}`),n;{log75.warn(`Upload attempt ${a}/${s} failed for ${i}, retrying...`),log75.warn(`Error: ${n.message}`);const e=1e3*a;await new Promise(t=>setTimeout(t,e))}}throw n||new Error("Upload failed with unknown error")}async getFileLists(e,t){const r=await this.manifestRepo.generateManifest(this.projectId,e,"ftp",{host:this.config.host,remotePath:this.config.remotePath});if(!t)return{changedFiles:r.getAllFiles(),deletedFiles:[]};const i=await this.manifestRepo.loadManifest(this.projectPath,"ftp");return i?{changedFiles:i.getChangedFiles(r),deletedFiles:i.getDeletedFiles(r)}:{changedFiles:r.getAllFiles(),deletedFiles:[]}}}}});import path33 from"path";import{promises as fs6}from"fs";var log77,MDFridayPublisher,init_netlify_publisher=__esm({"internal/domain/publish/value-object/netlify-publisher.ts"(){init_log(),log76=getDomainLogger("netlify-publisher",{component:"domain"}),NetlifyPublisher=class{constructor(e,t,r,i,s){this.config=e,this.manifestRepo=t,this.httpClient=r,this.projectId=i,this.projectPath=s}async publish(e,t){const r=Date.now();let i=0,s=0;try{log76.info(`Starting Netlify digest deployment from: ${e}`),log76.info("Incremental mode: "+(t?.incremental?"enabled":"disabled")),t?.onProgress?.({phase:"scanning",percentage:5,message:"Scanning files..."});const{changedFiles:n,unchangedFiles:a}=await this.getFileLists(e,t?.incremental),o=n.length;if(log76.info(`Files to upload: ${n.length}, unchanged: ${a.length}`),t?.onProgress?.({phase:"scanning",percentage:20,message:`Scanned ${o} files`}),0===n.length)return log76.info("No files to upload, deployment skipped"),{success:!0,url:await this.getSiteUrl(),filesUploaded:0,bytesTransferred:0,duration:Date.now()-r};t?.onProgress?.({phase:"uploading",percentage:25,message:"Creating deploy..."});const l=await this.manifestRepo.generateManifest(this.projectId,e,"netlify",{siteId:this.config.siteId}),c=l.getAllFiles();log76.info(`Sending ${c.length} files to Netlify (changed: ${n.length}, unchanged: ${a.length})`);const{deployId:h,requiredFiles:u,hashToPath:g}=await this.createDeployWithDigests(l,c);if(log76.info(`Deploy created: ${h}`),log76.info(`Required files: ${u.length}/${c.length} (${c.length-u.length} cached on CDN)`),u.length>0){t?.onProgress?.({phase:"uploading",percentage:30,message:`Uploading ${u.length} file(s)...`});const r=await this.uploadRequiredFiles(e,h,u,l,(e,r)=>{i=e;const s=30+Math.floor(e/r*60);t?.onProgress?.({phase:"uploading",percentage:s,message:"Uploading files...",filesCompleted:e,filesTotal:r})});s=r.bytesTransferred,i=r.filesUploaded}else log76.info("All files are cached on Netlify CDN, no upload needed");t?.onProgress?.({phase:"deploying",percentage:90,message:"Deploying..."});try{await this.waitForDeployment(h)}catch(e){log76.warn("Failed to confirm deployment status, but upload was successful",e)}const d=await this.getSiteUrl();t?.onProgress?.({phase:"complete",percentage:100,message:"Deployment complete!"});const p=Date.now()-r;return log76.info(`Deployment successful: ${d}`),log76.info(`Uploaded ${i} files (${this.formatBytes(s)})`),{success:!0,url:d,filesUploaded:i,bytesTransferred:s,duration:p}}catch(e){log76.error("Netlify deployment failed",e);const t=Date.now()-r;let n=e.message;return n.includes("401")||n.includes("Unauthorized")?n="Invalid Netlify access token. Please check your configuration.":n.includes("404")||n.includes("Not Found")?n="Netlify site not found. Please check your site ID.":(n.includes("network")||n.includes("CORS"))&&(n="Network error. Please check your internet connection."),{success:!1,filesUploaded:i,bytesTransferred:s,duration:t,error:n}}}async testConnection(){try{return await this.getSiteUrl(),{success:!0}}catch(e){return{success:!1,error:e.message}}}getConfig(){return this.config}getType(){return"netlify"}async getFileLists(e,t){const r=await this.manifestRepo.generateManifest(this.projectId,e,"netlify",{siteId:this.config.siteId});if(!t)return{changedFiles:r.getAllFiles(),unchangedFiles:[]};const i=await this.manifestRepo.loadManifest(this.projectPath,"netlify");if(!i)return{changedFiles:r.getAllFiles(),unchangedFiles:[]};const s=i.getChangedFiles(r),n=r.getAllFiles().filter(e=>!s.includes(e));return{changedFiles:s,unchangedFiles:n}}async createDeployWithDigests(e,t){log76.info(`Creating deploy with ${t.length} file digests...`);const r={},i=new Map;for(const s of t){const t=e.getFile(s);t&&(r[s]=t.hash,i.set(t.hash,s))}log76.debug(`Built hash to path mapping for ${i.size} files`);const s=await this.httpClient.postJSON(`https://api.netlify.com/api/v1/sites/${this.config.siteId}/deploys`,{files:r},{Authorization:`Bearer ${this.config.accessToken}`});if(!s.ok){const e=await s.text();throw log76.error(`Create deploy failed: ${s.status} - ${e}`),new Error(`Create deploy failed: ${s.status} - ${e}`)}const n=s.data,a=n.id,o=n.required||[];log76.debug(`Netlify returned ${o.length} required hashes`);const l=[];for(const e of o){const t=i.get(e);t?l.push(t):log76.warn(`Hash not found in mapping: ${e}`)}return log76.info(`Resolved ${l.length} file paths from ${o.length} hashes`),{deployId:a,requiredFiles:l,hashToPath:i}}async uploadRequiredFiles(e,t,r,i,s){let n=0,a=0;for(const o of r){const l=i.getFile(o);if(!l){log76.warn(`File not found in manifest: ${o}`);continue}const c=path33.join(e,o);try{const e=await fs6.readFile(c);await this.uploadFileWithRetry(t,o,e,l.hash),n++,a+=l.size,s?.(n,r.length),log76.debug(`Uploaded ${n}/${r.length}: ${o}`)}catch(e){throw log76.error(`Failed to upload file: ${o}`,e),e}}return log76.info(`Upload complete: ${n} files, ${this.formatBytes(a)}`),{filesUploaded:n,bytesTransferred:a}}async uploadFileWithRetry(e,t,r,i,s=2){let n=null;for(let a=1;a<=s;a++)try{const s=t.split("/").map(encodeURIComponent).join("/"),n=await this.httpClient.putBinary(`https://api.netlify.com/api/v1/deploys/${e}/files/${s}`,r,{Authorization:`Bearer ${this.config.accessToken}`});if(!n.ok){const e=await n.text();throw new Error(`Upload failed (${n.status}): ${e}`)}const a=n.data,o=(a.sha||a.SHA||"").toLowerCase();if(o!==i.toLowerCase())throw new Error(`SHA1 mismatch: expected ${i}, got ${o}`);return}catch(e){if(n=e,!(a<s))throw log76.error(`All upload attempts failed for ${t}`),n;log76.warn(`Upload attempt ${a}/${s} failed for ${t}, retrying...`),await new Promise(e=>setTimeout(e,1e3*a))}throw n||new Error("Upload failed with unknown error")}async waitForDeployment(e,t=30){log76.info(`Waiting for deployment to complete: ${e}`);for(let r=0;r<t;r++)try{log76.debug(`Checking deployment status (attempt ${r+1}/${t})...`);const i=await this.httpClient.get(`https://api.netlify.com/api/v1/deploys/${e}`,{Authorization:`Bearer ${this.config.accessToken}`});if(log76.debug(`Status check response: ${i.status}`),i.ok){const e=i.data;if(log76.info(`Deployment state: ${e.state}`,{published_at:e.published_at}),"ready"===e.state)return void log76.info("Deployment is ready!");if("error"===e.state)throw new Error(`Deployment failed: ${e.error_message||"Unknown error"}`);log76.debug(`Current state: ${e.state}, waiting...`)}else log76.warn(`Unexpected status code: ${i.status}`);await new Promise(e=>setTimeout(e,2e3))}catch(e){if(log76.error(`Error checking deployment status (attempt ${r+1}):`,e),r===t-1)throw e;await new Promise(e=>setTimeout(e,2e3))}throw log76.warn("Deployment status check timed out (60 seconds)"),new Error("Deployment timed out")}async getSiteUrl(){try{log76.debug(`Fetching site URL for: ${this.config.siteId}`);const e=await this.httpClient.get(`https://api.netlify.com/api/v1/sites/${this.config.siteId}`,{Authorization:`Bearer ${this.config.accessToken}`});if(log76.debug(`Get site URL response: ${e.status}`),!e.ok){const t=await e.text();throw log76.error(`Failed to get site URL: ${e.status} - ${t}`),new Error(`Failed to get site URL: ${e.status}`)}const t=e.data,r=t.ssl_url||t.url;return log76.info(`Site URL: ${r}`,{name:t.name}),r}catch(e){throw log76.error("Failed to get site URL:",e),e}}formatBytes(e){if(0===e)return"0 Bytes";const t=Math.floor(Math.log(e)/Math.log(1024));return Math.round(e/Math.pow(1024,t)*100)/100+" "+["Bytes","KB","MB","GB"][t]}}}});import path34 from"path";import{promises as fs7}from"fs";import JSZip2 from"jszip";var log78,PublisherFactory,log79,PublishAppService,NodeWorkspaceRepository,NodeProjectRepository,init_mdfriday_publisher=__esm({"internal/domain/publish/value-object/mdfriday-publisher.ts"(){init_log(),log77=getDomainLogger("mdfriday-publisher",{component:"domain"}),MDFridayPublisher=class{constructor(e,t,r,i,s){this.config=e,this.manifestRepo=t,this.httpClient=r,this.projectId=i,this.projectPath=s}async publish(e,t){const r=Date.now();try{if(log77.info(`Starting MDFriday deployment from: ${e}`),log77.info(`Deployment type: ${this.config.deploymentType}`),"free"!==this.config.deploymentType&&!this.config.accessToken)throw new Error("MDFriday access token not found.\nPlease login first:\n mdf auth login");const{changedFiles:i,allFiles:s}=await this.getFileLists(e,t?.incremental),n=t?.incremental&&i.length<s.length&&i.length>0;if(n)log77.info(`Incremental deploy: ${i.length}/${s.length} files (${Math.round(i.length/s.length*100)}%)`);else if(t?.incremental&&0===i.length)return log77.info("No files changed, skipping deployment"),{success:!0,url:"",filesUploaded:0,bytesTransferred:0,duration:Date.now()-r};t?.onProgress?.({phase:"scanning",percentage:5,message:n?`Creating incremental package (${i.length} files)...`:"Creating deployment package..."});const a=n?await this.createIncrementalZip(e,i):await this.createZipFromDirectory(e),o=a.length;log77.info(`Created ${n?"incremental":"full"} ZIP package: ${this.formatBytes(o)}`),t?.onProgress?.({phase:"scanning",percentage:30,message:"Package created"}),t?.onProgress?.({phase:"uploading",percentage:30,message:"Uploading to MDFriday..."});const l=await this.uploadToMDFriday(a,this.projectId,e=>{const r=30+e/100*40;t?.onProgress?.({phase:"uploading",percentage:r,message:"Uploading...",bytesTransferred:Math.floor(o*(e/100))})});log77.info(`Upload complete, preview ID: ${l}`),t?.onProgress?.({phase:"deploying",percentage:70,message:"Deploying..."});const c=await this.deployPreview(l);log77.info(`Deploy complete: ${c}`),t?.onProgress?.({phase:"deploying",percentage:90,message:"Saving manifest..."});const h=await this.manifestRepo.generateManifest(this.projectId,e,"mdfriday",{previewId:l,deploymentType:this.config.deploymentType});await this.manifestRepo.saveManifest(this.projectPath,h,this.config.deploymentType),t?.onProgress?.({phase:"complete",percentage:100,message:"Deployment complete!"});const u=Date.now()-r;return log77.info(`Deployment successful: ${c}`),{success:!0,url:c,filesUploaded:i.length,bytesTransferred:o,duration:u}}catch(e){log77.error("MDFriday deployment failed",e);const t=Date.now()-r;let i=e.message;return i.includes("401")||i.includes("Unauthorized")?i="Invalid access token. Please login again:\n mdf auth login":i.includes("403")||i.includes("Forbidden")?i="Access forbidden. Please check your account permissions.":i.includes("network")&&(i="Network error. Please check your internet connection."),{success:!1,filesUploaded:0,bytesTransferred:0,duration:t,error:i}}}async testConnection(){try{return"free"===this.config.deploymentType||this.config.accessToken?{success:!0}:{success:!1,error:"Access token not found. Please login first: mdf auth login"}}catch(e){return{success:!1,error:e.message}}}getConfig(){return this.config}getType(){return"mdfriday"}async getFileLists(e,t){const r=await this.manifestRepo.generateManifest(this.projectId,e,"mdfriday",{deploymentType:this.config.deploymentType}),i=r.getAllFiles();if(!t)return log77.debug("Full publish mode: deploying all files"),{changedFiles:i,allFiles:i};const s=await this.manifestRepo.loadManifest(this.projectPath,"mdfriday",this.config.deploymentType);if(!s)return log77.info("No previous manifest found, performing full deploy"),{changedFiles:i,allFiles:i};const n=s.getChangedFiles(r);return log77.info(`Incremental mode: ${n.length}/${i.length} files changed`),{changedFiles:n,allFiles:i}}async createIncrementalZip(e,t){const r=new JSZip2;log77.debug(`Creating incremental ZIP with ${t.length} files`);for(const i of t){const t=path34.join(e,i);try{const e=await fs7.readFile(t);r.file(i,new Uint8Array(e))}catch(e){throw log77.error(`Failed to add file to ZIP: ${i}`,e),new Error(`Failed to add file to incremental ZIP: ${i}`)}}return await r.generateAsync({type:"uint8array"})}async createZipFromDirectory(e){const t=new JSZip2,r=async(e,t)=>{const i=await fs7.readdir(e,{withFileTypes:!0});for(const s of i){const i=path34.join(e,s.name);if(s.isDirectory()){const e=t.folder(s.name);e&&await r(i,e)}else if(s.isFile()){const e=await fs7.readFile(i);t.file(s.name,new Uint8Array(e))}}};return await r(e,t),await t.generateAsync({type:"uint8array"})}async uploadToMDFriday(e,t,r){try{log77.info(`Uploading ${this.formatBytes(e.length)} to MDFriday...`);const i=this.simulateUploadProgress(e.length,r),s=this.buildFormData(e,t,this.config.path||"",this.config.deploymentType),n="free"===this.config.deploymentType,a=n?`${this.getApiUrl()}/api/mdf/preview/friday?type=MDFPreview`:`${this.getApiUrl()}/api/mdf/preview?type=MDFPreview`,o={};!n&&this.config.accessToken&&(o.Authorization=`Bearer ${this.config.accessToken}`);const l=await this.httpClient.postMultipart(a,s,o);if(clearInterval(i),r?.(100),!l.ok){const e=await l.text();throw log77.error(`Upload failed: ${l.status} - ${e}`),new Error(`Upload failed: ${l.status} - ${e}`)}const c=l.data.data[0].id;return log77.info(`Preview created: ${c}`),c}catch(e){throw log77.error("MDFriday upload error:",e),e}}async deployPreview(e){try{log77.info(`Deploying preview: ${e}`);const t={type:"MDFPreview",id:e,host_name:"MDFriday Preview",license_key:this.config.licenseKey||""},r="free"===this.config.deploymentType,i=r?`${this.getApiUrl()}/api/mdf/preview/friday/deploy?type=MDFPreview&id=${e}`:`${this.getApiUrl()}/api/mdf/preview/deploy?type=MDFPreview&id=${e}`,s={};!r&&this.config.accessToken&&(s.Authorization=`Bearer ${this.config.accessToken}`);const n=await this.httpClient.postMultipart(i,t,s);if(!n.ok){const e=await n.text();throw log77.error(`Deploy failed: ${n.status} - ${e}`),new Error(`Deploy failed: ${n.status} - ${e}`)}return n.data.data[0]}catch(e){throw log77.error("MDFriday deploy error:",e),e}}buildFormData(e,t,r,i){return{type:i,path:r,id:"-1",name:t,size:e.length.toString(),asset:{data:e,filename:`${t}.zip`,contentType:"application/zip"}}}getApiUrl(){return this.config.apiUrl||"https://api.mdfriday.com"}simulateUploadProgress(e,t){let r=0;const i=500/Math.min(Math.max(e/1024/1024*2e3,3e3),3e4)*100;return setInterval(()=>{r=Math.min(r+i,95),t?.(r)},500)}formatBytes(e){if(0===e)return"0 Bytes";const t=Math.floor(Math.log(e)/Math.log(1024));return Math.round(e/Math.pow(1024,t)*100)/100+" "+["Bytes","KB","MB","GB"][t]}}}}),init_publisher_factory=__esm({"internal/domain/publish/factory/publisher-factory.ts"(){init_publisher3(),init_ftp_publisher(),init_netlify_publisher(),init_mdfriday_publisher(),init_log(),log78=getDomainLogger("publisher-factory",{component:"domain"}),PublisherFactory=class{constructor(e,t){this.manifestRepo=e,this.httpClient=t}create(e,t,r){let i;switch(log78.debug(`Creating publisher: ${r.type}`,{projectId:e}),r.type){case"ftp":i=this.createFtpPublisher(e,t,r);break;case"netlify":i=this.createNetlifyPublisher(e,t,r);break;case"mdfriday":i=this.createMDFridayPublisher(e,t,r);break;default:throw new Error(`Unknown publish type: ${r.type}`)}return new PublisherAggregator(e,t,r,i,this.manifestRepo)}createFtpPublisher(e,t,r){return new FtpPublisher(r,this.manifestRepo,e,t)}createNetlifyPublisher(e,t,r){return new NetlifyPublisher(r,this.manifestRepo,this.httpClient,e,t)}createMDFridayPublisher(e,t,r){return new MDFridayPublisher(r,this.manifestRepo,this.httpClient,e,t)}}}}),init_manifest_repository=__esm({"internal/domain/publish/repository/manifest-repository.ts"(){}}),init_http_client=__esm({"internal/domain/publish/repository/http-client.ts"(){}}),init_publish=__esm({"internal/domain/publish/index.ts"(){init_type12(),init_publisher3(),init_publish_manifest(),init_publish_config(),init_ftp_publisher(),init_netlify_publisher(),init_mdfriday_publisher(),init_publisher_factory(),init_manifest_repository(),init_http_client()}}),init_publish2=__esm({"internal/application/publish.ts"(){init_publish(),init_log(),log79=getDomainLogger("publish-service",{component:"application"}),PublishAppService=class{constructor(e,t){this.publisherFactory=e,this.workspaceService=t}async publish(e,t,r,i){log79.info(`Publishing project: ${e.getName()} to ${t.type}`);try{const s=await e.getPublishDir(),n=this.publisherFactory.create(e.getId(),e.getPath(),t),a={incremental:!r?.force};return r?.force&&(a.force=!0),i&&(a.onProgress=i),await n.publish(s,a)}catch(e){throw log79.error(`Publish failed: ${t.type}`,e),e}}async testConnection(e,t){log79.info(`Testing ${t.type} connection for project: ${e.getName()}`);try{const r=this.publisherFactory.create(e.getId(),e.getPath(),t);return r.testConnection?await r.testConnection():{success:!0}}catch(e){return log79.error(`Test connection failed: ${t.type}`,e),{success:!1,error:e.message}}}async prepareFinalConfig(e,t,r){const i=await e.getAllConfig();let s=WorkspacePublishConfig.fromGlobalConfig(i);await t.loadConfig();const n=t.getConfig();if(n?.publish){log79.debug("Merging project publish config");const e=n.publish;s=s.merge(e,r)}return this.getMethodConfig(s,r,e)}async getMethodConfig(e,t,r){switch(t){case"ftp":const i=e.getFTPConfig();if(!i)throw new Error("FTP configuration not found.\nPlease configure FTP settings:\n mdf config:set publish.ftp.host <host> --global\n mdf config:set publish.ftp.username <username> --global\n mdf config:set publish.ftp.password <password> --global\n mdf config:set publish.ftp.remotePath /public_html --global");return{type:"ftp",...i};case"netlify":const s=e.getNetlifyConfig();if(!s)throw new Error("Netlify configuration not found.\nPlease configure Netlify settings:\n mdf config:set publish.netlify.siteId <site-id> --global\n mdf config:set publish.netlify.accessToken <token> --global");return{type:"netlify",...s};case"mdfriday":const n=e.getMDFridayConfig();if(!n)throw new Error("MDFriday configuration not found.\nPlease configure MDFriday settings:\n mdf config:set publish.mdfriday.enabled true --global");const a=n.licenseKey||"";if(!a)throw new Error("❌ MDFriday license key is required for publishing.\n\nDifferent licenses deploy to different servers.\nYou must explicitly configure a license key:\n\nConfigure license globally (recommended):\n mdf config:set publish.mdfriday.licenseKey MDF-XXXX-XXXX-XXXX --global\n\nOr configure for project only:\n mdf config:set publish.mdfriday.licenseKey MDF-XXXX-XXXX-XXXX\n\n💡 Note: License login (mdf license:login) only gets TOKEN.\n Publishing requires explicitly setting a license key.");const{createIdentityService:o}=await Promise.resolve().then(()=>(init_container(),container_exports));let l=null,c="https://app.mdfriday.com";try{const e=await o(r.getInfo().path);await e.initialize(),l=e.getToken();const t=e.getServerConfig();t&&(c=t.getApiUrl(),log79.debug(`Using API URL from auth: ${c}`))}catch(e){log79.warn("Failed to get identity info",e)}if(!l)throw new Error("❌ Not authenticated.\n\nPlease login first:\n mdf auth:login\n\nOr use license login:\n mdf license:login --key YOUR-LICENSE-KEY");return{type:"mdfriday",licenseKey:a,accessToken:l,apiUrl:c,deploymentType:n.type||"share",path:"",enabled:!0};default:throw new Error(`Unsupported publish method: ${t}`)}}}}});import{promises as fs8}from"fs";import path35 from"path";var NodeSnapshotRepository,init_node_workspace_repository=__esm({"internal/infrastructure/persistence/node-workspace-repository.ts"(){NodeWorkspaceRepository=class{async isWorkspace(e){try{const t=path35.join(e,".mdfriday","workspace.json");return await fs8.access(t),!0}catch{return!1}}async initWorkspaceStructure(e,t,r){const i=path35.join(e,".mdfriday"),s=path35.join(e,t),n=path35.join(e,r);await fs8.mkdir(i,{recursive:!0}),await fs8.mkdir(s,{recursive:!0}),await fs8.mkdir(n,{recursive:!0})}async saveWorkspaceMetadata(e,t){const r=path35.join(e,".mdfriday","workspace.json");await fs8.writeFile(r,JSON.stringify(t,null,2))}async loadWorkspaceMetadata(e){const t=path35.join(e,".mdfriday","workspace.json"),r=await fs8.readFile(t,"utf-8");return JSON.parse(r)}async saveProjectRegistry(e,t){const r=path35.join(e,".mdfriday","projects.json");await fs8.writeFile(r,JSON.stringify(t,null,2))}async loadProjectRegistry(e){const t=path35.join(e,".mdfriday","projects.json"),r=await fs8.readFile(t,"utf-8");return JSON.parse(r)}},NodeProjectRepository=class{async isProject(e){try{const t=path35.join(e,".mdfriday","project.json");return await fs8.access(t),!0}catch{return!1}}async initProjectStructure(e,t,r,i){const s=path35.join(e,".mdfriday"),n=path35.join(e,t),a=path35.join(e,r),o=path35.join(e,i);await fs8.mkdir(s,{recursive:!0}),await fs8.mkdir(n,{recursive:!0}),await fs8.mkdir(a,{recursive:!0}),await fs8.mkdir(o,{recursive:!0})}async saveProjectMetadata(e,t){const r=path35.join(e,".mdfriday","project.json");await fs8.writeFile(r,JSON.stringify(t,null,2))}async loadProjectMetadata(e){const t=path35.join(e,".mdfriday","project.json"),r=await fs8.readFile(t,"utf-8");return JSON.parse(r)}async saveProjectConfig(e,t){const r=path35.join(e,"config.json");await fs8.writeFile(r,JSON.stringify(t,null,2))}async createSampleContent(e,t){await fs8.writeFile(e,t)}async deleteProjectFiles(e){await fs8.rm(e,{recursive:!0,force:!0})}async deleteProjectDirectory(e){await fs8.rm(e,{recursive:!0,force:!0})}}}});import{promises as fs9}from"fs";import path36 from"path";var log80,LANGUAGE_CODE_MAP,NodeFileSystemRepository,init_node_snapshot_repository=__esm({"internal/infrastructure/persistence/node-snapshot-repository.ts"(){NodeSnapshotRepository=class{async createSnapshot(e,t,r){const i=path36.join(e,".mdfriday","snapshots");await fs9.mkdir(i,{recursive:!0});const s=path36.join(i,t);await fs9.mkdir(s,{recursive:!0}),await this.copyDirectory(r,s);const n=await this.getDirectorySize(s),a=await this.countFiles(s),o={id:t,name:t,timestamp:Date.now(),outputDir:path36.relative(e,r),storageDir:path36.relative(e,s),size:n,fileCount:a},l=path36.join(i,`${t}.json`);return await fs9.writeFile(l,JSON.stringify(o,null,2)),o}async listSnapshots(e){const t=path36.join(e,".mdfriday","snapshots");try{await fs9.access(t)}catch{return[]}const r=(await fs9.readdir(t)).filter(e=>e.endsWith(".json")),i=[];for(const e of r)try{const r=await fs9.readFile(path36.join(t,e),"utf-8");i.push(JSON.parse(r))}catch{}return i}async getSnapshot(e,t){const r=path36.join(e,".mdfriday","snapshots"),i=path36.join(r,`${t}.json`);try{const e=await fs9.readFile(i,"utf-8"),t=JSON.parse(e);if(!t.storageDir)throw new Error("This is a legacy metadata-only snapshot and cannot be restored");return t}catch(e){if("ENOENT"===e.code)throw new Error(`Snapshot not found: ${t}`);throw e}}async restoreSnapshot(e,t,r){const i=await this.getSnapshot(e,t),s=path36.join(e,i.storageDir);try{await fs9.access(s)}catch{throw new Error(`Snapshot storage not found: ${t}`)}try{await fs9.rm(r,{recursive:!0,force:!0})}catch{}await this.copyDirectory(s,r)}async deleteSnapshot(e,t){const r=path36.join(e,".mdfriday","snapshots"),i=path36.join(r,`${t}.json`);try{const t=await fs9.readFile(i,"utf-8"),r=JSON.parse(t);if(r.storageDir){const t=path36.join(e,r.storageDir);try{await fs9.rm(t,{recursive:!0,force:!0})}catch{}}await fs9.rm(i,{force:!0})}catch(e){if("ENOENT"===e.code)throw new Error(`Snapshot not found: ${t}`);throw e}}async copyDirectory(e,t){await fs9.mkdir(t,{recursive:!0});const r=await fs9.readdir(e,{withFileTypes:!0});await Promise.all(r.map(async r=>{const i=path36.join(e,r.name),s=path36.join(t,r.name);r.isDirectory()?await this.copyDirectory(i,s):await fs9.copyFile(i,s)}))}async getDirectorySize(e){let t=0;const r=await fs9.readdir(e,{withFileTypes:!0});for(const i of r){const r=path36.join(e,i.name);i.isDirectory()?t+=await this.getDirectorySize(r):t+=(await fs9.stat(r)).size}return t}async countFiles(e){let t=0;const r=await fs9.readdir(e,{withFileTypes:!0});for(const i of r){const r=path36.join(e,i.name);i.isDirectory()?t+=await this.countFiles(r):t++}return t}}}});import{promises as fs10}from"fs";import path37 from"path";function mapLanguageCode(e){const t=e.toLowerCase().trim();return LANGUAGE_CODE_MAP[t]||t}var log81,NodeManifestRepository,init_node_file_system=__esm({"internal/infrastructure/persistence/node-file-system.ts"(){init_log(),log80=getDomainLogger("node-fs",{component:"infrastructure"}),LANGUAGE_CODE_MAP={zh:"zh",cn:"zh","zh-cn":"zh","zh-hans":"zh",en:"en",ja:"ja",jp:"ja",ko:"ko",kr:"ko",es:"es",fr:"fr",de:"de",it:"it",pt:"pt",ru:"ru"},NodeFileSystemRepository=class{async exists(e){try{return await fs10.access(e),!0}catch{return!1}}async isDirectory(e){try{return(await fs10.stat(e)).isDirectory()}catch{return!1}}async isFile(e){try{return(await fs10.stat(e)).isFile()}catch{return!1}}async readDirectory(e){try{return(await fs10.readdir(e,{withFileTypes:!0})).map(t=>({path:path37.join(e,t.name),name:t.name,isDirectory:t.isDirectory(),isFile:t.isFile()}))}catch(t){throw log80.error(`Failed to read directory: ${e}`,t),new Error(`Failed to read directory: ${t.message}`)}}async scanFolderStructure(e){try{if(!await this.exists(e))throw new Error(`Path does not exist: ${e}`);if(!await this.isDirectory(e))throw new Error(`Path is not a directory: ${e}`);const t=await this.readDirectory(e),r=[];let i=null;for(const e of t){if(!e.isDirectory)continue;const t=e.name.toLowerCase();if("content"===t)r.push({path:e.path,languageCode:"en",weight:0});else if(t.startsWith("content.")){const i=mapLanguageCode(t.split(".")[1]);r.push({path:e.path,languageCode:i,weight:1})}"static"===t&&(i={path:e.path})}r.sort((e,t)=>e.weight!==t.weight?e.weight-t.weight:path37.basename(e.path).localeCompare(path37.basename(t.path)));const s=r.length>0;return log80.debug(`Scanned folder structure: ${e}`,{contentFolders:r.length,hasStatic:!!i,isStructured:s}),{rootPath:e,contentFolders:r,staticFolder:i,isStructured:s}}catch(t){throw log80.error(`Failed to scan folder structure: ${e}`,t),t}}async createSymlink(e,t){try{if(!await this.exists(e))return{source:e,target:t,success:!1,error:`Source does not exist: ${e}`};if(await this.exists(t)){if(await this.isSymlink(t)&&await this.readSymlink(t)===e)return log80.debug(`Symlink already exists: ${t} -> ${e}`),{source:e,target:t,success:!0};await this.remove(t,!0)}const r=this.dirname(t);await this.createDirectory(r,!0);const i=(await fs10.stat(e)).isFile(),s="win32"===process.platform;return i?s?await fs10.symlink(e,t,"file"):await fs10.symlink(e,t):s?await fs10.symlink(e,t,"junction"):await fs10.symlink(e,t,"dir"),log80.debug(`Created symlink: ${t} -> ${e}`),{source:e,target:t,success:!0}}catch(r){return log80.error(`Failed to create symlink: ${t} -> ${e}`,r),{source:e,target:t,success:!1,error:r.message}}}async createSymlinks(e){const t=[];for(const r of e){const e=await this.createSymlink(r.source,r.target);t.push(e)}return t}async removeSymlink(e){try{await this.isSymlink(e)&&(await fs10.unlink(e),log80.debug(`Removed symlink: ${e}`))}catch(t){throw log80.error(`Failed to remove symlink: ${e}`,t),t}}async isSymlink(e){try{return(await fs10.lstat(e)).isSymbolicLink()}catch{return!1}}async readSymlink(e){try{return await fs10.readlink(e)}catch(t){throw log80.error(`Failed to read symlink: ${e}`,t),t}}async createDirectory(e,t=!1){try{await fs10.mkdir(e,{recursive:t}),log80.debug(`Created directory: ${e}`)}catch(t){throw log80.error(`Failed to create directory: ${e}`,t),t}}async remove(e,t=!1){try{(await fs10.lstat(e)).isDirectory()?await fs10.rm(e,{recursive:t,force:!0}):await fs10.unlink(e),log80.debug(`Removed: ${e}`)}catch(t){throw log80.error(`Failed to remove: ${e}`,t),t}}async stat(e){try{const t=await fs10.stat(e);return{isFile:()=>t.isFile(),isDirectory:()=>t.isDirectory(),isSymbolicLink:()=>t.isSymbolicLink(),size:t.size,mtime:t.mtime}}catch(t){throw log80.error(`Failed to stat: ${e}`,t),t}}async copyFile(e,t){try{const r=path37.dirname(t);await this.exists(r)||await fs10.mkdir(r,{recursive:!0}),await fs10.copyFile(e,t),log80.debug(`Copied file: ${e} -> ${t}`)}catch(r){throw log80.error(`Failed to copy file: ${e} -> ${t}`,r),r}}async readFile(e,t="utf-8"){try{return await fs10.readFile(e,t)}catch(t){throw log80.error(`Failed to read file: ${e}`,t),t}}async writeFile(e,t,r="utf-8"){try{const i=path37.dirname(e);await this.exists(i)||await fs10.mkdir(i,{recursive:!0}),await fs10.writeFile(e,t,r),log80.debug(`Wrote file: ${e}`)}catch(t){throw log80.error(`Failed to write file: ${e}`,t),t}}async unlink(e){try{await fs10.unlink(e),log80.debug(`Deleted file: ${e}`)}catch(t){throw log80.error(`Failed to delete file: ${e}`,t),t}}async access(e){try{await fs10.access(e)}catch(t){throw new Error(`Cannot access path: ${e}`)}}async resolvePath(e){return path37.resolve(e)}basename(e){return path37.basename(e)}dirname(e){return path37.dirname(e)}join(...e){return path37.join(...e)}resolvePathSync(...e){return path37.resolve(...e)}relative(e,t){return path37.relative(e,t)}parsePath(e){return path37.parse(e)}normalize(e){return path37.normalize(e)}isAbsolute(e){return path37.isAbsolute(e)}}}});import path38 from"path";import{promises as fs11}from"fs";import{createReadStream}from"fs";import crypto3 from"crypto";var log82,NodeHttpClient2,log83,NetlifyHttpClient,LLMError,LLMConnectError,LLMHttpError,LLMAbortError,FetchHttpClient,init_node_manifest_repository=__esm({"internal/infrastructure/persistence/node-manifest-repository.ts"(){init_publish(),init_log(),log81=getDomainLogger("node-manifest-repo",{component:"infrastructure"}),NodeManifestRepository=class{async loadManifest(e,t,r){const i=this.getManifestPath(e,t,r);try{const e=await fs11.readFile(i,"utf-8"),t=JSON.parse(e);return PublishManifest.fromJSON(t)}catch(e){if("ENOENT"===e.code)return log81.debug(`Manifest not found: ${i}`),null;throw log81.error(`Failed to load manifest: ${i}`,e),e}}async saveManifest(e,t,r){const i=path38.join(e,".mdfriday");await fs11.mkdir(i,{recursive:!0});const s=this.getManifestPath(e,t.getPublishMethod(),r);await fs11.writeFile(s,JSON.stringify(t.toJSON(),null,2),"utf-8"),log81.debug(`Manifest saved: ${s}`)}async generateManifest(e,t,r,i){log81.debug(`Generating manifest for: ${t}`);const s=new Map,n="netlify"===r?"sha1":"md5";return await this.scanDirectory(t,"",s,n),log81.debug(`Scanned ${s.size} files`),PublishManifest.create({projectId:e,publishMethod:r,files:s,remoteConfig:i})}async deleteManifest(e,t,r){const i=this.getManifestPath(e,t,r);try{return await fs11.unlink(i),log81.debug(`Manifest deleted: ${i}`),!0}catch(e){if("ENOENT"===e.code)return!1;throw e}}getManifestPath(e,t,r){const i=r?`manifest-${t}-${r}.json`:`manifest-${t}.json`;return path38.join(e,".mdfriday",i)}async scanDirectory(e,t,r,i="md5"){const s=await fs11.readdir(e,{withFileTypes:!0});for(const n of s){const s=path38.join(e,n.name),a=t?path38.join(t,n.name):n.name;if(n.isDirectory())await this.scanDirectory(s,a,r,i);else if(n.isFile()){const e=await fs11.stat(s),t=await this.calculateFileHash(s,i),n=a.replace(/\\/g,"/");r.set(n,{hash:t,size:e.size,mtime:e.mtimeMs,relativePath:n})}}}async calculateFileHash(e,t="md5"){return new Promise((r,i)=>{const s=crypto3.createHash(t),n=createReadStream(e);n.on("data",e=>s.update(e)),n.on("end",()=>r(s.digest("hex"))),n.on("error",i)})}}}}),init_node_http_client=__esm({"internal/infrastructure/http/node-http-client.ts"(){init_log(),log82=getDomainLogger("node-http-client",{component:"infrastructure"}),NodeHttpClient2=class{async post(e,t,r){log82.debug(`POST ${e} (JSON)`);const i=t&&Object.keys(t).length>0,s=await fetch(e,{method:"POST",headers:i?{"Content-Type":"application/json",...r}:{...r},...i&&{body:JSON.stringify(t)}}),n=await s.text();let a;try{a=JSON.parse(n)}catch{a={text:n}}return log82.debug(`Response status: ${s.status}`),{status:s.status,data:a,text:async()=>n}}async postForm(e,t){const r=Object.entries(t).map(([e,t])=>`${encodeURIComponent(e)}=${encodeURIComponent(t)}`).join("&");log82.debug(`POST ${e} (form-urlencoded)`),log82.debug(`Request body: ${r.replace(/password=[^&]+/,"password=***")}`);const i=await fetch(e,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:r}),s=await i.text();let n;log82.debug(`Response status: ${i.status}`),log82.debug(`Response text: ${s.substring(0,500)}`);try{n=JSON.parse(s)}catch(e){log82.error("Failed to parse response as JSON:",e),n={text:s}}return{status:i.status,data:n,text:async()=>s}}async postMultipart(e,t,r){const i=`----WebKitFormBoundary${Math.random().toString(36).substring(2,9)}`,s=[];new TextEncoder;for(const[e,r]of Object.entries(t))s.push(Buffer.from(`--${i}\r\n`)),s.push(Buffer.from(`Content-Disposition: form-data; name="${e}"\r\n\r\n`)),"string"==typeof r?s.push(Buffer.from(r)):Buffer.isBuffer(r)?s.push(r):s.push(Buffer.from(String(r))),s.push(Buffer.from("\r\n"));s.push(Buffer.from(`--${i}--\r\n`));const n=Buffer.concat(s);log82.debug(`POST ${e} (multipart/form-data)`),log82.debug(`Boundary: ${i}, Body size: ${n.length} bytes`);const a=await fetch(e,{method:"POST",headers:{"Content-Type":`multipart/form-data; boundary=${i}`,...r},body:n}),o=await a.text();let l;log82.debug(`Response status: ${a.status}`),log82.debug(`Response text: ${o.substring(0,500)}`);try{l=JSON.parse(o)}catch(e){log82.error("Failed to parse response as JSON:",e),l={text:o}}return{status:a.status,data:l,text:async()=>o}}async get(e,t){log82.debug(`GET ${e}`);const r=await fetch(e,{method:"GET",...t&&{headers:t}}),i=await r.text();let s;try{s=JSON.parse(i)}catch{s={text:i}}return log82.debug(`Response status: ${r.status}`),{status:r.status,data:s,text:async()=>i}}}}}),init_netlify_http_client=__esm({"internal/infrastructure/http/netlify-http-client.ts"(){init_log(),log83=getDomainLogger("netlify-http-client",{component:"infrastructure"}),NetlifyHttpClient=class{async postJSON(e,t,r){log83.debug(`POST ${e}`);const i=await fetch(e,{method:"POST",headers:{"Content-Type":"application/json",...r},body:JSON.stringify(t)});return this.createResponse(i)}async postMultipart(e,t,r){log83.debug(`POST ${e} (multipart)`);const i=`----WebKitFormBoundary${Math.random().toString(36).substring(2,15)}`,s=[];for(const[e,r]of Object.entries(t))r&&"object"==typeof r&&"data"in r?(s.push(Buffer.from(`--${i}\r\nContent-Disposition: form-data; name="${e}"; filename="${r.filename}"\r\nContent-Type: ${r.contentType}\r\n\r\n`)),s.push(Buffer.from(r.data)),s.push(Buffer.from("\r\n"))):s.push(Buffer.from(`--${i}\r\nContent-Disposition: form-data; name="${e}"\r\n\r\n${r}\r\n`));s.push(Buffer.from(`--${i}--\r\n`));const n=Buffer.concat(s),a=await fetch(e,{method:"POST",headers:{"Content-Type":`multipart/form-data; boundary=${i}`,...r},body:n});return this.createResponse(a)}async putBinary(e,t,r){log83.debug(`PUT ${e} (${t.byteLength} bytes)`);const i=await fetch(e,{method:"PUT",headers:{"Content-Type":"application/octet-stream",...r},body:t});return this.createResponse(i)}async get(e,t){log83.debug(`GET ${e}`);const r=await fetch(e,{method:"GET",...t?{headers:t}:{}});return this.createResponse(r)}async createResponse(e){const t=await e.text();let r;try{r=JSON.parse(t)}catch{r=t}return{status:e.status,ok:e.ok,statusText:e.statusText,data:r,text:async()=>t,json:async()=>"object"==typeof r?r:JSON.parse(t)}}}}}),init_provider2=__esm({"internal/infrastructure/llm/provider.ts"(){LLMError=class extends Error{constructor(e,t){super(e),this.provider=t,this.name="LLMError"}},LLMConnectError=class extends LLMError{constructor(e,t){super(`Failed to connect to ${e}: ${t?.message||"Unknown error"}`,e),this.name="LLMConnectError"}},LLMHttpError=class extends LLMError{constructor(e,t,r){super(`${e} HTTP error: ${t} ${r}`,e),this.status=t,this.statusText=r,this.name="LLMHttpError"}},LLMAbortError=class extends LLMError{constructor(e){super(`${e} request aborted`,e),this.name="LLMAbortError"}}}});function createDefaultLLMHttpClient(){return new FetchHttpClient}var OpenAICompatibleEmbeddingProvider,OllamaProvider,OllamaEmbeddingProvider,NodeFileSystem,init_fetch_http_client=__esm({"internal/infrastructure/llm/fetch-http-client.ts"(){FetchHttpClient=class{async fetch(e){const t={method:e.method};e.headers&&(t.headers=e.headers),e.body&&(t.body=e.body),e.signal&&(t.signal=e.signal);const r=await fetch(e.url,t);return{status:r.status,statusText:r.statusText,ok:r.ok,body:r.body,text:()=>r.text(),json:()=>r.json()}}}}}),init_lmstudio_provider=__esm({"internal/infrastructure/llm/lmstudio-provider.ts"(){init_provider2(),init_fetch_http_client(),OpenAICompatibleEmbeddingProvider=class{constructor(e="http://localhost:1234/v1",t="text-embedding-nomic-embed-text-v2-moe",r,i,s){this.baseURL=e,this.apiKey=i,this.embeddingModel=t,this.httpClient=r||createDefaultLLMHttpClient(),this.name=s||this.inferProviderName(e)}name;embeddingModel;httpClient;inferProviderName(e){return e.includes("localhost")||e.includes("127.0.0.1")?"LMStudio":e.includes("openai.com")?"OpenAI":e.includes("bigmodel.cn")?"GLM":e.includes("deepseek.com")?"DeepSeek":e.includes("moonshot.cn")?"Moonshot":"OpenAI-Compatible"}buildHeaders(){const e={"Content-Type":"application/json"};return this.apiKey&&(e.Authorization=`Bearer ${this.apiKey}`),e}async*complete(e,t,r){const i=`${this.baseURL}/chat/completions`,s=[];t.systemMessage&&s.push({role:"system",content:t.systemMessage}),s.push({role:"user",content:e});const n={model:t.model||this.embeddingModel,messages:s,temperature:t.temperature??.7,max_tokens:t.maxTokens??16384,stream:!0};let a;try{const e={url:i,method:"POST",headers:this.buildHeaders(),body:JSON.stringify(n)};r&&(e.signal=r),a=await this.httpClient.fetch(e)}catch(e){if("AbortError"===e.name)throw new LLMAbortError(this.name);throw new LLMConnectError(this.name,e)}if(!a.ok)throw new LLMHttpError(this.name,a.status,a.statusText);if(!a.body)throw new LLMConnectError(this.name,new Error("No response body"));const o=a.body.getReader(),l=new TextDecoder;let c="";try{for(;;){const{done:e,value:t}=await o.read();if(e)break;c+=l.decode(t,{stream:!0});const r=c.split("\n");c=r.pop()||"";for(const e of r){const t=e.trim();if(t&&"data: [DONE]"!==t&&t.startsWith("data: ")){const e=t.slice(6);try{const t=JSON.parse(e),r=t.choices[0]?.delta,i=r?.content||r?.reasoning_content||"",s=t.choices[0]?.finish_reason;if(i&&(yield{text:i,done:!1}),s)return void(yield{text:"",done:!0})}catch{}}}}yield{text:"",done:!0}}finally{o.releaseLock()}}async completeSync(e,t,r,i){const s=`${this.baseURL}/chat/completions`,n=[];t.systemMessage&&n.push({role:"system",content:t.systemMessage}),n.push({role:"user",content:e});const a={model:t.model||this.embeddingModel,messages:n,temperature:t.temperature??.7,max_tokens:t.maxTokens??16384,stream:!1};let o;try{const e={url:s,method:"POST",headers:this.buildHeaders(),body:JSON.stringify(a)};r&&(e.signal=r),o=await this.httpClient.fetch(e)}catch(e){if("AbortError"===e.name)throw new LLMAbortError(this.name);throw new LLMConnectError(this.name,e)}if(!o.ok){const e=await o.text();throw new LLMHttpError(this.name,o.status,`${o.statusText}: ${e}`)}const l=await o.json();if(i&&l.usage){const e=l.model||t.model||this.embeddingModel;i({promptTokens:l.usage.prompt_tokens??0,completionTokens:l.usage.completion_tokens??0,totalTokens:l.usage.total_tokens??0,...e?{model:e}:{}})}const c=l.choices?.[0]?.message?.content||"",h=l.choices?.[0]?.message?.reasoning_content||"",u=l.choices?.[0]?.finish_reason;return!c&&"length"===u&&h?(console.warn(`⚠️ [${this.name}] Model hit maxTokens limit during reasoning. Consider increasing maxTokens.`),h.trim()):c.trim()}async generateEmbedding(e,t,r){return this.embed({text:e,model:t,...r?{onUsage:r}:{}})}async embed(e){const t=`${this.baseURL}/embeddings`,r=e.model||this.embeddingModel,i={model:r,input:e.text};let s;try{const r={url:t,method:"POST",headers:this.buildHeaders(),body:JSON.stringify(i)};e.signal&&(r.signal=e.signal),s=await this.httpClient.fetch(r)}catch(e){if("AbortError"===e.name)throw new Error("Embedding request aborted");throw new Error(`[${this.name}] Failed to connect to embedding API: ${e.message}`)}if(!s.ok){const e=await s.text();throw new Error(`[${this.name}] Embedding API error (${s.status}): ${e}`)}const n=await s.json();if(!n.data?.[0]?.embedding)throw new Error(`[${this.name}] Invalid embedding response format`);if(e.onUsage){const t=n.usage?.prompt_tokens??0,i=n.usage?.total_tokens??t,s=t>0?t:Math.max(1,Math.ceil(e.text.length/4)),a=i>0?i:s,o=n.model||r;e.onUsage({promptTokens:s,completionTokens:0,totalTokens:a,...o?{model:o}:{}})}return n.data[0].embedding}async embedBatch(e){const t=`${this.baseURL}/embeddings`,r={model:this.embeddingModel,input:e},i=await this.httpClient.fetch({url:t,method:"POST",headers:this.buildHeaders(),body:JSON.stringify(r)});if(!i.ok){const e=await i.text();throw new Error(`[${this.name}] Embedding batch API error (${i.status}): ${e}`)}const s=await i.json();if(!s.data||!Array.isArray(s.data))throw new Error(`[${this.name}] Invalid batch embedding response format`);return s.data.sort((e,t)=>e.index-t.index).map(e=>e.embedding)}async healthCheck(){try{return(await this.httpClient.fetch({url:`${this.baseURL}/models`,method:"GET",headers:this.buildHeaders()})).ok}catch{return!1}}}}}),init_ollama_provider=__esm({"internal/infrastructure/llm/ollama-provider.ts"(){init_provider2(),OllamaProvider=class{constructor(e="http://localhost:11434"){this.baseURL=e}name="Ollama";async*complete(e,t,r){t.systemMessage?yield*this.completeWithChat(e,t,r):yield*this.completeWithGenerate(e,t,r)}async*completeWithChat(e,t,r){const i=`${this.baseURL}/api/chat`,s=[];t.systemMessage&&s.push({role:"system",content:t.systemMessage}),s.push({role:"user",content:e});const n={model:t.model||"llama2",messages:s,stream:!0,options:{temperature:t.temperature??.7,num_predict:t.maxTokens??16384}};let a;try{a=await fetch(i,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n),...r?{signal:r}:{}})}catch(e){if("AbortError"===e.name)throw new LLMAbortError(this.name);throw new LLMConnectError(this.name,e)}if(!a.ok)throw new LLMHttpError(this.name,a.status,a.statusText);if(!a.body)throw new LLMConnectError(this.name,new Error("No response body"));const o=a.body.getReader(),l=new TextDecoder;try{for(;;){const{done:e,value:r}=await o.read();if(e)break;const i=l.decode(r,{stream:!0}).split("\n").filter(e=>e.trim());for(const e of i)try{const r=JSON.parse(e),i=r.message?.content||"";if(i&&(yield{text:i,done:!1}),r.done){const e=void 0!==r.prompt_eval_count||void 0!==r.eval_count?{promptTokens:r.prompt_eval_count??0,completionTokens:r.eval_count??0,totalTokens:(r.prompt_eval_count??0)+(r.eval_count??0),model:r.model||t.model}:void 0;return void(yield{text:"",done:!0,...e?{usage:e}:{}})}}catch(t){console.warn("Failed to parse Ollama chunk:",e)}}}finally{o.releaseLock()}}async*completeWithGenerate(e,t,r){const i=`${this.baseURL}/api/generate`,s={model:t.model||"llama2",prompt:e,stream:!0,options:{temperature:t.temperature??.7,num_predict:t.maxTokens??4096}};let n;try{n=await fetch(i,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(s),...r?{signal:r}:{}})}catch(e){if("AbortError"===e.name)throw new LLMAbortError(this.name);throw new LLMConnectError(this.name,e)}if(!n.ok)throw new LLMHttpError(this.name,n.status,n.statusText);if(!n.body)throw new LLMConnectError(this.name,new Error("No response body"));const a=n.body.getReader(),o=new TextDecoder;try{for(;;){const{done:e,value:r}=await a.read();if(e)break;const i=o.decode(r,{stream:!0}).split("\n").filter(e=>e.trim());for(const e of i)try{const r=JSON.parse(e);if(r.done){const e=void 0!==r.prompt_eval_count||void 0!==r.eval_count?{promptTokens:r.prompt_eval_count??0,completionTokens:r.eval_count??0,totalTokens:(r.prompt_eval_count??0)+(r.eval_count??0),model:r.model||t.model}:void 0;return void(yield{text:r.response||"",done:!0,...e?{usage:e}:{}})}yield{text:r.response||"",done:!1}}catch(t){console.warn("Failed to parse Ollama chunk:",e)}}}finally{a.releaseLock()}}async completeSync(e,t,r,i){let s="";for await(const n of this.complete(e,t,r))n.done?n.usage&&i&&i(n.usage):s+=n.text;return s.trim()}async healthCheck(){try{return(await fetch(`${this.baseURL}/api/tags`,{method:"GET"})).ok}catch{return!1}}}}}),init_llm=__esm({"internal/infrastructure/llm/index.ts"(){init_provider2(),init_lmstudio_provider(),init_ollama_provider()}}),init_embedding_provider_interface=__esm({"internal/infrastructure/embedding/embedding-provider.interface.ts"(){}}),init_ollama_embedding_provider=__esm({"internal/infrastructure/embedding/ollama-embedding-provider.ts"(){OllamaEmbeddingProvider=class{config;constructor(e){this.config={timeout:3e4,...e}}async generateEmbedding(e,t,r){return this.embed({text:e,model:t,...r?{onUsage:r}:{}})}async embed(e){const t=e.model??this.config.model,r=`${this.config.baseUrl}/api/embeddings`,i=new AbortController,s=setTimeout(()=>i.abort(),this.config.timeout);try{const s=await fetch(r,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({model:t,prompt:e.text}),signal:e.signal??i.signal});if(!s.ok)throw new Error(`Ollama embedding failed: ${s.status} ${s.statusText}`);const n=await s.json();if(!n.embedding||!Array.isArray(n.embedding))throw new Error("Invalid embedding response from Ollama");if(e.onUsage){const r=n.prompt_eval_count??0,i=r>0?r:Math.max(1,Math.ceil(e.text.length/4)),s=n.model||t;e.onUsage({promptTokens:i,completionTokens:0,totalTokens:i,...s?{model:s}:{}})}return n.embedding}finally{clearTimeout(s)}}async embedBatch(e){const t=[];for(const r of e){const e=await this.embed({text:r});t.push(e)}return t}async healthCheck(){try{const e=await this.embed({text:"test"});return Array.isArray(e)&&e.length>0}catch(e){return console.error("Ollama embedding health check failed:",e),!1}}}}}),init_embedding=__esm({"internal/infrastructure/embedding/index.ts"(){init_embedding_provider_interface(),init_ollama_embedding_provider()}});import*as fs12 from"fs/promises";import*as fsSync from"fs";var NodePathService,init_node_file_system2=__esm({"internal/infrastructure/node/node-file-system.ts"(){NodeFileSystem=class{async readFile(e,t){return await fs12.readFile(e,t)}async writeFile(e,t,r){await fs12.writeFile(e,t,r)}async stat(e){const t=await fs12.stat(e);return{mtimeMs:t.mtimeMs,isFile:()=>t.isFile(),isDirectory:()=>t.isDirectory()}}async exists(e){try{return await fs12.access(e),!0}catch{return!1}}async mkdir(e,t){await fs12.mkdir(e,t)}async readdir(e){return await fs12.readdir(e)}async unlink(e){await fs12.unlink(e)}existsSync(e){return fsSync.existsSync(e)}readFileSync(e,t){return fsSync.readFileSync(e,t)}statSync(e){const t=fsSync.statSync(e);return{mtimeMs:t.mtimeMs,isFile:()=>t.isFile(),isDirectory:()=>t.isDirectory()}}}}});import*as path39 from"path";var NodeCryptoService,init_node_path_service=__esm({"internal/infrastructure/node/node-path-service.ts"(){NodePathService=class{join(...e){return path39.join(...e)}basename(e,t){return path39.basename(e,t)}dirname(e){return path39.dirname(e)}relative(e,t){return path39.relative(e,t)}resolve(...e){return path39.resolve(...e)}extname(e){return path39.extname(e)}}}});import*as crypto4 from"crypto";var NodeConversationRepository,EntityId,EntityType,ConnectionType,SourceRecord,ExtractionResult,init_node_crypto_service=__esm({"internal/infrastructure/node/node-crypto-service.ts"(){NodeCryptoService=class{hash(e,t){return crypto4.createHash(t).update(e).digest("hex")}randomUUID(){return crypto4.randomUUID()}}}}),init_node_conversation_repository=__esm({"internal/infrastructure/node/node-conversation-repository.ts"(){NodeConversationRepository=class{constructor(e,t,r){this.baseDir=e,this.fileSystem=t,this.pathService=r,this.ensureDirectory()}async save(e,t={}){const r=e.getFilename(),i=this.pathService.join(this.baseDir,r);if(await this.fileSystem.exists(this.baseDir)||await this.fileSystem.mkdir(this.baseDir,{recursive:!0}),!t.overwrite&&await this.fileSystem.exists(i))throw new Error(`Conversation file already exists: ${i}`);const s=e.formatAsMarkdown();return await this.fileSystem.writeFile(i,s,"utf-8"),i}async list(){if(!await this.fileSystem.exists(this.baseDir))return[];const e=await this.fileSystem.readdir(this.baseDir);for(const t of e)if(t.endsWith(".md")){const e=this.pathService.join(this.baseDir,t);try{await this.fileSystem.readFile(e,"utf-8")}catch(t){console.warn(`Failed to read conversation file: ${e}`,t)}}return[]}async exists(e){const t=`${e}.md`,r=this.pathService.join(this.baseDir,t);return await this.fileSystem.exists(r)}getFilePath(e){const t=`${e}.md`;return this.pathService.join(this.baseDir,t)}ensureDirectory(){}}}}),init_entity_id=__esm({"internal/domain/wiki/value-object/entity-id.ts"(){EntityId=class e{_value;constructor(e){this._value=e}get value(){return this._value}static create(t){const r=t.toLowerCase().trim().replace(/[^\w\s\u4e00-\u9fa5-]/g,"").replace(/\s+/g,"-").replace(/-+/g,"-").replace(/^-|-$/g,"");if(!r)throw new Error("Cannot create EntityId from empty string");return new e(r)}equals(e){return this._value===e._value}toString(){return this._value}}}}),init_entity_type=__esm({"internal/domain/wiki/value-object/entity-type.ts"(){EntityType=class e{static VALID_TYPES=new Set(["person","org","tool","project","book","article","place","event","other"]);_value;constructor(e){this._value=e}get value(){return this._value}static fromString(t){const r=t.toLowerCase();return e.VALID_TYPES.has(r)?new e(r):new e("other")}equals(e){return this._value===e._value}toString(){return this._value}static PERSON=new e("person");static ORG=new e("org");static TOOL=new e("tool");static PROJECT=new e("project");static BOOK=new e("book");static ARTICLE=new e("article");static PLACE=new e("place");static EVENT=new e("event");static OTHER=new e("other")}}}),init_connection_type=__esm({"internal/domain/wiki/value-object/connection-type.ts"(){ConnectionType=class e{static VALID_TYPES=new Set(["influences","uses","critiques","extends","part-of","created-by","related-to","applies-to","contrasts-with"]);_value;constructor(e){this._value=e}get value(){return this._value}static fromString(t){const r=t.toLowerCase();return e.VALID_TYPES.has(r)?new e(r):new e("related-to")}equals(e){return this._value===e._value}toString(){return this._value}static INFLUENCES=new e("influences");static USES=new e("uses");static CRITIQUES=new e("critiques");static EXTENDS=new e("extends");static PART_OF=new e("part-of");static CREATED_BY=new e("created-by");static RELATED_TO=new e("related-to");static APPLIES_TO=new e("applies-to");static CONTRASTS_WITH=new e("contrasts-with")}}}),init_source_record=__esm({"internal/domain/wiki/value-object/source-record.ts"(){SourceRecord=class e{path;summary;date;mtime;origin;contentHash;constructor(e,t,r,i,s,n){this.path=e,this.summary=t,this.date=r,this.mtime=i,this.origin=s,this.contentHash=n}toJSON(){return{path:this.path,summary:this.summary,date:this.date.toISOString(),mtime:this.mtime,origin:this.origin,contentHash:this.contentHash}}static fromJSON(t){return new e(t.path,t.summary,new Date(t.date),t.mtime,t.origin,t.contentHash)}}}}),init_extraction_result=__esm({"internal/domain/wiki/value-object/extraction-result.ts"(){ExtractionResult=class e{sourceSummary;entities;concepts;connections;constructor(e,t,r,i){this.sourceSummary=e,this.entities=t,this.concepts=r,this.connections=i}static fromJSON(t){return new e(t.source_summary||"",t.entities||[],t.concepts||[],t.connections||[])}toJSON(){return{source_summary:this.sourceSummary,entities:this.entities,concepts:this.concepts,connections:this.connections}}}}});function cleanString(e){return"string"!=typeof e?"":e.trim()}function cleanEntities(e){return Array.isArray(e)?e.filter(e=>e&&e.name).map(e=>({name:cleanString(e.name),type:cleanString(e.type||"other"),aliases:cleanArray(e.aliases),facts:cleanArray(e.facts)})).filter(e=>e.name.length>0):[]}function cleanConcepts(e){return Array.isArray(e)?e.filter(e=>e&&e.name).map(e=>({name:cleanString(e.name),definition:cleanString(e.definition||""),related:cleanArray(e.related)})).filter(e=>e.name.length>0):[]}function cleanConnections(e){return Array.isArray(e)?e.filter(e=>e&&e.from&&e.to).map(e=>({from:cleanString(e.from),to:cleanString(e.to),type:cleanString(e.type||"related-to"),description:cleanString(e.description||"")})).filter(e=>e.from.length>0&&e.to.length>0):[]}function cleanArray(e){return Array.isArray(e)?e.filter(e=>"string"==typeof e).map(e=>e.trim()).filter(e=>e.length>0):[]}var WIKI_KB_FILENAME,WIKI_EMBEDDINGS_FILENAME,init_extraction_parser=__esm({"internal/domain/wiki/value-object/extraction-parser.ts"(){init_extraction_result()}});function createWikiConfig(e){return{kbPath:WIKI_KB_FILENAME,embeddingsPath:WIKI_EMBEDDINGS_FILENAME,wikiDir:e,entitiesDir:`${e}/entities`,conceptsDir:`${e}/concepts`,sourcesDir:`${e}/sources`,conversationsDir:`${e}/conversations`,indexFile:`${e}/index.md`,glossaryFile:`${e}/GLOSSARY.md`,logFile:`${e}/log.md`}}var Retrieval,ContentAnnotator,MODEL_PRICING,init_wiki_config=__esm({"internal/domain/wiki/value-object/wiki-config.ts"(){WIKI_KB_FILENAME="kb.json",WIKI_EMBEDDINGS_FILENAME="embeddings.json",createWikiConfig(".wiki/wiki")}}),init_retrieval=__esm({"internal/domain/wiki/value-object/retrieval.ts"(){Retrieval=class{static extractQueryTerms(e){return e.toLowerCase().split(/\s+/).filter(e=>e.length>=3)}static rankByKeyword(e,t){if(0===t.length)return[];const r=[];for(const i of e.getAllEntities()){let e=0;const s=i.name.toLowerCase(),n=Array.from(i.aliases).map(e=>e.toLowerCase());for(const r of t){(s.includes(r)||n.some(e=>e.includes(r)))&&(e+=3);for(const t of i.facts)t.toLowerCase().includes(r)&&(e+=1)}for(let r=0;r<t.length-1;r++){const i=`${t[r]} ${t[r+1]}`;s.includes(i)&&(e+=6)}e>0&&r.push({id:i.id.value,score:e,richness:i.facts.length+i.sources.length})}for(const i of e.getAllConcepts()){let e=0;const s=i.name.toLowerCase(),n=Array.from(i.aliases).map(e=>e.toLowerCase()),a=(i.definition??"").toLowerCase();for(const r of t)(s.includes(r)||n.some(e=>e.includes(r)))&&(e+=3),a.includes(r)&&(e+=1);for(let r=0;r<t.length-1;r++){const i=`${t[r]} ${t[r+1]}`;s.includes(i)&&(e+=6)}e>0&&r.push({id:`concept:${i.id.value}`,score:e,richness:i.related.length+i.sources.length})}return r.sort((e,t)=>t.score-e.score||t.richness-e.richness),r.map(({id:e,score:t})=>({id:e,score:t}))}static rankByPath(e,t){if(0===t.length)return[];const r=[];for(const i of e.getAllEntities()){let e=0;for(const r of i.sources){const i=r.toLowerCase();for(const r of t)i.includes(r)&&(e+=1)}e>0&&r.push({id:i.id.value,score:e})}for(const i of e.getAllConcepts()){let e=0;for(const r of i.sources){const i=r.toLowerCase();for(const r of t)i.includes(r)&&(e+=1)}e>0&&r.push({id:`concept:${i.id.value}`,score:e})}return r.sort((e,t)=>t.score-e.score),r}static rankByEmbedding(e,t){const r=[],i=(Map,()=>e.keys()),s=t=>e.get(t);for(const e of i()){const i=s(e);if(!i)continue;const n=this.cosineSimilarity(t,i);n>0&&r.push({id:e,score:n})}return r.sort((e,t)=>t.score-e.score),r.slice(0,50)}static rrfFuse(e,t,r=60){const i=new Map;for(let s=0;s<e.length;s++){const n=e[s],a=t[s]??1;for(let e=0;e<n.length;e++){const t=n[e],s=a/(r+e+1);i.set(t.id,(i.get(t.id)??0)+s)}}return Array.from(i.entries()).map(([e,t])=>({id:e,score:t})).sort((e,t)=>t.score-e.score)}static qualityMultiplier(e,t){if(e.startsWith("concept:")){const r=e.slice(8),i=t.getConcept(r);return i?1+.1*(i.related.length+i.sources.length):1}{const r=t.getEntity(e);return r?1+.1*(r.facts.length+r.sources.length):1}}static cosineSimilarity(e,t){const r=Math.min(e.length,t.length);let i=0,s=0,n=0;for(let a=0;a<r;a++){const r=e[a],o=t[a];i+=r*o,s+=r*r,n+=o*o}return 0===s||0===n?0:i/(Math.sqrt(s)*Math.sqrt(n))}static contextualTextForEntity(e){const t=[`Entity [${e.type.value}]: ${e.name}.`],r=Array.from(e.aliases);return r.length>0&&t.push(`Also known as: ${r.join(", ")}.`),e.facts.length>0&&t.push(e.facts.slice(0,5).join(" ")),t.join(" ")}static contextualTextForConcept(e){const t=[`Concept: ${e.name}.`],r=(e.definition??"").slice(0,200);return r.length>0&&t.push(r),e.related&&e.related.length>0&&t.push(`Related to: ${e.related.join(", ")}.`),t.join(" ")}static async buildEmbeddingIndex(e){const t=new Map,r=e.kb.getAllEntities(),i=e.kb.getAllConcepts(),s=r.length+i.length;let n=0;const a=t=>{n+=1,e.onProgress?.({current:n,total:s,phase:t})};for(const i of r){if(e.signal?.aborted)throw new Error("Embedding index build aborted");const r=i.id.value,s=this.contextualTextForEntity(i),n=e.cache.entries[r];if(n&&n.sourceText===s){t.set(r,n.vector),a("entities");continue}const o=await e.provider.embed({text:s,model:e.model,...e.signal?{signal:e.signal}:{}});e.cache.entries[r]={sourceText:s,vector:o},t.set(r,o),a("entities")}for(const r of i){if(e.signal?.aborted)throw new Error("Embedding index build aborted");const i=`concept:${r.id.value}`,s=this.contextualTextForConcept(r),n=e.cache.entries[i];if(n&&n.sourceText===s){t.set(i,n.vector),a("concepts");continue}const o=await e.provider.embed({text:s,model:e.model,...e.signal?{signal:e.signal}:{}});e.cache.entries[i]={sourceText:s,vector:o},t.set(i,o),a("concepts")}return t}static createEmbeddingCache(){return{entries:{}}}static loadEmbeddingCache(e){try{return JSON.parse(e)}catch{return this.createEmbeddingCache()}}static saveEmbeddingCache(e){return JSON.stringify(e,null,2)}}}}),init_content_annotator=__esm({"internal/domain/wiki/value-object/content-annotator.ts"(){ContentAnnotator=class{options;constructor(e={}){this.options={markFirstOccurrenceOnly:e.markFirstOccurrenceOnly??!0,contextAware:e.contextAware??!0,differentMarkers:e.differentMarkers??!1}}annotate(e,t,r){const i=this.collectTerms(t,r),s=[];i.forEach(e=>{s.push({term:e,text:e.name,isAlias:!1}),e.aliases.forEach(t=>{t&&t!==e.name&&s.push({term:e,text:t,isAlias:!0})})});const n=s.sort((e,t)=>t.text.length-e.text.length);return this.markTerms(e,n)}collectTerms(e,t){const r=[];return e.forEach(e=>{r.push({name:e.name,aliases:Array.from(e.aliases),type:"entity"})}),t.forEach(e=>{r.push({name:e.name,aliases:Array.from(e.aliases),type:"concept"})}),r}markTerms(e,t){const r=this.options.contextAware?this.extractSkipRanges(e):[];let i=e;const s=new Set;for(const{term:e,text:n,isAlias:a}of t){const t=e.name;i=this.markSingleTerm(i,n,t,e.type,r,s)}return i}extractSkipRanges(e){const t=[],r=e.match(/^---\n[\s\S]*?\n---\n/);r&&t.push([0,r[0].length]);const i=/```[\s\S]*?```/g;let s;for(;null!==(s=i.exec(e));)t.push([s.index,s.index+s[0].length]);const n=/`[^`]+`/g;for(;null!==(s=n.exec(e));)t.push([s.index,s.index+s[0].length]);const a=/\[\[[^\]]+\]\]/g;for(;null!==(s=a.exec(e));)t.push([s.index,s.index+s[0].length]);const o=/^#{1,6}\s+/gm;for(;null!==(s=o.exec(e));)t.push([s.index,s.index+s[0].length]);return t.sort((e,t)=>e[0]-t[0]),t}isInSkipRange(e,t){return t.some(([t,r])=>e>=t&&e<r)}markSingleTerm(e,t,r,i,s,n){const a=t.toLowerCase();if(this.options.markFirstOccurrenceOnly&&n.has(a))return e;const o=this.escapeRegex(t),l=/[\u4e00-\u9fa5]/.test(t),c=new RegExp(l?`(?<!\\[\\[)${o}(?!\\]\\])`:`(?<!\\[\\[)\\b${o}\\b(?!\\]\\])`,"gi");let h,u="",g=0,d=0;for(;null!==(h=c.exec(e));){const t=h.index,n=t+h[0].length;if(!this.options.contextAware||!this.isInSkipRange(t,s)){if(this.options.markFirstOccurrenceOnly&&d>0)break;u+=e.substring(g,t),this.options.differentMarkers?u+="entity"===i?`[[${r}]]`:`**[[${r}]]**`:u+=`[[${r}]]`,g=n,d++}}return u+=e.substring(g),d>0&&n.add(a),u}escapeRegex(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}}}}),init_wiki_page_renderer=__esm({"internal/domain/wiki/value-object/wiki-page-renderer.ts"(){init_content_annotator()}}),init_wiki_index_generator=__esm({"internal/domain/wiki/value-object/wiki-index-generator.ts"(){}}),init_token_usage=__esm({"internal/domain/wiki/value-object/token-usage.ts"(){}});function findPricing(e,t){const r=e.toLowerCase(),i=t.toLowerCase();return MODEL_PRICING.find(e=>e.provider.toLowerCase()===r&&e.model.toLowerCase()===i)||MODEL_PRICING.find(e=>e.provider.toLowerCase()===r&&"*"===e.model)}function estimateCost(e,t,r,i){const s=findPricing(e,t);if(!s)return;const n=r/1e6*s.inputPer1M,a=i/1e6*s.outputPer1M,o=s.model.toLowerCase()===t.toLowerCase();return{provider:s.provider,model:"*"===s.model?t:s.model,inputTokens:r,outputTokens:i,inputCost:n,outputCost:a,totalCost:n+a,currency:"USD",isLocal:s.isLocal??!1,isExact:o}}var Entity,Concept,Connection,OperationLog,EmbeddingIndex,KnowledgeBase,Conversation,WikiFactory,NodeKBRepository,NodeWikiPageRepository,log84,IdentityAppService,init_pricing=__esm({"internal/domain/wiki/value-object/pricing.ts"(){MODEL_PRICING=[{provider:"openai",model:"gpt-4.1",inputPer1M:2,outputPer1M:8,currency:"USD"},{provider:"openai",model:"gpt-4.1-mini",inputPer1M:.4,outputPer1M:1.6,currency:"USD"},{provider:"openai",model:"gpt-4o",inputPer1M:5,outputPer1M:15,currency:"USD"},{provider:"openai",model:"gpt-4o-mini",inputPer1M:.15,outputPer1M:.6,currency:"USD"},{provider:"deepseek",model:"deepseek-chat",inputPer1M:.27,outputPer1M:1.1,currency:"USD"},{provider:"deepseek",model:"deepseek-reasoner",inputPer1M:.55,outputPer1M:2.19,currency:"USD"},{provider:"glm",model:"glm-4-plus",inputPer1M:.7,outputPer1M:.7,currency:"USD"},{provider:"glm",model:"glm-4-air",inputPer1M:.14,outputPer1M:.14,currency:"USD"},{provider:"glm",model:"glm-5.1",inputPer1M:.88,outputPer1M:3.52,currency:"USD"},{provider:"moonshot",model:"moonshot-v1-128k",inputPer1M:.7,outputPer1M:2.8,currency:"USD"},{provider:"moonshot",model:"moonshot-v1-32k",inputPer1M:.4,outputPer1M:1.6,currency:"USD"},{provider:"ollama",model:"*",inputPer1M:0,outputPer1M:0,currency:"USD",isLocal:!0},{provider:"lmstudio",model:"*",inputPer1M:0,outputPer1M:0,currency:"USD",isLocal:!0}]}}),init_entity2=__esm({"internal/domain/wiki/entity/entity.ts"(){init_entity_id(),init_entity_type(),Entity=class e{_id;_name;_type;_aliases;_facts;_sources;constructor(e,t,r,i=[],s=[],n=[]){this._id=e,this._name=t,this._type=r,this._aliases=[...i],this._facts=[...s],this._sources=[...n]}get id(){return this._id}get name(){return this._name}get type(){return this._type}get aliases(){return this._aliases}get facts(){return this._facts}get sources(){return this._sources}merge(e,t,r){for(const t of e)this._aliases.includes(t)||this._aliases.push(t);for(const e of t)this._facts.includes(e)||this._facts.push(e);this._sources.includes(r)||this._sources.push(r)}qualityScore(){return 2*this._facts.length+this._sources.length}toJSON(){return{id:this._id.value,name:this._name,type:this._type.value,aliases:this._aliases,facts:this._facts,sources:this._sources}}static fromJSON(t){return new e(EntityId.create(t.name),t.name,EntityType.fromString(t.type),t.aliases||[],t.facts||[],t.sources||[])}}}}),init_concept=__esm({"internal/domain/wiki/entity/concept.ts"(){init_entity_id(),Concept=class e{_id;_name;_definition;_related;_sources;_aliases;constructor(e,t,r,i=[],s=[],n=[]){this._id=e,this._name=t,this._definition=r,this._related=[...i],this._sources=[...s],this._aliases=new Set(n)}get id(){return this._id}get name(){return this._name}get definition(){return this._definition}get related(){return this._related}get sources(){return this._sources}get aliases(){return this._aliases}merge(e,t,r,i){e&&e.length>this._definition.length&&(this._definition=e);for(const e of t)this._related.includes(e)||this._related.push(e);for(const e of r)e&&e!==this._name&&this._aliases.add(e);this._sources.includes(i)||this._sources.push(i)}qualityScore(){return(this._definition.length>0?10:0)+2*this._related.length+this._sources.length}toJSON(){return{id:this._id.value,name:this._name,definition:this._definition,related:this._related,sources:this._sources,aliases:Array.from(this._aliases)}}static fromJSON(t){return new e(EntityId.create(t.name),t.name,t.definition||"",t.related||[],t.sources||[],t.aliases||[])}}}}),init_connection=__esm({"internal/domain/wiki/entity/connection.ts"(){init_connection_type(),Connection=class e{_from;_to;_type;_description;_sources;constructor(e,t,r,i="",s=[]){this._from=e,this._to=t,this._type=r,this._description=i,this._sources=[...s]}get from(){return this._from}get to(){return this._to}get type(){return this._type}get description(){return this._description}get sources(){return this._sources}addSource(e){this._sources.includes(e)||this._sources.push(e)}updateDescription(e){e&&e.length>this._description.length&&(this._description=e)}toJSON(){return{from:this._from,to:this._to,type:this._type.value,description:this._description,sources:this._sources}}static fromJSON(t){return new e(t.from,t.to,ConnectionType.fromString(t.type),t.description||"",t.sources||[])}}}}),init_operation_log=__esm({"internal/domain/wiki/entity/operation-log.ts"(){OperationLog=class e{entries=[];addIngest(e){const t=`${this.getFilename(e.sourcePath)} → ${e.entities}E, ${e.concepts}C, ${e.connections}Conn`;this.entries.push({timestamp:new Date,operation:"ingest",details:t,metadata:e})}addQuery(e){const t=e.answerSaved?" [saved]":"",r=`"${this.truncate(e.query,60)}" → ${e.resultCount} results${t}`;this.entries.push({timestamp:new Date,operation:"query",details:r,metadata:e})}addLint(e){const t=`${e.issuesCount} issues found`+(e.issuesCount>0?` (${this.formatCategories(e.categories)})`:"");this.entries.push({timestamp:new Date,operation:"lint",details:t,metadata:e})}addGenerate(e){const t=`${e} pages generated`;this.entries.push({timestamp:new Date,operation:"generate",details:t,metadata:{pageCount:e}})}addSaveAnswer(e,t){const r=`"${this.truncate(e,50)}" → ${t}`;this.entries.push({timestamp:new Date,operation:"save-answer",details:r,metadata:{query:e,filepath:t}})}toMarkdown(){return 0===this.entries.length?"# Operation Log\n\nNo operations recorded yet.\n":"# Operation Log\n\n> This file records all operations performed on the wiki (ingests, queries, lints, etc.)\n\n"+this.entries.map(e=>`## [${this.formatTimestamp(e.timestamp)}] ${this.formatOperation(e.operation)} | ${e.details}`).join("\n\n")+"\n"}appendToExisting(e){if(0===this.entries.length)return e;if(!e||e.includes("No operations recorded yet"))return this.toMarkdown();const t=this.entries.map(e=>`## [${this.formatTimestamp(e.timestamp)}] ${this.formatOperation(e.operation)} | ${e.details}`).join("\n\n");return e.trim()+"\n\n"+t+"\n"}get count(){return this.entries.length}clear(){this.entries=[]}static fromJSON(t){const r=new e;return t&&Array.isArray(t.entries)&&(r.entries=t.entries.map(e=>({...e,timestamp:new Date(e.timestamp)}))),r}toJSON(){return{entries:this.entries}}formatTimestamp(e){return`${e.getFullYear()}-${String(e.getMonth()+1).padStart(2,"0")}-${String(e.getDate()).padStart(2,"0")} ${String(e.getHours()).padStart(2,"0")}:${String(e.getMinutes()).padStart(2,"0")}`}formatOperation(e){return{ingest:"ingest",query:"query",lint:"lint",generate:"generate","save-answer":"save-answer"}[e]||e}getFilename(e){const t=e.split("/");return t[t.length-1]}truncate(e,t){return e.length<=t?e:e.slice(0,t-3)+"..."}formatCategories(e){return Object.entries(e).map(([e,t])=>`${e}:${t}`).join(", ")}}}}),init_embedding_index=__esm({"internal/domain/wiki/entity/embedding-index.ts"(){EmbeddingIndex=class e{index;cachePath;isDirty=!1;constructor(e,t){this.cachePath=e,this.index=t||new Map}set(e,t){this.index.set(e,t),this.isDirty=!0}get(e){return this.index.get(e)}findSimilar(e,t){const r=[];for(const[t,i]of this.index.entries()){const s=this.cosineSimilarity(e,i);r.push({key:t,similarity:s})}return r.sort((e,t)=>t.similarity-e.similarity).slice(0,t)}getReadOnlyIndex(){return this.index}keys(){return this.index.keys()}has(e){return this.index.has(e)}toJSON(){return Object.fromEntries(this.index.entries())}static fromJSON(t,r){const i=new Map(Object.entries(r)),s=new e(t,i);return s.isDirty=!1,s}cosineSimilarity(e,t){if(e.length!==t.length)return 0;let r=0,i=0,s=0;for(let n=0;n<e.length;n++)r+=e[n]*t[n],i+=e[n]*e[n],s+=t[n]*t[n];const n=Math.sqrt(i)*Math.sqrt(s);return 0===n?0:r/n}getCachePath(){return this.cachePath}isDirtyState(){return this.isDirty}markClean(){this.isDirty=!1}size(){return this.index.size}clear(){this.index.clear(),this.isDirty=!0}}}}),init_knowledge_base=__esm({"internal/domain/wiki/entity/knowledge-base.ts"(){init_entity2(),init_concept(),init_connection(),init_operation_log(),init_embedding_index(),init_source_record(),init_entity_id(),init_entity_type(),init_connection_type(),init_extraction_parser(),init_retrieval(),init_content_annotator(),KnowledgeBase=class e{_entities;_concepts;_connections;_sources;_operationLog;_embeddingIndex=null;_version;_createdAt;_updatedAt;constructor(){this._entities=new Map,this._concepts=new Map,this._connections=[],this._sources=new Map,this._operationLog=new OperationLog,this._embeddingIndex=null,this._version=1,this._createdAt=new Date,this._updatedAt=new Date}addOrMergeEntity(e,t,r,i,s){const n=EntityId.create(e),a=n.value,o=this._entities.get(a);if(o)return o.merge(r,i,s),this._updatedAt=new Date,o;{const o=new Entity(n,e,EntityType.fromString(t),r,i,[s]);return this._entities.set(a,o),this._updatedAt=new Date,o}}addOrMergeConcept(e,t,r,i,s){const n=EntityId.create(e),a=n.value,o=this._concepts.get(a);if(o)return o.merge(t,r,i,s),this._updatedAt=new Date,o;{const o=new Concept(n,e,t,r,[s],i);return this._concepts.set(a,o),this._updatedAt=new Date,o}}addConnection(e,t,r,i,s){const n=EntityId.create(e).value,a=EntityId.create(t).value,o=this._connections.find(e=>e.from===n&&e.to===a&&e.type.value===r);if(o)return o.addSource(s),o.updateDescription(i),this._updatedAt=new Date,o;{const e=new Connection(n,a,ConnectionType.fromString(r),i,[s]);return this._connections.push(e),this._updatedAt=new Date,e}}markSource(e){this._sources.set(e.path,e),this._updatedAt=new Date}getOperationLog(){return this._operationLog}getStats(){return{entities:this._entities.size,concepts:this._concepts.size,connections:this._connections.length,sources:this._sources.size,operations:this._operationLog.count}}needsExtraction(e,t,r){const i=this._sources.get(e);return!i||i.contentHash!==r}isNewSource(e){return!this._sources.has(e)}getIngestedPaths(){return new Set(this._sources.keys())}backfillContentHash(e,t,r){const i=this._sources.get(e);if(i){const s=new SourceRecord(i.path,i.summary,i.date,r,i.origin,t);this._sources.set(e,s)}}get entities(){return this._entities.values()}get concepts(){return this._concepts.values()}get connections(){return this._connections}get sources(){return this._sources.values()}getEntity(e){return this._entities.get(e)}getConcept(e){return this._concepts.get(e)}getSource(e){return this._sources.get(e)}getAllEntities(){return Array.from(this._entities.values())}getAllConcepts(){return Array.from(this._concepts.values())}getAllSources(){return Array.from(this._sources.values())}getConnectionsByEntity(e){const t=e.value;return this._connections.filter(e=>e.from===t||e.to===t)}getEntitiesBySource(e){return Array.from(this._entities.values()).filter(t=>t.sources.includes(e))}getConceptsBySource(e){return Array.from(this._concepts.values()).filter(t=>t.sources.includes(e))}exportVocabulary(){let e="ENTITIES:\n";for(const t of this._entities.values())e+=`- ${t.name} (${t.type.value})\n`;e+="\nCONCEPTS:\n";for(const t of this._concepts.values())e+=`- ${t.name}\n`;return e}toJSON(){return{meta:{version:this._version,created:this._createdAt.toISOString(),updated:this._updatedAt.toISOString()},entities:Object.fromEntries(Array.from(this._entities.entries()).map(([e,t])=>[e,t.toJSON()])),concepts:Object.fromEntries(Array.from(this._concepts.entries()).map(([e,t])=>[e,t.toJSON()])),connections:this._connections.map(e=>e.toJSON()),sources:Object.fromEntries(Array.from(this._sources.entries()).map(([e,t])=>[e,t.toJSON()]))}}static fromJSON(t){const r="string"==typeof t?JSON.parse(t):t,i=new e;if(i._version=r.meta?.version||1,i._createdAt=r.meta?.created?new Date(r.meta.created):new Date,i._updatedAt=r.meta?.updated?new Date(r.meta.updated):new Date,r.entities)for(const[e,t]of Object.entries(r.entities))i._entities.set(e,Entity.fromJSON(t));if(r.concepts)for(const[e,t]of Object.entries(r.concepts))i._concepts.set(e,Concept.fromJSON(t));if(r.connections&&(i._connections=r.connections.map(e=>Connection.fromJSON(e))),r.sources)for(const[e,t]of Object.entries(r.sources))i._sources.set(e,SourceRecord.fromJSON(t));return i}mergeExtraction(e,t,r,i,s){for(const r of e.entities)this.addOrMergeEntity(r.name,r.type,r.aliases||[],r.facts||[],t);for(const r of e.concepts)this.addOrMergeConcept(r.name,r.definition||"",r.related||[],r.aliases||[],t);for(const r of e.connections)this.addConnection(r.from,r.to,r.type,r.description||"",t);const n=new SourceRecord(t,e.sourceSummary,new Date,r,s,i);this.markSource(n)}async ingestFromSource(e,t,r){const i=Date.now();try{const s=await r.fileSystem.stat(e),n=r.crypto.hash(t,"sha256");if(!this.needsExtraction(e,s.mtimeMs,n))return{success:!0,extractedEntities:0,extractedConcepts:0,extractedConnections:0,timeMs:Date.now()-i,error:"Already processed (same content hash)"};const a=this.exportVocabulary(),o=this.buildExtractionPrompt(a,e,t,r.outputLanguage||"English"),l={model:r.model,temperature:r.temperature??.1,maxTokens:r.maxTokens??32768,systemMessage:"You are a knowledge extraction system. Output ONLY valid JSON, no explanations, no thinking process, no commentary."};let c;if(r.onIngestProgress){let e="",t=0;const i=e=>Math.max(1,Math.ceil(e.length/3));for await(const s of r.llmProvider.complete(o,l))s.done?s.usage&&r.onIngestTokenUsage&&r.onIngestTokenUsage(s.usage):(e+=s.text,t+=i(s.text),r.onIngestProgress(t));c=e.trim()}else c=await r.llmProvider.completeSync(o,l,void 0,r.onIngestTokenUsage);const h=function(e){let t=e.trim();t=t.replace(/```json\s*/g,""),t=t.replace(/```\s*/g,"");const r=[];let i=0;for(;i<t.length;){const e=t.indexOf("{",i);if(-1===e)break;let s=0,n=-1,a=!1,o=!1;for(let r=e;r<t.length;r++){const e=t[r];if(o)o=!1;else if("\\"!==e)if('"'!==e){if(!a&&("{"===e&&s++,"}"===e&&(s--,0===s))){n=r;break}}else a=!a;else o=!0}if(!(n>e))break;{const s=t.substring(e,n+1);r.push(s),i=n+1}if(r.length>=5)break}for(let e=0;e<r.length;e++){const t=r[e];try{const e=JSON.parse(t);if(!e||"object"!=typeof e)continue;const r=e.source_summary||e.summary||"";if("..."===r||"Brief summary"===r||r.includes("..."))continue;const i={source_summary:cleanString(r),entities:cleanEntities(e.entities||[]),concepts:cleanConcepts(e.concepts||[]),connections:cleanConnections(e.connections||[])};if(0===i.entities.length&&0===i.concepts.length)continue;return ExtractionResult.fromJSON(i)}catch(e){continue}}return null}(c);return h?(this.mergeExtraction(h,e,s.mtimeMs,n,"user-note"),this._operationLog.addIngest({sourcePath:e,entities:h.entities.length,concepts:h.concepts.length,connections:h.connections.length}),{success:!0,extractedEntities:h.entities.length,extractedConcepts:h.concepts.length,extractedConnections:h.connections.length,timeMs:Date.now()-i}):{success:!1,extractedEntities:0,extractedConcepts:0,extractedConnections:0,timeMs:Date.now()-i,error:"Failed to parse extraction result"}}catch(e){return{success:!1,extractedEntities:0,extractedConcepts:0,extractedConnections:0,timeMs:Date.now()-i,error:e.message||"Unknown error"}}}buildExtractionPrompt(e,t,r,i){return`You are analyzing a knowledge source to extract structured information.\n\nEXISTING VOCABULARY (merge with these if applicable):\n${e}\n\nSOURCE: ${t}\nCONTENT:\n${r}\n\nExtract the following in ${i}:\n1. ENTITIES: People, places, organizations, tools, etc.\n2. CONCEPTS: Abstract ideas, methodologies, principles.\n3. CONNECTIONS: Relationships between entities and concepts.\n\nOutput ONLY valid JSON in this exact format:\n{\n "entities": [{"name": "...", "type": "...", "aliases": [...], "facts": [...]}],\n "concepts": [{"name": "...", "definition": "...", "related": [...], "aliases": [...]}],\n "connections": [{"from": "...", "to": "...", "type": "...", "description": "..."}],\n "sourceSummary": "..."\n}`}retrieve(e,t={}){const r=t.maxEntities??12,i=t.maxConcepts??8,s=[2,.5,1],n=Retrieval.extractQueryTerms(e),a=[Retrieval.rankByKeyword(this,n),Retrieval.rankByPath(this,n)],o=[s[0],s[1]];if(t.embeddingIndex&&t.queryEmbedding){const e=Retrieval.rankByEmbedding(t.embeddingIndex,t.queryEmbedding);a.push(e),o.push(s[2])}const l=Retrieval.rrfFuse(a,o,60).map(e=>({id:e.id,score:e.score*Retrieval.qualityMultiplier(e.id,this)})).sort((e,t)=>t.score-e.score),c=[],h=[];for(const e of l)if(e.id.startsWith("concept:")){if(h.length>=i)continue;const t=e.id.slice(8),r=this._concepts.get(t);r&&h.push(r)}else{if(c.length>=r)continue;const t=this._entities.get(e.id);t&&c.push(t)}const u=new Set(c.map(e=>e.id.value)),g=this._connections.filter(e=>u.has(e.from)||u.has(e.to)),d=new Set;for(const e of c)for(const t of e.sources)d.add(t);for(const e of h)for(const t of e.sources)d.add(t);return{question:e,queryType:"entity_lookup",entities:c,concepts:h,connections:g,sources:Array.from(this._sources.values()).filter(e=>d.has(e.path))}}lint(){const e=[],t=new Set;for(const e of this._connections)t.add(e.from),t.add(e.to);for(const r of this._entities.values())t.has(r.id.value)||e.push({severity:"info",type:"orphan-entity",message:`Entity "${r.name}" has no connections`,location:`entity/${r.id.value}`,suggestion:"Consider adding relationships to other entities or concepts"});for(const t of this._entities.values())0===t.facts.length&&e.push({severity:"warning",type:"empty-entity",message:`Entity "${t.name}" has no facts`,location:`entity/${t.id.value}`,suggestion:"Add descriptive facts about this entity"});for(const t of this._concepts.values())t.definition&&0!==t.definition.trim().length||e.push({severity:"warning",type:"missing-definition",message:`Concept "${t.name}" lacks a definition`,location:`concept/${t.id.value}`,suggestion:"Add a clear definition for this concept"});const r=new Set;for(const e of this._entities.values())r.add(e.id.value);for(const e of this._concepts.values())r.add(e.id.value);for(const t of this._connections)r.has(t.from)||e.push({severity:"error",type:"broken-connection",message:`Connection references non-existent entity: "${t.from}"`,suggestion:"Remove this connection or create the missing entity"}),r.has(t.to)||e.push({severity:"error",type:"broken-connection",message:`Connection references non-existent entity: "${t.to}"`,suggestion:"Remove this connection or create the missing entity"});for(const t of this._entities.values())1===t.sources.length&&t.facts.length<3&&e.push({severity:"info",type:"single-source",message:`Entity "${t.name}" has only one source and few facts`,location:`entity/${t.id.value}`,suggestion:"Consider gathering more information from additional sources"});return e}async query(e,t){const r=t.maxResults||10;let i;if(this.hasEmbeddingIndex()&&t.embeddingProvider)try{const r=t.embeddingModel||t.model;i=await t.embeddingProvider.generateEmbedding(e,r,t.onEmbeddingUsage)}catch(e){console.warn("Failed to generate query embedding, falling back to keyword search",e)}const s={maxEntities:r,maxConcepts:r};this._embeddingIndex&&(s.embeddingIndex=this._embeddingIndex.getReadOnlyIndex()),i&&(s.queryEmbedding=i);const n=this.retrieve(e,s);return{entities:n.entities.map((e,t)=>({id:e.id.value,name:e.name,type:e.type.value,relevance:1-.05*t})),concepts:n.concepts.map((e,t)=>({name:e.name,definition:e.definition,relevance:1-.05*t})),connections:n.connections.map(e=>({from:e.from,to:e.to,type:e.type.value,description:e.description}))}}async generateWikiPages(e){const t=new Map,r=new ContentAnnotator;for(const i of this._entities.values()){const s=this.renderEntityPage(i,r,e.pathService,e.sourcePath),n=this.sanitizeFilename(i.name);t.set(`entities/${n}.md`,s)}for(const i of this._concepts.values()){const s=this.renderConceptPage(i,r,e.pathService,e.sourcePath),n=this.sanitizeFilename(i.name);t.set(`concepts/${n}.md`,s)}for(const i of this._sources.values()){const s=await this.renderSourcePage(i,r,e.pathService,e.fileSystem),n=this.getSourceFilename(i.path,e.pathService,e.sourcePath);t.set(`sources/${n}`,s)}t.set("index.md",this.generateIndex(e.pathService,e.sourcePath)),t.set("GLOSSARY.md",this.generateGlossary()),this._operationLog.count>0&&t.set("log.md",this._operationLog.toMarkdown()),await e.wikiPageRepo.writePages(t)}renderEntityPage(e,t,r,i){let s=`---\ntitle: ${e.name}\ntype: entity\ncategory: ${e.type.value}\n---\n\n`;s+=`# ${e.name}\n\n`,s+=`**Type**: ${e.type.value}\n\n`,e.aliases&&e.aliases.length>0&&(s+=`**Aliases**: ${e.aliases.join(", ")}\n\n`),s+="## Facts\n\n";for(const r of e.facts)s+=`- ${t.annotate(r,this.getAllEntities(),this.getAllConcepts())}\n`;const n=this.getConnectionsByEntity(e.id);if(n.length>0){s+="\n## Connections\n\n";for(const e of n){const t=this._entities.get(e.from),r=this._entities.get(e.to)||this._concepts.get(e.to);t&&r&&(s+=`- [[${t.name}]] ${e.type.value} [[${r.name}]]: ${e.description}\n`)}}s+="\n## Sources\n\n";for(const t of e.sources)this._sources.get(t)&&(s+=`- [[${this.getSourceLinkName(t,r,i)}]]\n`);return s}renderConceptPage(e,t,r,i){let s=`---\ntitle: ${e.name}\ntype: concept\n---\n\n`;if(s+=`# ${e.name}\n\n`,e.aliases&&e.aliases.size>0&&(s+=`**Aliases**: ${Array.from(e.aliases).join(", ")}\n\n`),s+="## Definition\n\n",s+=`${t.annotate(e.definition,this.getAllEntities(),this.getAllConcepts())}\n\n`,e.related&&e.related.length>0){s+="## Related Concepts\n\n";for(const t of e.related)s+=`- [[${t}]]\n`;s+="\n"}s+="## Sources\n\n";for(const t of e.sources)this._sources.get(t)&&(s+=`- [[${this.getSourceLinkName(t,r,i)}]]\n`);return s}async renderSourcePage(e,t,r,i){let s=`---\ntitle: ${r.basename(e.path)}\ntype: source\npath: ${e.path}\ndate: ${e.date.toISOString()}\n---\n\n`;s+=`# ${r.basename(e.path)}\n\n`,s+=`**Path**: \`${e.path}\`\n\n`,s+=`**Summary**: ${e.summary}\n\n`;const n=this.getEntitiesBySource(e.path);if(n.length>0){s+="## Entities\n\n";for(const e of n)s+=`- [[${e.name}]] (${e.type.value})\n`;s+="\n"}const a=this.getConceptsBySource(e.path);if(a.length>0){s+="## Concepts\n\n";for(const e of a)s+=`- [[${e.name}]]\n`;s+="\n"}s+="## Original Content\n\n";try{const r=await i.readFile(e.path,"utf-8"),n=this.getAllEntities(),a=this.getAllConcepts();s+=`${t.annotate(r,n,a)}\n\n`}catch(t){s+=`*Could not read original content from \`${e.path}\`: ${t.message}*\n\n`}return s}generateIndex(e,t){let r="---\ntitle: Knowledge Base Index\n---\n\n";r+="# Knowledge Base\n\n",r+=`**Last Updated**: ${this._updatedAt.toISOString()}\n\n`,r+="## Statistics\n\n";const i=this.getStats();if(r+=`- **Entities**: ${i.entities}\n`,r+=`- **Concepts**: ${i.concepts}\n`,r+=`- **Connections**: ${i.connections}\n`,r+=`- **Sources**: ${i.sources}\n\n`,this._entities.size>0){r+="## Entities\n\n";const e=new Map;for(const t of this._entities.values()){const r=t.type.value;e.has(r)||e.set(r,[]),e.get(r).push(t)}const t=Array.from(e.keys()).sort();for(const i of t){const s=e.get(i).sort((e,t)=>e.name.localeCompare(t.name));t.length>1&&"other"!==i&&(r+=`### ${i.charAt(0).toUpperCase()+i.slice(1)}\n\n`);for(const e of s){const t=e.facts.length>0?e.facts[0].substring(0,80)+(e.facts[0].length>80?"...":""):e.type.value,i=e.sources.length;r+=`- [[${e.name}]] - ${t} (${i} source${1!==i?"s":""})\n`}r+="\n"}}if(this._concepts.size>0){r+="## Concepts\n\n";const e=Array.from(this._concepts.values()).sort((e,t)=>e.name.localeCompare(t.name));for(const t of e){const e=t.definition.split(/[.!?]\s/)[0],i=e.length>100?e.substring(0,100)+"...":e,s=t.sources.length;r+=`- [[${t.name}]] - ${i} (${s} source${1!==s?"s":""})\n`}r+="\n"}if(this._sources.size>0){r+="## Sources\n\n";const i=Array.from(this._sources.values()).sort((e,t)=>t.date.getTime()-e.date.getTime());for(const s of i){const i=this.getSourceLinkName(s.path,e,t),n=s.date.toISOString().split("T")[0],a=this.getEntitiesBySource(s.path).length,o=this.getConceptsBySource(s.path).length,l=s.summary.split(/[.!?]\s/)[0];r+=`- [[${i}]] - ${l.length>80?l.substring(0,80)+"...":l} (${n}, ${a} entities, ${o} concepts)\n`}r+="\n"}return r+="## Quick Links\n\n",r+="- [[GLOSSARY]]\n",this._operationLog.count>0&&(r+="- [[log]]\n"),r}generateGlossary(){let e="---\ntitle: Glossary\n---\n\n";e+="# Glossary\n\n",e+="## Entities\n\n";const t=Array.from(this._entities.values()).sort((e,t)=>e.name.localeCompare(t.name));for(const r of t)e+=`- [[${r.name}]] - ${r.type.value}\n`;e+="\n## Concepts\n\n";const r=Array.from(this._concepts.values()).sort((e,t)=>e.name.localeCompare(t.name));for(const t of r)e+=`- [[${t.name}]]\n`;return e}sanitizeFilename(e){return e.toLowerCase().replace(/[^a-z0-9-]/g,"-").replace(/-+/g,"-").replace(/^-|-$/g,"")}getSourceLinkName(e,t,r){const i=this.resolveSourceRelParts(e,t,r),s=i[i.length-1]||e.split("/").pop()||e;return[...i.slice(0,-1),s.endsWith(".md")?s.slice(0,-3):s].filter(Boolean).map(e=>this.sanitizeFilename(e)).join("-")}getSourceFilename(e,t,r){return`${this.getSourceLinkName(e,t,r)}.md`}resolveSourceRelParts(e,t,r){if(t&&r)try{const i=t.relative(r,e).split("/").filter(e=>e&&"."!==e);if(i.length>1)return i.slice(1);if(1===i.length)return i}catch{}return[e.split("/").pop()||e]}async buildEmbeddingIndex(e){const{embeddingProvider:t,model:r,cachePath:i,fileSystem:s,onEmbeddingUsage:n}=e;if(!this._embeddingIndex&&await s.exists(i))try{const e=await s.readFile(i,"utf-8"),t=JSON.parse(e);this._embeddingIndex=EmbeddingIndex.fromJSON(i,t)}catch(e){console.warn("Failed to load embedding cache, will rebuild from scratch",e)}this._embeddingIndex||(this._embeddingIndex=new EmbeddingIndex(i));const a=this.getAllEntities(),o=this.getAllConcepts();for(const e of a)if(!this._embeddingIndex.has(e.id.value)){const i=`${e.name}: ${e.facts.join(". ")}`;try{const s=await t.generateEmbedding(i,r,n);this._embeddingIndex.set(e.id.value,s)}catch(t){throw console.error(`[kb] generateEmbedding FAILED for entity "${e.name}": ${t.message}`),t}}for(const e of o){const i=`concept:${e.id.value}`;if(!this._embeddingIndex.has(i)){const s=`${e.name}: ${e.definition}`;try{const e=await t.generateEmbedding(s,r,n);this._embeddingIndex.set(i,e)}catch(t){throw console.error(`[kb] generateEmbedding FAILED for concept "${e.name}": ${t.message}`),t}}}}async saveEmbeddingIndex(e,t){if(!this._embeddingIndex||!this._embeddingIndex.isDirtyState())return;const r=this._embeddingIndex.getCachePath(),i=t.dirname(r);await e.mkdir(i,{recursive:!0}),await e.writeFile(r,JSON.stringify(this._embeddingIndex.toJSON(),null,2),"utf-8"),this._embeddingIndex.markClean()}getEmbeddingIndex(){return this._embeddingIndex}hasEmbeddingIndex(){return null!==this._embeddingIndex&&this._embeddingIndex.size()>0}buildQueryContext(e){let t="";if(e.entities.length>0){t+="ENTITIES:\n";for(const r of e.entities)t+=`- ${r.name} (${r.type.value}): ${r.facts.join(". ")}\n`;t+="\n"}if(e.concepts.length>0){t+="CONCEPTS:\n";for(const r of e.concepts)t+=`- ${r.name}: ${r.definition}\n`;t+="\n"}if(e.connections.length>0){t+="CONNECTIONS:\n";for(const r of e.connections)t+=`- ${r.from} ${r.type.value} ${r.to}\n`;t+="\n"}return t}buildQueryPrompt(e,t){return`You are answering a question based on the following knowledge base context.\n\nCONTEXT:\n${t}\n\nQUESTION:\n${e}\n\nPlease provide a comprehensive answer based on the context above. If the context doesn't contain enough information, say so.`}async*queryStream(e,t){const r=t.maxResults||10;let i;if(this.hasEmbeddingIndex()&&t.embeddingProvider)try{const r=t.embeddingModel||t.model;i=await t.embeddingProvider.generateEmbedding(e,r,t.onEmbeddingUsage)}catch(e){console.warn("Failed to generate query embedding",e)}const s={maxEntities:r,maxConcepts:r};this._embeddingIndex&&(s.embeddingIndex=this._embeddingIndex.getReadOnlyIndex()),i&&(s.queryEmbedding=i);const n=this.retrieve(e,s),a=this.buildQueryContext(n),o=this.buildQueryPrompt(e,a);for await(const e of t.llmProvider.complete(o,{model:t.model,temperature:t.temperature??.7,maxTokens:8192,systemMessage:"You are a helpful assistant answering questions based on the provided knowledge base."}))e.done?e.usage&&t.onTokenUsage&&t.onTokenUsage(e.usage):e.text&&(yield e.text)}}}}),init_conversation=__esm({"internal/domain/wiki/entity/conversation.ts"(){Conversation=class e{id;query;answer;metadata;constructor(e,t,r,i){this.id=e,this.query=t,this.answer=r,this.metadata=i}static create(t,r,i){const s=new Date,n=e.generateId(t,s);return new e(n,t,r,{query:t,timestamp:s,...i})}static generateId(t,r){return`${e.formatDate(r)}-${e.slugify(t)}`}formatAsMarkdown(){return this.buildFrontmatter()+this.buildBody()+this.buildFooter()}getFilename(){return`${this.id}.md`}getId(){return this.id}getQuery(){return this.query}getAnswer(){return this.answer}getMetadata(){return{...this.metadata}}getTimestamp(){return this.metadata.timestamp}getSources(){return[...this.metadata.sources]}buildFrontmatter(){return["---","type: query-answer",`query: "${this.escapeYaml(this.query)}"`,`timestamp: ${this.metadata.timestamp.toISOString()}`,"retrieval:",` entities: ${this.metadata.retrieval.entityCount}`,` concepts: ${this.metadata.retrieval.conceptCount}`,` total: ${this.metadata.retrieval.totalResults}`,"sources:",...this.metadata.sources.map(e=>` - ${e}`),"---",""].join("\n")}buildBody(){return[`# ${this.query}`,"",`> 📅 Generated on ${this.formatDateTime(this.metadata.timestamp)}`,`> 🔍 Based on ${this.metadata.retrieval.totalResults} results (${this.metadata.retrieval.entityCount} entities, ${this.metadata.retrieval.conceptCount} concepts)`,"","## Answer","",this.answer,""].join("\n")}buildFooter(){return["## Sources","",...this.metadata.sources.map((e,t)=>`${t+1}. \`${e}\``),"","---","","*This document was automatically generated from a query. It can be re-ingested to extract new entities and concepts.*"].join("\n")}static formatDate(e){return`${e.getFullYear()}-${String(e.getMonth()+1).padStart(2,"0")}-${String(e.getDate()).padStart(2,"0")}`}formatDateTime(e){return e.toLocaleString("en-US",{year:"numeric",month:"long",day:"numeric",hour:"2-digit",minute:"2-digit"})}static slugify(e){return e.toLowerCase().replace(/[^a-z0-9\s-]/g,"").replace(/\s+/g,"-").replace(/-+/g,"-").slice(0,50).replace(/^-+|-+$/g,"")}escapeYaml(e){return e.replace(/"/g,'\\"')}toJSON(){return{id:this.id,query:this.query,answer:this.answer,metadata:this.metadata}}static fromJSON(t){return new e(t.id,t.query,t.answer,{...t.metadata,timestamp:new Date(t.metadata.timestamp)})}}}}),init_wiki_factory=__esm({"internal/domain/wiki/factory/wiki-factory.ts"(){init_knowledge_base(),WikiFactory=class{kbRepo;wikiPageRepo;constructor(e){this.kbRepo=e.kbRepo,this.wikiPageRepo=e.wikiPageRepo}create(){return new KnowledgeBase}async load(){return await this.kbRepo.load()}async save(e){await this.kbRepo.save(e)}getWikiPageRepository(){return this.wikiPageRepo}}}}),init_kb_repository_interface=__esm({"internal/domain/wiki/repository/kb-repository.interface.ts"(){}}),init_wiki_page_repository_interface=__esm({"internal/domain/wiki/repository/wiki-page-repository.interface.ts"(){}}),init_conversation_repository_interface=__esm({"internal/domain/wiki/repository/conversation-repository.interface.ts"(){}}),init_llm_provider=__esm({"internal/domain/wiki/repository/llm-provider.ts"(){}}),init_llm_http_client=__esm({"internal/domain/wiki/repository/llm-http-client.ts"(){}}),init_embedding_provider=__esm({"internal/domain/wiki/repository/embedding-provider.ts"(){}}),init_file_system2=__esm({"internal/domain/wiki/repository/file-system.ts"(){}}),init_path_service=__esm({"internal/domain/wiki/repository/path-service.ts"(){}}),init_crypto_service=__esm({"internal/domain/wiki/repository/crypto-service.ts"(){}}),init_repository2=__esm({"internal/domain/wiki/repository/index.ts"(){init_kb_repository_interface(),init_wiki_page_repository_interface(),init_conversation_repository_interface(),init_llm_provider(),init_llm_http_client(),init_embedding_provider(),init_file_system2(),init_path_service(),init_crypto_service()}}),init_wiki=__esm({"internal/domain/wiki/index.ts"(){init_entity_id(),init_entity_type(),init_connection_type(),init_source_record(),init_extraction_result(),init_extraction_parser(),init_wiki_config(),init_retrieval(),init_content_annotator(),init_wiki_page_renderer(),init_wiki_index_generator(),init_token_usage(),init_pricing(),init_entity2(),init_concept(),init_connection(),init_knowledge_base(),init_conversation(),init_embedding_index(),init_wiki_factory(),init_repository2()}}),init_node_kb_repository=__esm({"internal/infrastructure/node/node-kb-repository.ts"(){init_wiki(),NodeKBRepository=class{constructor(e,t,r){this.filePath=e,this.fileSystem=t,this.pathService=r}async load(){if(!await this.fileSystem.exists(this.filePath))return null;try{const e=await this.fileSystem.readFile(this.filePath,"utf-8");return KnowledgeBase.fromJSON(e)}catch(e){return console.error(`Failed to load KB from ${this.filePath}:`,e),null}}async exists(){return await this.fileSystem.exists(this.filePath)}async save(e){const t=this.pathService.dirname(this.filePath);await this.fileSystem.exists(t)||await this.fileSystem.mkdir(t,{recursive:!0});const r=JSON.stringify(e.toJSON(),null,2);await this.fileSystem.writeFile(this.filePath,r,"utf-8")}async getLastModified(){return await this.fileSystem.exists(this.filePath)?(await this.fileSystem.stat(this.filePath)).mtimeMs:0}async getSize(){return await this.fileSystem.exists(this.filePath)?(await this.fileSystem.stat(this.filePath),0):0}}}}),init_node_wiki_page_repository=__esm({"internal/infrastructure/node/node-wiki-page-repository.ts"(){NodeWikiPageRepository=class{constructor(e,t,r){this.baseDir=e,this.fileSystem=t,this.pathService=r,this.wikiDir=e}wikiDir;async writePage(e,t){const r=this.pathService.join(this.wikiDir,e),i=this.pathService.dirname(r);await this.fileSystem.exists(i)||await this.fileSystem.mkdir(i,{recursive:!0}),await this.fileSystem.writeFile(r,t,"utf-8")}async deletePage(e){const t=this.pathService.join(this.wikiDir,e);await this.fileSystem.exists(t)&&await this.fileSystem.unlink(t)}async writePages(e){for(const[t,r]of e.entries())await this.writePage(t,r)}async listPages(e){const t=this.pathService.join(this.wikiDir,e);return await this.fileSystem.exists(t)?(await this.listMarkdownFiles(t)).map(e=>this.pathService.relative(this.wikiDir,e)):[]}async appendToLog(e){const t=this.pathService.join(this.wikiDir,"log.md"),r=`\n## [${(new Date).toISOString()}] ${e}\n`;if(!await this.fileSystem.exists(t)){const e=this.pathService.dirname(t);await this.fileSystem.exists(e)||await this.fileSystem.mkdir(e,{recursive:!0}),await this.fileSystem.writeFile(t,"# Wiki Operation Log\n\n","utf-8")}const i=await this.fileSystem.readFile(t,"utf-8");await this.fileSystem.writeFile(t,i+r,"utf-8")}async updateIndex(e){await this.writePage("index.md",e)}async updateGlossary(e){await this.writePage("GLOSSARY.md",e)}async exists(e){const t=this.pathService.join(this.wikiDir,e);return await this.fileSystem.exists(t)}async listMarkdownFiles(e){const t=[];try{const r=await this.fileSystem.readdir(e);for(const i of r){const r=this.pathService.join(e,i);if((await this.fileSystem.stat(r)).isDirectory()){const e=await this.listMarkdownFiles(r);t.push(...e)}else i.endsWith(".md")&&t.push(r)}}catch(t){console.warn(`Failed to list files in ${e}:`,t)}return t}}}}),init_node=__esm({"internal/infrastructure/node/index.ts"(){init_node_file_system2(),init_node_path_service(),init_node_crypto_service(),init_node_conversation_repository(),init_node_kb_repository(),init_node_wiki_page_repository()}}),init_infrastructure=__esm({"internal/infrastructure/index.ts"(){init_node_workspace_repository(),init_node_snapshot_repository(),init_node_file_system(),init_node_manifest_repository(),init_node_http_client(),init_netlify_http_client(),init_llm(),init_embedding(),init_node()}}),init_identity3=__esm({"internal/application/identity.ts"(){init_server_config(),init_log(),log84=getDomainLogger("identity-app",{component:"application"}),IdentityAppService=class{userFactory;currentUser=null;cachedServerConfig=null;constructor(e){this.userFactory=e.userFactory}async initialize(){try{this.currentUser=await this.userFactory.load(),this.currentUser?this.cachedServerConfig=this.currentUser.getServerConfig():log84.debug("No existing user session")}catch(e){log84.error("Failed to initialize identity service",e)}}async login(e,t){const r=await this.userFactory.login(e,t,this.cachedServerConfig||void 0);return this.currentUser=r,this.cachedServerConfig=r.getServerConfig(),r}async register(e,t){const r=await this.userFactory.register(e,t,this.cachedServerConfig||void 0);return this.currentUser=r,this.cachedServerConfig=r.getServerConfig(),r}async logout(){await this.userFactory.logout(),this.currentUser=null}getCurrentUser(){return this.currentUser}isAuthenticated(){return this.currentUser?.isAuthenticated()||!1}getToken(){return this.currentUser?.getToken()?.getValue()||null}getStatus(){return this.currentUser?this.currentUser.getStatus():{isAuthenticated:!1,email:"",serverUrl:this.getServerConfig().getApiUrl(),tokenExpired:!0,hasToken:!1,hasLicense:!1,license:void 0,licenseValid:!1,isTrial:!1,licensePlan:void 0,licenseExpires:void 0,licenseDaysRemaining:void 0,hasSyncConfig:!1,syncConfig:void 0}}getServerConfig(){return this.currentUser?this.currentUser.getServerConfig():this.cachedServerConfig||ServerConfig.createDefault()}async updateServerConfig(e){this.currentUser||(this.currentUser=this.userFactory.createAnonymous()),await this.userFactory.updateServerConfig(this.currentUser,e),this.cachedServerConfig=this.currentUser.getServerConfig()}async requestTrial(e){return this.userFactory.requestTrialLicense(e,this.cachedServerConfig||void 0)}async loginWithLicense(e){const t=await this.userFactory.loginWithLicense(e,this.cachedServerConfig||void 0);return this.currentUser=t,this.cachedServerConfig=t.getServerConfig(),t}async activateLicense(e,t){if(!this.currentUser)throw new Error("User must be logged in to activate license");const r=await this.userFactory.activateLicense(this.currentUser,e,t);return this.currentUser=r,r}async requestAndActivateTrial(e){const t=await this.userFactory.requestAndActivateTrial(e,this.cachedServerConfig||void 0);return this.currentUser=t,this.cachedServerConfig=t.getServerConfig(),t}getLicense(){return this.currentUser?.getLicense()||null}hasValidLicense(){return this.currentUser?.hasValidLicense()||!1}isTrialAccount(){return this.currentUser?.isTrialAccount()||!1}getLicenseDisplay(){const e=this.getLicense();return e?{key:e.getMaskedKey(),plan:e.getFormattedPlan(),expires:e.getFormattedExpiresAt(),daysRemaining:e.getDaysRemaining(),isValid:e.isValid(),isExpired:e.isExpired(),isTrial:e.isTrial(),features:e.getFeatures()}:null}async refreshTokenIfNeeded(){if(!this.currentUser)return log84.debug("No current user, cannot refresh token"),!1;const e=this.currentUser.getToken(),t=await this.userFactory.refreshTokenIfNeeded(this.currentUser),r=t.getToken(),i=e?.getValue()!==r?.getValue();return i&&(this.currentUser=t,log84.info("Token was refreshed")),i}async requestWithAutoRefresh(e){if(!this.currentUser)throw new Error("User must be logged in to make authenticated requests");const t=await this.userFactory.requestWithAutoRefresh(this.currentUser,e),r=await this.userFactory.load();return r&&(this.currentUser=r),t}async getLicenseUsage(){if(!this.currentUser)throw new Error("User must be logged in to get license usage");return this.userFactory.getLicenseUsage(this.currentUser)}async getLicenseInfo(e){if(!this.currentUser)throw new Error("User must be logged in to get license info");return this.userFactory.getLicenseInfo(this.currentUser,e)}async resetUsage(){if(!this.currentUser)throw new Error("User must be logged in to reset usage");return this.userFactory.resetUsage(this.currentUser)}async getDomains(){if(!this.currentUser)throw new Error("User must be logged in to get domains");return this.userFactory.getDomains(this.currentUser)}async checkSubdomainAvailability(e){if(!this.currentUser)throw new Error("User must be logged in to check subdomain");return this.userFactory.checkSubdomainAvailability(this.currentUser,e)}async updateSubdomain(e){if(!this.currentUser)throw new Error("User must be logged in to update subdomain");return this.userFactory.updateSubdomain(this.currentUser,e)}async checkCustomDomain(e){if(!this.currentUser)throw new Error("User must be logged in to check custom domain");return this.userFactory.checkCustomDomain(this.currentUser,e)}async addCustomDomain(e){if(!this.currentUser)throw new Error("User must be logged in to add custom domain");return this.userFactory.addCustomDomain(this.currentUser,e)}async checkCustomDomainHttpsStatus(e){if(!this.currentUser)throw new Error("User must be logged in to check HTTPS status");return this.userFactory.checkCustomDomainHttpsStatus(this.currentUser,e)}}}}),container_exports={};function createWorkspaceFactory(e){const t={workspaceRepo:e?.workspaceRepo??new NodeWorkspaceRepository,projectRepo:e?.projectRepo??new NodeProjectRepository,snapshotRepo:e?.snapshotRepo??new NodeSnapshotRepository,fileSystemRepo:e?.fileSystemRepo??new NodeFileSystemRepository};return new WorkspaceFactory(t)}function createWorkspaceAppService(e){const t=createWorkspaceFactory(e);return new WorkspaceAppService({workspaceFactory:t})}async function createIdentityService(e){const t=new NodeHttpClient2,r=createWorkspaceAppService(),i=await r.loadWorkspace(e),s=r.createIdentityStorage(i),n=new UserFactory({httpClient:t,storageProvider:s});return new IdentityAppService({userFactory:n})}async function createIdentityServiceForObsidian(e,t){const r=createWorkspaceAppService(),i=await r.loadWorkspace(e),s=r.createIdentityStorage(i),n=new UserFactory({httpClient:t,storageProvider:s});return new IdentityAppService({userFactory:n})}function createPublishAppService(){const e=new NodeManifestRepository,t=new NetlifyHttpClient,r=new PublisherFactory(e,t),i=createWorkspaceAppService();return new PublishAppService(r,i)}__export(container_exports,{createIdentityService:()=>createIdentityService,createIdentityServiceForObsidian:()=>createIdentityServiceForObsidian,createPublishAppService:()=>createPublishAppService,createWorkspaceAppService:()=>createWorkspaceAppService,createWorkspaceFactory:()=>createWorkspaceFactory});var init_container=__esm({"internal/application/container.ts"(){init_workspace2(),init_workspace3(),init_identity2(),init_publish2(),init_publish(),init_infrastructure(),init_identity3(),init_infrastructure()}});init_ssg(),init_log(),init_log();import*as workerpool from"workerpool";init_log(),init_page_filter();var log58=getDomainLogger("application",{component:"worker-state"}),WorkerState=class{constructor(e,t){this.projDir=e,this.moduleDir=t}initialized=!1;async initialize(){if(this.initialized)return void log58.warn("Worker already initialized, skipping...");const e=performance.now();log58.info("🚀 Initializing worker environment...",{projDir:this.projDir,moduleDir:this.moduleDir}),this.initialized=!0;const t=performance.now()-e;log58.info(`✅ Worker environment initialized in ${t.toFixed(2)}ms`)}async processBatch(e){if(!this.initialized)throw new Error("Worker not initialized. Call initialize() first.");const t=performance.now(),r=[];log58.info(`📦 Processing batch: ${e.length} tasks`);try{i=e,pageFilter.setFilter(i),log58.debug(`Filter set for ${e.length} tasks`);const{generateStaticSite:s}=await Promise.resolve().then(()=>(init_ssg(),ssg_exports));await s(this.projDir,this.moduleDir),log58.debug("✅ Tasks processed (filtered)");const n=performance.now()-t,a={success:!0,processedCount:e.length,totalCount:e.length,duration:n,errors:r};return log58.info(`✅ Batch processed: ${e.length} tasks in ${n.toFixed(2)}ms`),a}catch(i){const s=`Batch processing failed: ${i instanceof Error?i.message:String(i)}`;log58.error(`❌ ${s}`),r.push(s);const n=performance.now()-t;return{success:!1,processedCount:0,totalCount:e.length,duration:n,errors:r}}finally{pageFilter.clearFilter()}var i}async cleanup(){log58.info("🧹 Cleaning up worker resources..."),this.initialized=!1}getStats(){return{initialized:this.initialized,projDir:this.projDir,moduleDir:this.moduleDir}}};init_log();var log59=getDomainLogger("application",{component:"worker-main"}),workerState=null;async function handleWorkerTask(e){try{switch(e.type){case"init":return await async function(e){return e.projDir&&e.moduleDir?(log59.info("🔧 Initializing worker..."),workerState=new WorkerState(e.projDir,e.moduleDir),await workerState.initialize(),{success:!0,data:{message:"Worker initialized successfully"}}):{success:!1,error:"Missing projDir or moduleDir for init task"}}(e);case"process-batch":return await async function(e){if(!workerState)return{success:!1,error:"Worker not initialized. Call init task first."};if(!e.pageTasks||0===e.pageTasks.length)return{success:!1,error:"Missing pageTasks for process-batch task"};const t=await workerState.processBatch(e.pageTasks);return{success:t.success,data:t,error:t.errors.length>0?t.errors.join("; "):void 0}}(e);case"stats":return await async function(){return workerState?{success:!0,data:workerState.getStats()}:{success:!1,error:"Worker not initialized"}}();case"cleanup":return await async function(){return workerState?(await workerState.cleanup(),workerState=null,{success:!0,data:{message:"Worker cleaned up successfully"}}):{success:!0,data:{message:"Worker already cleaned up"}}}();default:return{success:!1,error:`Unknown task type: ${e.type}`}}}catch(e){const t=e instanceof Error?e.message:String(e);return log59.error(`Worker task failed: ${t}`),{success:!1,error:t}}}import*as os from"os";import*as path28 from"path";var log60=getDomainLogger("application",{component:"pool-manager"}),WorkerPoolManager=class{pool=null;environment;workerCount;constructor(e={}){this.environment=this.detectEnvironment(),this.workerCount=e.workerCount||this.calculateOptimalWorkerCount(),log60.info("Worker pool manager created",{environment:this.environment,workerCount:this.workerCount})}detectEnvironment(){if("undefined"!=typeof Worker&&void 0!==globalThis.window)return log60.debug("Detected Web Worker support (browser/Electron environment)"),"browser";if("undefined"!=typeof process&&process.versions&&process.versions.node)try{return __require.resolve("worker_threads"),log60.debug("Detected Node.js Worker Threads support"),"node"}catch{return log60.debug("Node.js detected but worker_threads unavailable, falling back to browser mode"),"browser"}return log60.debug("Using browser mode as default"),"browser"}calculateOptimalWorkerCount(){if("node"===this.environment){const e=os.cpus().length;return Math.max(1,e-1)}{const e="undefined"!=typeof navigator&&navigator.hardwareConcurrency||4;return Math.max(2,Math.min(e-1,4))}}async initialize(){if(this.pool)return void log60.warn("Worker pool already initialized");const e=performance.now();log60.info(`🚀 Initializing ${this.environment} worker pool with ${this.workerCount} workers...`);try{"node"===this.environment?await this.initializeNodePool():await this.initializeBrowserPool();const t=performance.now()-e;log60.info(`✅ Worker pool initialized in ${t.toFixed(2)}ms`)}catch(t){const r=t instanceof Error?t.message:String(t);if("node"===this.environment){log60.warn(`❌ Node worker pool initialization failed: ${r}`),log60.warn("🔄 Attempting fallback to browser workers...");try{this.environment="browser",await this.initializeBrowserPool();const t=performance.now()-e;return void log60.info(`✅ Successfully initialized browser worker pool as fallback in ${t.toFixed(2)}ms`)}catch(e){const t=e instanceof Error?e.message:String(e);throw log60.error(`❌ Fallback to browser workers also failed: ${t}`),new Error(`Worker pool initialization failed. Node: ${r}, Browser: ${t}`)}}throw log60.error(`❌ Failed to initialize worker pool: ${r}`),t}}async initializeNodePool(){const e=path28.join(__dirname,"worker","worker-node.js");log60.debug(`Initializing Node.js worker pool with path: ${e}`),this.pool=workerpool.pool(e,{minWorkers:this.workerCount,maxWorkers:this.workerCount,workerType:"thread"}),log60.debug(`Node.js worker pool created with ${this.workerCount} workers`,{workerPath:e})}async initializeBrowserPool(){this.pool=workerpool.pool({minWorkers:this.workerCount,maxWorkers:this.workerCount,workerType:"web"}),this.pool.proxy().then(e=>{log60.debug(`Browser worker pool created with ${this.workerCount} workers`)})}async exec(e){if(!this.pool)throw new Error("Worker pool not initialized. Call initialize() first.");try{return"node"===this.environment?await this.pool.exec("processTask",[e]):await this.pool.exec(handleWorkerTask,[e])}catch(e){const t=e instanceof Error?e.message:String(e);return log60.error(`Worker task execution failed: ${t}`),{success:!1,error:t}}}getStats(){return this.pool?{environment:this.environment,workerCount:this.workerCount,poolStats:this.pool.stats()}:null}async terminate(){this.pool?(log60.info("🧹 Terminating worker pool..."),await this.pool.terminate(),this.pool=null,log60.info("✅ Worker pool terminated")):log60.warn("Worker pool already terminated")}};init_log();var log61=getDomainLogger("application",{component:"batch-task-queue"}),BatchTaskQueue=class{queue=[];currentIndex=0;totalBatches;constructor(e){this.queue=e,this.totalBatches=e.length,log61.info(`Task queue initialized with ${this.totalBatches} batches`)}nextBatch(){if(this.currentIndex>=this.queue.length)return null;const e=this.queue[this.currentIndex];return this.currentIndex++,e}getProgress(){const e=this.currentIndex,t=this.totalBatches;return{completed:e,total:t,percentage:0===t?100:Math.round(e/t*100)}}hasMore(){return this.currentIndex<this.queue.length}getRemainingCount(){return Math.max(0,this.queue.length-this.currentIndex)}};init_ssg();import*as os2 from"os";var log62=getDomainLogger("ssg",{component:"parallel"});async function runWorkerLoop(e,t,r,i,s,n){const a=[];for(;;){const o=t.nextBatch();if(!o){log62.debug(`Worker ${r} finished - no more tasks`);break}const l=t.getProgress();log62.info(`🔄 Worker ${r} processing batch ${l.completed}/${l.total} (${o.length} tasks)`);const c={type:"process-batch",pageTasks:o},h=await e.exec(c);if(h.success&&h.data){const e=h.data;a.push(e),s.count+=e.processedCount;const t=70+Math.floor(s.count/i*29);n?.({stage:"build",message:`Rendering pages (${s.count}/${i})...`,percentage:t,pageRender:{currentPage:s.count,totalPages:i}}),log62.info(`✅ Worker ${r} completed batch: ${e.processedCount} tasks in ${e.duration.toFixed(2)}ms`)}else log62.error(`❌ Worker ${r} failed: ${h.error}`),a.push({success:!1,processedCount:0,totalCount:o.length,duration:0,errors:[h.error||"Unknown error"]})}return a}async function processSSGParallel(e,t,r,i,s){const n=performance.now(),a=process.cwd();process.chdir(e);try{i?.({stage:"config",message:"Initializing parallel SSG...",percentage:5}),i?.({stage:"pages",message:"Collecting all page tasks...",percentage:10});const r=await collectAllPageTasks(e,t);if(0===r.length)return log62.warn("⚠️ No page tasks found to process"),i?.({stage:"completion",message:"No pages to process",percentage:100}),{totalPages:0,totalBatches:0,workerCount:0,batchSize:0,totalDuration:0,parallelSpeedup:0,pagesPerSecond:0};i?.({stage:"config",message:`Found ${r.length} pages, calculating optimal worker configuration...`,percentage:20});const s=os2.cpus().length,a=Math.max(2,Math.floor(.6*s)),o=function(e,t){const r=4*t,i=Math.ceil(e/r);return Math.max(5,Math.min(50,i))}(r.length,a);log62.info(`⚙️ Using ${a} workers with batch size ${o}`),i?.({stage:"config",message:`Creating worker pool with ${a} workers...`,percentage:30});const l=new WorkerPoolManager({workerCount:a});await l.initialize(),i?.({stage:"config",message:"Initializing workers...",percentage:50}),log62.info("🔧 Initializing workers...");const c=performance.now(),h=[];for(let r=0;r<a;r++){const r={type:"init",projDir:e,moduleDir:t};h.push(l.exec(r))}await Promise.all(h);const u=performance.now()-c;log62.info(`✅ All workers initialized in ${u.toFixed(2)}ms`),i?.({stage:"build",message:`Creating ${Math.ceil(r.length/o)} task batches...`,percentage:65});const g=function(e,t){const r=[];for(let i=0;i<e.length;i+=t)r.push(e.slice(i,i+t));return log62.info(`📦 Created ${r.length} batches (${t} tasks per batch)`),r}(r,o),d=new BatchTaskQueue(g);i?.({stage:"build",message:"Starting parallel page rendering...",percentage:70}),log62.info("🏃 Starting worker loops...");const p=performance.now(),m={count:0},f=[];for(let e=0;e<a;e++)f.push(runWorkerLoop(l,d,e,r.length,m,i));const y=await Promise.all(f),w=performance.now()-p,S=y.flat(),b=S.filter(e=>e.success).length,_=S.reduce((e,t)=>e+t.processedCount,0),k=S.reduce((e,t)=>e+t.errors.length,0);await l.terminate();const v=performance.now()-n,P=_/v*1e3,C=w/_*_/w;return i?.({stage:"completion",message:`Parallel SSG completed! Processed ${_} pages with ${a} workers`,percentage:100}),log62.info("✨ Parallel SSG completed!"),log62.info("📊 Statistics:",{totalTasks:r.length,processedTasks:_,successfulBatches:b,failedBatches:S.length-b,totalErrors:k,totalDuration:`${v.toFixed(2)}ms`,processingDuration:`${w.toFixed(2)}ms`,pagesPerSecond:P.toFixed(2),parallelSpeedup:`${C.toFixed(2)}x`}),{totalPages:r.length,totalBatches:g.length,workerCount:a,batchSize:o,totalDuration:v,parallelSpeedup:C,pagesPerSecond:P}}catch(e){const t=e instanceof Error?e.message:String(e);throw log62.error(`❌ Parallel SSG failed: ${t}`),e}finally{process.chdir(a)}}init_ssg(),init_log(),init_log();import*as chokidar from"chokidar";import*as path29 from"path";import*as fs2 from"fs";var log63=getDomainLogger("web",{component:"content-file-watcher"}),ContentFileWatcher=class{constructor(e){this.config=e,this.batchDelay=e.batchDelay||500,void 0!==e.isSingleFileMode?this.isSingleFileMode=e.isSingleFileMode:this.isSingleFileMode=this.detectSingleFileMode(e.contentDirs),this.isSingleFileMode&&log63.info("Single file mode detected",{contentDirs:e.contentDirs})}watcher=null;eventQueue=[];batchTimer=null;batchDelay;callbacks=[];isSingleFileMode=!1;detectSingleFileMode(e){return 0!==e.length&&e.every(e=>{try{return fs2.statSync(e).isFile()}catch{const t=path29.extname(e).toLowerCase();return".md"===t||".markdown"===t}})}async startWatching(){this.watcher&&await this.stopWatching(),this.watcher=chokidar.watch(this.config.contentDirs,{ignored:[/(^|[\/\\])\../,/\.tmp$/,/\.swp$/,/~$/,/\.DS_Store$/,...this.config.ignorePatterns||[]],persistent:!0,ignoreInitial:!0,followSymlinks:!0,awaitWriteFinish:{stabilityThreshold:100,pollInterval:50}}),this.watcher.on("add",e=>this.queueEvent(e,"created")).on("change",e=>this.queueEvent(e,"modified")).on("unlink",e=>this.queueEvent(e,"deleted")).on("error",e=>{log63.error("File watcher error:",e)})}onFileChange(e){this.callbacks.push(e)}queueEvent(e,t){let r=e;if(this.isSingleFileMode){const t=this.config.contentDirs.findIndex(t=>path29.normalize(e)===path29.normalize(t));if(-1===t)return;{const i=this.config.projContentDirs[t];r=path29.join(i,"index.md"),log63.debug("Single file event mapped",{original:e,mapped:r})}}else{const{projContentDirs:e,contentDirs:t}=this.config;for(let i=0;i<e.length;i++){const s=e[i];for(let e=0;e<t.length;e++){const i=t[e];if(s!==i&&r.startsWith(i)){r=s+r.slice(i.length);break}}}}const i=path29.normalize(r);if(!this.isRelevantFile(i))return;const s={filePath:i,eventType:t,timestamp:Date.now(),isMarkdown:this.isMarkdownFile(i),isImage:this.isImageFile(i)};this.eventQueue.push(s),this.scheduleBatch()}isRelevantFile(e){return this.isMarkdownFile(e)||this.isImageFile(e)}isMarkdownFile(e){const t=path29.extname(e).toLowerCase();return".md"===t||".markdown"===t}isImageFile(e){const t=path29.extname(e).toLowerCase();return[".jpg",".jpeg",".png",".gif",".svg",".webp",".bmp"].includes(t)}scheduleBatch(){this.batchTimer&&clearTimeout(this.batchTimer),this.batchTimer=setTimeout(async()=>{if(this.eventQueue.length>0){const e=this.deduplicateEvents(this.eventQueue);this.eventQueue=[];for(const t of this.callbacks)try{await t(e)}catch(e){log63.error("Error processing file change events:",e)}}},this.batchDelay)}deduplicateEvents(e){const t=new Map;for(const r of e){const e=t.get(r.filePath);(!e||r.timestamp>e.timestamp)&&t.set(r.filePath,r)}return Array.from(t.values())}async stopWatching(){this.batchTimer&&(clearTimeout(this.batchTimer),this.batchTimer=null),this.watcher&&(await this.watcher.close(),this.watcher=null),this.eventQueue=[],this.callbacks=[]}};init_log();import*as http3 from"http";import*as path30 from"path";import*as fs3 from"fs/promises";import{WebSocket,WebSocketServer}from"ws";var log64=getDomainLogger("web",{component:"livereload-server"}),FoundryLiveReloadServer=class{httpServer=null;wsServer=null;clients=new Set;running=!1;config;constructor(e){this.config={port:e.port||8091,host:e.host||"localhost",livereloadPort:e.livereloadPort||35729,enableLiveReload:!1!==e.enableLiveReload,publicDir:e.publicDir}}async start(){if(this.running)log64.warn("LiveReloadServer already running");else try{await this.startHttpServer(),this.config.enableLiveReload&&await this.startLiveReloadServer(),this.running=!0}catch(e){throw log64.error("Failed to start LiveReloadServer:",e),e}}async stop(){if(this.running)try{for(const e of this.clients)e.close();this.clients.clear(),this.wsServer&&(this.wsServer.close(),this.wsServer=null),this.httpServer&&(await new Promise(e=>{this.httpServer.close(()=>e())}),this.httpServer=null),this.running=!1}catch(e){log64.error("Error stopping LiveReloadServer:",e)}}notifyReload(e){if(!this.config.enableLiveReload||0===this.clients.size)return;const t={command:"reload",liveCSS:this.shouldLiveReloadCSS(e),liveImg:this.shouldLiveReloadImages(e)};if(e&&1===e.length){const r=e[0],i=path30.extname(r).toLowerCase();".css"===i?(t.path=r,t.liveCSS=!0):[".jpg",".jpeg",".png",".gif",".svg",".webp"].includes(i)&&(t.path=r,t.liveImg=!0)}const r=JSON.stringify(t);for(const e of this.clients)e.readyState===WebSocket.OPEN&&e.send(r)}getUrl(){return`http://${this.config.host}:${this.config.port}`}isServerRunning(){return this.running}async startHttpServer(){this.httpServer=http3.createServer(async(e,t)=>{try{await this.handleHttpRequest(e,t)}catch(e){log64.error("HTTP request error:",e),t.statusCode=500,t.end("Internal Server Error")}}),await new Promise((e,t)=>{this.httpServer.listen(this.config.port,this.config.host,()=>{e()}),this.httpServer.on("error",e=>{"EADDRINUSE"===e.code?(this.config.port++,this.config.port<8099?this.httpServer.listen(this.config.port,this.config.host):t(new Error("No available ports"))):t(e)})})}async startLiveReloadServer(){this.wsServer=new WebSocketServer({port:this.config.livereloadPort,host:this.config.host}),this.wsServer.on("connection",e=>{this.clients.add(e),e.send(JSON.stringify({command:"hello",protocols:["http://livereload.com/protocols/official-7"],serverName:"foundry-livereload"})),e.on("close",()=>{this.clients.delete(e)}),e.on("message",e=>{try{JSON.parse(e.toString())}catch(t){log64.error("Invalid LiveReload message:",e.toString())}})}),this.wsServer.on("error",e=>{log64.error("LiveReload WebSocket server error:",e)})}async handleHttpRequest(e,t){const r=e.url||"/";let i=this.resolveFilePath(r);try{if((await fs3.stat(i)).isDirectory()){const e=path30.join(i,"index.html");try{await fs3.stat(e),i=e}catch{return t.statusCode=404,void t.end("Not Found")}}let e=await fs3.readFile(i);const r=this.getContentType(i);if(t.setHeader("Content-Type",r),r.includes("text/html")&&this.config.enableLiveReload){const t=e.toString(),r=this.getLiveReloadScript(),i=t.replace(/<\/body>/i,`${r}\n</body>`);e=Buffer.from(i,"utf8")}t.setHeader("Cache-Control","no-cache, no-store, must-revalidate"),t.setHeader("Pragma","no-cache"),t.setHeader("Expires","0"),t.statusCode=200,t.end(e)}catch(e){if("ENOENT"!==e.code)throw e;t.statusCode=404,t.end("Not Found")}}resolveFilePath(e){const t=e.split("?")[0].split("#")[0];let r;try{r=decodeURIComponent(t)}catch(e){log64.warn("Failed to decode URL:",t,e),r=t}const i=path30.normalize(r).replace(/^(\.\.[\/\\])+/,""),s=i.startsWith("/")?i.slice(1):i,n=path30.join(this.config.publicDir,s);return"win32"===process.platform&&n.length>260&&log64.warn("Path too long for Windows filesystem:",n),"win32"===process.platform&&/[<>:"|?*\x00-\x1f]/.test(s)&&log64.warn("Path contains invalid characters for Windows:",s),n}getContentType(e){return{".html":"text/html; charset=utf-8",".css":"text/css; charset=utf-8",".js":"application/javascript; charset=utf-8",".json":"application/json; charset=utf-8",".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".svg":"image/svg+xml",".webp":"image/webp",".ico":"image/x-icon",".woff":"font/woff",".woff2":"font/woff2",".ttf":"font/ttf",".eot":"application/vnd.ms-fontobject",".xml":"application/xml; charset=utf-8",".txt":"text/plain; charset=utf-8"}[path30.extname(e).toLowerCase()]||"application/octet-stream"}getLiveReloadScript(){return`\n<script>\n(function() {\n 'use strict';\n \n var protocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:';\n var address = protocol + '//${this.config.host}:${this.config.livereloadPort}/livereload';\n var socket = new WebSocket(address);\n \n socket.onmessage = function(event) {\n var data = JSON.parse(event.data);\n \n if (data.command === 'reload') {\n if (data.liveCSS) {\n // 热更新 CSS\n reloadCSS();\n } else if (data.liveImg) {\n // 热更新图片\n reloadImages();\n } else {\n // 完整页面刷新\n window.location.reload();\n }\n }\n };\n \n socket.onopen = function() {\n console.log('LiveReload connected');\n };\n \n socket.onclose = function() {\n console.log('LiveReload disconnected');\n // 尝试重连\n setTimeout(function() {\n window.location.reload();\n }, 1000);\n };\n \n function reloadCSS() {\n var links = document.querySelectorAll('link[rel="stylesheet"]');\n for (var i = 0; i < links.length; i++) {\n var link = links[i];\n var href = link.href;\n if (href) {\n var url = new URL(href);\n url.searchParams.set('_t', Date.now().toString());\n link.href = url.toString();\n }\n }\n console.log('CSS reloaded');\n }\n \n function reloadImages() {\n var images = document.querySelectorAll('img');\n for (var i = 0; i < images.length; i++) {\n var img = images[i];\n var src = img.src;\n if (src) {\n var url = new URL(src);\n url.searchParams.set('_t', Date.now().toString());\n img.src = url.toString();\n }\n }\n console.log('Images reloaded');\n }\n})();\n<\/script>`}shouldLiveReloadCSS(e){return!!e&&e.some(e=>".css"===path30.extname(e).toLowerCase())}shouldLiveReloadImages(e){if(!e)return!1;const t=[".jpg",".jpeg",".png",".gif",".svg",".webp"];return e.some(e=>t.includes(path30.extname(e).toLowerCase()))}};init_log();import*as http4 from"http";import*as path31 from"path";import*as fs4 from"fs/promises";var log65=getDomainLogger("web",{component:"electron-livereload-server"}),ElectronLiveReloadServer=class{httpServer=null;running=!1;config;stateFilePath;constructor(e){this.config={port:e.port||8091,host:e.host||"localhost",livereloadPort:e.livereloadPort||35729,enableLiveReload:!1!==e.enableLiveReload,publicDir:e.publicDir},this.stateFilePath=path31.join(this.config.publicDir,".foundry-livereload-state.json")}async start(){if(this.running)log65.warn("ElectronLiveReloadServer already running");else try{await this.startHttpServer(),this.config.enableLiveReload&&await this.initStateFile(),this.running=!0,log65.info(`ElectronLiveReloadServer started at ${this.getUrl()}`)}catch(e){throw log65.error("Failed to start ElectronLiveReloadServer:",e),e}}async stop(){if(this.running)try{this.httpServer&&(await new Promise(e=>{this.httpServer.close(()=>e())}),this.httpServer=null);try{await fs4.unlink(this.stateFilePath)}catch(e){}this.running=!1,log65.info("ElectronLiveReloadServer stopped")}catch(e){log65.error("Error stopping ElectronLiveReloadServer:",e)}}notifyReload(e){if(!this.config.enableLiveReload)return;const t={timestamp:Date.now(),command:"reload",liveCSS:this.shouldLiveReloadCSS(e),liveImg:this.shouldLiveReloadImages(e),...e&&{changedFiles:e}};if(e&&1===e.length){const r=e[0],i=path31.extname(r).toLowerCase();(".css"===i||[".jpg",".jpeg",".png",".gif",".svg",".webp"].includes(i))&&(t.path=r)}this.writeStateFile(t).catch(e=>{log65.error("Failed to write state file:",e)})}getUrl(){return`http://${this.config.host}:${this.config.port}`}isServerRunning(){return this.running}async initStateFile(){const e={timestamp:Date.now(),command:"hello"};await this.writeStateFile(e)}async writeStateFile(e){try{await fs4.writeFile(this.stateFilePath,JSON.stringify(e),"utf8")}catch(e){log65.error("Failed to write LiveReload state file:",e)}}async startHttpServer(){this.httpServer=http4.createServer(async(e,t)=>{try{await this.handleHttpRequest(e,t)}catch(e){log65.error("HTTP request error:",e),t.statusCode=500,t.end("Internal Server Error")}}),await new Promise((e,t)=>{this.httpServer.listen(this.config.port,this.config.host,()=>{e()}),this.httpServer.on("error",e=>{"EADDRINUSE"===e.code?(this.config.port++,this.config.port<8099?this.httpServer.listen(this.config.port,this.config.host):t(new Error("No available ports"))):t(e)})})}async handleHttpRequest(e,t){const r=e.url||"/";if(r.startsWith("/.foundry-livereload-state.json"))try{const e=await fs4.readFile(this.stateFilePath,"utf8");return t.setHeader("Content-Type","application/json; charset=utf-8"),t.setHeader("Cache-Control","no-cache, no-store, must-revalidate"),t.setHeader("Pragma","no-cache"),t.setHeader("Expires","0"),t.statusCode=200,void t.end(e)}catch(e){return void("ENOENT"===e.code?(t.statusCode=404,t.end("State file not found")):(t.statusCode=500,t.end("Internal Server Error")))}let i=this.resolveFilePath(r);try{if((await fs4.stat(i)).isDirectory()){const e=path31.join(i,"index.html");try{await fs4.stat(e),i=e}catch{return t.statusCode=404,void t.end("Not Found")}}let e=await fs4.readFile(i);const r=this.getContentType(i);if(t.setHeader("Content-Type",r),r.includes("text/html")&&this.config.enableLiveReload){const t=e.toString(),r=this.getLiveReloadScript(),i=t.replace(/<\/body>/i,`${r}\n</body>`);e=Buffer.from(i,"utf8")}t.setHeader("Cache-Control","no-cache, no-store, must-revalidate"),t.setHeader("Pragma","no-cache"),t.setHeader("Expires","0"),t.statusCode=200,t.end(e)}catch(e){if("ENOENT"!==e.code)throw e;t.statusCode=404,t.end("Not Found")}}resolveFilePath(e){const t=e.split("?")[0].split("#")[0];let r;try{r=decodeURIComponent(t)}catch(e){log65.warn("Failed to decode URL:",t,e),r=t}const i=path31.normalize(r).replace(/^(\.\.[\/\\])+/,""),s=i.startsWith("/")?i.slice(1):i;return path31.join(this.config.publicDir,s)}getContentType(e){return{".html":"text/html; charset=utf-8",".css":"text/css; charset=utf-8",".js":"application/javascript; charset=utf-8",".json":"application/json; charset=utf-8",".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".svg":"image/svg+xml",".webp":"image/webp",".ico":"image/x-icon",".woff":"font/woff",".woff2":"font/woff2",".ttf":"font/ttf",".eot":"application/vnd.ms-fontobject",".xml":"application/xml; charset=utf-8",".txt":"text/plain; charset=utf-8"}[path31.extname(e).toLowerCase()]||"application/octet-stream"}getLiveReloadScript(){return"\n<script>\n(function() {\n 'use strict';\n \n var stateFilePath = '/.foundry-livereload-state.json';\n var storageKey = 'foundry-livereload-last-timestamp';\n var lastTimestamp = 0;\n var pollInterval = 500; // 500ms 轮询间隔\n \n // 从 localStorage 恢复上次的时间戳,避免页面刷新后重复触发\n try {\n var stored = localStorage.getItem(storageKey);\n if (stored) {\n lastTimestamp = parseInt(stored, 10) || 0;\n }\n } catch (error) {\n // localStorage 可能不可用,使用默认值\n console.warn('LiveReload: localStorage not available, may cause duplicate reloads');\n }\n \n function checkForReload() {\n fetch(stateFilePath + '?_t=' + Date.now(), { cache: 'no-cache' })\n .then(function(response) {\n if (!response.ok) {\n throw new Error('Failed to fetch state file');\n }\n return response.json();\n })\n .then(function(state) {\n if (state.timestamp > lastTimestamp) {\n // 更新时间戳并保存到 localStorage\n lastTimestamp = state.timestamp;\n try {\n localStorage.setItem(storageKey, lastTimestamp.toString());\n } catch (error) {\n // localStorage 写入失败,忽略\n }\n \n if (state.command === 'reload') {\n if (state.liveCSS) {\n // 热更新 CSS\n reloadCSS();\n } else if (state.liveImg) {\n // 热更新图片\n reloadImages();\n } else {\n // 完整页面刷新\n window.location.reload();\n }\n }\n }\n })\n .catch(function(error) {\n // 静默处理错误,避免控制台噪音\n });\n }\n \n function reloadCSS() {\n var links = document.querySelectorAll('link[rel=\"stylesheet\"]');\n for (var i = 0; i < links.length; i++) {\n var link = links[i];\n var href = link.href;\n if (href) {\n var url = new URL(href);\n url.searchParams.set('_t', Date.now().toString());\n link.href = url.toString();\n }\n }\n console.log('CSS reloaded');\n }\n \n function reloadImages() {\n var images = document.querySelectorAll('img');\n for (var i = 0; i < images.length; i++) {\n var img = images[i];\n var src = img.src;\n if (src) {\n var url = new URL(src);\n url.searchParams.set('_t', Date.now().toString());\n img.src = url.toString();\n }\n }\n console.log('Images reloaded');\n }\n \n // 开始轮询\n setInterval(checkForReload, pollInterval);\n \n // 初始检查\n checkForReload();\n})();\n<\/script>"}shouldLiveReloadCSS(e){return!!e&&e.some(e=>".css"===path31.extname(e).toLowerCase())}shouldLiveReloadImages(e){if(!e)return!1;const t=[".jpg",".jpeg",".png",".gif",".svg",".webp"];return e.some(e=>t.includes(path31.extname(e).toLowerCase()))}};var log66=getDomainLogger("build",{component:"incremental-coordinator"}),IncrementalBuildCoordinator=class{constructor(e){if(this.config=e,e.enableWatching){const t={contentDirs:e.contentDirs,projContentDirs:e.projContentDirs||e.contentDirs,batchDelay:e.batchDelay||500};this.fileWatcher=new ContentFileWatcher(t),this.fileWatcher.onFileChange(e=>this.handleFileChanges(e))}if(!1!==e.liveReload?.enabled){const t={port:e.liveReload?.port||8091,host:e.liveReload?.host||"localhost",livereloadPort:e.liveReload?.livereloadPort||35729,publicDir:e.publicDir,enableLiveReload:!0};this.liveReloadServer=function(e){return"undefined"!=typeof globalThis&&globalThis.window&&globalThis.window.process&&globalThis.window.process.type||"undefined"!=typeof process&&process.versions&&process.versions.electron||"undefined"!=typeof process&&process.env&&(process.env.ELECTRON_RUN_AS_NODE||process.env.ELECTRON_NO_ATTACH_CONSOLE)?new ElectronLiveReloadServer(e):new FoundryLiveReloadServer(e)}(t)}}fileWatcher;liveReloadServer;buildInProgress=!1;initialized=!1;domainInstances;async initialize(){this.initialized?log66.warn("IncrementalBuildCoordinator already initialized"):(await this.performFullBuildAndCacheDomains(),this.initialized=!0,this.config.onSuccess&&await this.config.onSuccess())}async performFullBuildAndCacheDomains(){try{this.domainInstances=await serveSSG(this.config.projDir,this.config.modulesDir,this.config.markdown,this.config.progressCallback,this.config.httpClient)}catch(e){throw log66.error("Failed to perform full build and cache domains:",e),e}}async startWatching(){if(!this.initialized)throw new Error("Must call initialize() before startWatching()");this.config.enableWatching&&this.fileWatcher&&await this.fileWatcher.startWatching(),this.liveReloadServer&&await this.liveReloadServer.start()}async stopWatching(){this.fileWatcher&&await this.fileWatcher.stopWatching(),this.liveReloadServer&&await this.liveReloadServer.stop()}async handleFileChanges(e){if(this.buildInProgress)setTimeout(()=>this.handleFileChanges(e),1e3);else try{if(this.buildInProgress=!0,this.needFullRebuild(e))return void await this.performFullRebuild(e);await this.performIncrementalBuild(e)}finally{this.buildInProgress=!1}}needFullRebuild(e){return e.some(e=>"deleted"===e.eventType||"created"===e.eventType)}async performIncrementalBuild(e){if(!this.domainInstances)return log66.error("Domain instances not available, falling back to full rebuild"),void await this.performFullRebuild(e);try{const t=await this.domainInstances.fs.getFileMetaInfos(this.getEventsFilePaths(e));if(await this.domainInstances.content.handleChangeFiles(t),await this.domainInstances.site.renderAllLanguages(),this.liveReloadServer){const t=e.map(e=>e.filePath);this.liveReloadServer.notifyReload(t)}this.config.onSuccess&&await this.config.onSuccess()}catch(t){log66.error("Incremental build failed, falling back to full rebuild:",t),await this.performFullRebuild(e)}}getEventsFilePaths(e){return e.map(e=>e.filePath)}async performFullRebuild(e){if(await processSSGWithProgress(this.config.projDir,this.config.modulesDir,this.config.markdown,e=>{log66.info(`Rebuild progress: ${e.stage} - ${e.percentage}%`)},this.config.httpClient),this.liveReloadServer){const t=e.map(e=>e.filePath);this.liveReloadServer.notifyReload(t)}this.config.onSuccess&&await this.config.onSuccess()}isInitialized(){return this.initialized}isBuildInProgress(){return this.buildInProgress}getConfig(){return{...this.config}}getServerUrl(){return this.liveReloadServer?this.liveReloadServer.getUrl():""}getLiveReloadStatus(){if(!this.liveReloadServer)return{running:!1};const e=this.liveReloadServer.isServerRunning();return{running:e,...e&&{url:this.liveReloadServer.getUrl()}}}};async function startIncrementalBuild(e){const t=new IncrementalBuildCoordinator(e);return await t.initialize(),e.enableWatching&&await t.startWatching(),t}init_log(),getDomainLogger("build",{component:"incremental-ssg"}),init_markdown5(),init_page_filter(),init_container(),init_workspace3(),init_identity3(),init_publish2(),init_log(),init_workspace2(),init_fetch_http_client();var ObsidianAuthService=class{constructor(e,t){this.httpClient=e,this.identityAdapter=t}async getStatus(e){try{const t=await this.identityAdapter.getIdentityService(e,this.httpClient),r=t.getStatus(),i={isAuthenticated:r.isAuthenticated,serverUrl:r.serverUrl,hasSyncConfig:r.hasSyncConfig,...r.license?{license:r.license}:{},...r.email?{email:r.email}:{}};if(r.isAuthenticated){const e=t.getToken();e&&(i.token=e)}return r.syncConfig&&(i.syncConfig={dbEndpoint:r.syncConfig.dbEndpoint,dbName:r.syncConfig.dbName,email:r.syncConfig.email,userDir:r.syncConfig.userDir,status:r.syncConfig.status,isActive:r.syncConfig.isActive}),{success:!0,message:r.isAuthenticated?`Authenticated as ${r.email}`:"Not authenticated",data:i}}catch(e){const t=e.message;return t.includes("No workspace found")?{success:!1,message:"No workspace found. Please initialize workspace first.",error:t}:{success:!1,message:`Failed to get status: ${t}`,error:t}}}async getConfig(e){try{const t=(await this.identityAdapter.getIdentityService(e,this.httpClient)).getServerConfig(),r=t.getWebsiteUrl(),i={apiUrl:t.getApiUrl()};return r&&(i.websiteUrl=r),{success:!0,message:"Server configuration retrieved",data:i}}catch(e){const t=e.message;return t.includes("No workspace found")?{success:!1,message:"No workspace found. Please initialize workspace first.",error:t}:{success:!1,message:`Failed to get config: ${t}`,error:t}}}async updateConfig(e,t){try{const r={};t.apiUrl&&(r.apiUrl=t.apiUrl),t.websiteUrl&&(r.websiteUrl=t.websiteUrl);const i=await this.identityAdapter.getIdentityService(e,this.httpClient);await i.updateServerConfig(r);const s=i.getServerConfig(),n=s.getWebsiteUrl(),a={apiUrl:s.getApiUrl()};return n&&(a.websiteUrl=n),{success:!0,message:"Server configuration updated",data:a}}catch(e){const t=e.message;return t.includes("No workspace found")?{success:!1,message:"No workspace found. Please initialize workspace first.",error:t}:{success:!1,message:`Failed to update config: ${t}`,error:t}}}};init_log();var log85=getDomainLogger("obsidian-license",{component:"interface"}),ObsidianLicenseService=class{constructor(e,t){this.httpClient=e,this.identityAdapter=t}async requestTrial(e,t){try{if(!t)return{success:!1,error:"Email is required"};log85.info("Requesting trial license (without activation)",{email:t});const r=await this.identityAdapter.getIdentityService(e,this.httpClient),i=await r.requestTrial(t);return{success:!0,message:"Trial license requested successfully",data:{email:i.email,licenseKey:i.license_key,password:i.password,validityDays:i.validity_days}}}catch(e){return log85.error("Trial license request failed",e),{success:!1,error:e.message}}}async requestAndActivateTrial(e,t){try{if(!t)return{success:!1,error:"Email is required"};log85.info("Requesting and activating trial license",{email:t});const r=await this.identityAdapter.getIdentityService(e,this.httpClient),i=(await r.requestAndActivateTrial(t)).getLicense();return i?{success:!0,message:"Trial license activated successfully",data:this.buildLicenseInfo(i)}:{success:!1,error:"Trial license request succeeded but license not found"}}catch(e){return log85.error("Trial license request and activation failed",e),{success:!1,error:e.message}}}async loginWithLicense(e,t){try{if(!t)return{success:!1,error:"License key is required"};log85.info("Logging in with license key",{licenseKey:t});const r=await this.identityAdapter.getIdentityService(e,this.httpClient),i=await r.loginWithLicense(t);return log85.info("Login successful",{email:i.getEmail().getValue(),hasToken:!!i.getToken()}),{success:!0,message:"Logged in successfully. Token saved.",data:{}}}catch(e){return log85.error("License login failed",e),{success:!1,error:e.message}}}async activateLicense(e,t){try{if(!t)return{success:!1,error:"License key is required"};log85.info("Activating license",{licenseKey:t});const r=await this.identityAdapter.getIdentityService(e,this.httpClient),i=await r.activateLicense(t),s=i.getLicense(),n=i.getSyncConfig();if(!s)return{success:!1,error:"License activation succeeded but license not found"};const a=this.buildLicenseInfo(s);return a.user={email:i.getEmail().getValue(),userDir:n?.getUserDir()||""},a.activation={activated:s.isActivated(),firstTime:s.isFirstTime()},n&&s.getFeatures().syncEnabled&&(a.sync={enabled:!0,status:n.getStatus(),dbEndpoint:n.getDbEndpoint(),dbName:n.getDbName(),email:n.getEmail(),dbPassword:n.getDbPassword(),userDir:n.getUserDir(),liveSyncConfig:n.toObsidianLiveSyncFormat()},log85.info("Sync configuration included in activation response",{dbName:n.getDbName(),email:n.getEmail(),status:n.getStatus()})),{success:!0,message:"License activated successfully",data:a}}catch(e){return log85.error("License activation failed",e),{success:!1,error:e.message}}}async getLicenseInfo(e){try{const t=await this.identityAdapter.getIdentityService(e,this.httpClient),r=t.getLicense();if(!r)return{success:!0,message:"No active license"};const i=this.buildLicenseInfo(r),s=t.getCurrentUser();if(s){const e=s.getSyncConfig();i.user={email:s.getEmail().getValue(),userDir:e?.getUserDir()||""}}return{success:!0,data:i}}catch(e){return log85.error("Failed to get license info",e),{success:!1,error:e.message}}}async getLicenseUsage(e){try{const t=await this.identityAdapter.getIdentityService(e,this.httpClient),r=await t.getLicenseUsage();return r?{success:!0,data:{licenseKey:r.license_key,plan:r.plan,devices:{count:r.devices.count,max:r.features.max_devices,list:r.devices.devices.map(e=>({id:e.id,name:e.device_name,type:e.device_type,status:e.status,lastSeenAt:e.last_seen_at}))},ips:{count:r.ips.count,max:r.features.max_ips,list:r.ips.ips.map(e=>({ip:e.ip_address,city:e.city,region:e.region,country:e.country,status:e.status,lastSeenAt:e.last_seen_at}))},disk:{syncUsage:Number(r.disks.sync_disk_usage)||0,publishUsage:Number(r.disks.publish_disk_usage)||0,totalUsage:Number(r.disks.total_disk_usage)||0,maxStorage:r.features.max_storage,unit:r.disks.unit}}}:{success:!1,error:"Failed to get license usage information"}}catch(e){return log85.error("Failed to get license usage",e),{success:!1,error:e.message}}}async resetUsage(e,t){try{if(!t)return{success:!1,error:"This will delete all sync and publish data! Set force=true to confirm."};const r=await this.identityAdapter.getIdentityService(e,this.httpClient),i=await r.resetUsage();return i.success?{success:!0,message:"License usage data has been reset successfully",data:i}:{success:!1,error:i.message||"Unknown error"}}catch(e){return log85.error("Failed to reset license usage",e),{success:!1,error:e.message}}}async hasActiveLicense(e){try{const t=await this.getLicenseInfo(e);return t.success&&void 0!==t.data&&!t.data.isExpired}catch{return!1}}buildLicenseInfo(e){const t=e.getFeatures();return{key:e.getKey(),plan:e.getFormattedPlan(),isExpired:e.isExpired(),expires:e.getFormattedExpiresAt(),expiresAt:e.getExpiresAt(),daysRemaining:e.getDaysRemaining(),isTrial:e.isTrial(),features:{maxDevices:t.maxDevices,maxIps:t.maxIps,syncEnabled:t.syncEnabled,syncQuota:t.syncQuota,publishEnabled:t.publishEnabled,maxSites:t.maxSites,maxStorage:t.maxStorage,customDomain:t.customDomain,customSubDomain:t.customSubDomain}}}};init_log();var log86=getDomainLogger("obsidian-workspace",{component:"interface"}),ObsidianWorkspaceService=class{constructor(e){this.workspaceAdapter=e}buildWorkspaceInfo(e){const t=e.getInfo(),r=e.getProjects();return{id:t.id,name:t.name,path:t.path,createdAt:t.createdAt.toISOString(),modulesDir:t.modulesDir,projectsDir:t.projectsDir,projectCount:t.projectCount,projects:r.map(e=>{const t=e.getMetadata(),r=t.buildHistory||[],i=r.length>0?new Date(r[r.length-1].timestamp).toISOString():void 0,s={id:t.id,name:t.name,path:e.getPath(),createdAt:new Date(t.createdAt).toISOString()};return i&&(s.lastBuild=i),s})}}async initWorkspace(e,t={}){try{log86.info("Initializing workspace from Obsidian",{workspacePath:e,options:t});const r=this.workspaceAdapter.getWorkspaceAppService(),i={};t.name&&(i.name=t.name),t.modulesDir&&(i.modulesDir=t.modulesDir),t.projectsDir&&(i.projectsDir=t.projectsDir);const s=await r.createWorkspace(e,i),n=this.buildWorkspaceInfo(s);return log86.info("Workspace initialized successfully",{workspaceId:n.id,name:n.name,projectCount:n.projects.length}),{success:!0,message:`Workspace initialized: ${n.name}`,data:n}}catch(e){return log86.error("Failed to initialize workspace",e),{success:!1,message:"Failed to initialize workspace",error:e.message}}}async getWorkspaceInfo(e){try{log86.info("Getting workspace info from Obsidian",{workspacePath:e});const t=this.workspaceAdapter.getWorkspaceAppService(),r=await t.loadWorkspace(e),i=this.buildWorkspaceInfo(r);return log86.info("Workspace info retrieved",{workspaceId:i.id,name:i.name,projectCount:i.projects.length}),{success:!0,data:i}}catch(e){return log86.error("Failed to get workspace info",e),{success:!1,message:"Failed to get workspace info",error:e.message}}}async workspaceExists(e){try{log86.debug("Checking workspace existence",{workspacePath:e});const t=this.workspaceAdapter.getFileSystemRepository(),r=this.workspaceAdapter.getWorkspaceFactory(),i=await t.resolvePath(e);return{success:!0,data:await r.isWorkspace(i)}}catch(e){return log86.error("Failed to check workspace existence",e),{success:!1,error:e.message,data:!1}}}};init_log();var log87=getDomainLogger("obsidian-config",{component:"interface"}),ObsidianGlobalConfigService=class{constructor(e){this.workspaceAdapter=e}async get(e,t){try{log87.info("Getting global config",{workspacePath:e,key:t});const r=this.workspaceAdapter.getWorkspaceAppService(),i=await r.loadWorkspace(e),s=await i.getConfig(t);return void 0===s?{success:!1,error:`Configuration key not found: ${t}`}:{success:!0,data:{key:t,value:s}}}catch(e){return log87.error("Failed to get global config",e),{success:!1,error:e.message}}}async set(e,t,r){try{log87.info("Setting global config",{workspacePath:e,key:t});const i=this.workspaceAdapter.getWorkspaceAppService(),s=await i.loadWorkspace(e);return await s.setConfig(t,r),await i.saveWorkspace(s),{success:!0,message:`Configuration updated: ${t}`,data:{key:t,value:r}}}catch(e){return log87.error("Failed to set global config",e),{success:!1,error:e.message}}}async list(e){try{log87.info("Listing global config",{workspacePath:e});const t=this.workspaceAdapter.getWorkspaceAppService(),r=await t.loadWorkspace(e);return{success:!0,data:{config:await r.getAllConfig(),scope:"global"}}}catch(e){return log87.error("Failed to list global config",e),{success:!1,error:e.message}}}async unset(e,t){try{log87.info("Unsetting global config",{workspacePath:e,key:t});const r=this.workspaceAdapter.getWorkspaceAppService(),i=await r.loadWorkspace(e);return await i.unsetConfig(t)?(await r.saveWorkspace(i),{success:!0,message:`Configuration deleted: ${t}`,data:{key:t}}):{success:!1,error:`Configuration key not found: ${t}`}}catch(e){return log87.error("Failed to unset global config",e),{success:!1,error:e.message}}}async getConfigPath(e){try{const t=this.workspaceAdapter.getWorkspaceAppService();return{success:!0,data:{path:(await t.loadWorkspace(e)).getConfigPath()}}}catch(e){return log87.error("Failed to get global config path",e),{success:!1,error:e.message}}}},ObsidianProjectConfigService=class{constructor(e){this.workspaceAdapter=e}async get(e,t,r){try{log87.info("Getting project config",{workspacePath:e,projectName:t,key:r});const i=this.workspaceAdapter.getWorkspaceAppService(),{workspace:s,project:n}=await i.loadWorkspaceAndProject(t,e);await n.loadConfig();const a=n.getConfigValue(r);return void 0===a?{success:!1,error:`Configuration key not found: ${r}`}:{success:!0,data:{key:r,value:a,project:n.getName()}}}catch(e){return log87.error("Failed to get project config",e),{success:!1,error:e.message}}}async set(e,t,r,i){try{log87.info("Setting project config",{workspacePath:e,projectName:t,key:r});const s=this.workspaceAdapter.getWorkspaceAppService(),{workspace:n,project:a}=await s.loadWorkspaceAndProject(t,e);return await a.loadConfig(),a.setConfigValue(r,i),await s.saveProject(a),{success:!0,message:`Configuration updated: ${r}`,data:{key:r,value:i,project:a.getName()}}}catch(e){return log87.error("Failed to set project config",e),{success:!1,error:e.message}}}async setAll(e,t,r){try{log87.info("Setting entire project config",{workspacePath:e,projectName:t});const i=this.workspaceAdapter.getWorkspaceAppService(),{workspace:s,project:n}=await i.loadWorkspaceAndProject(t,e);return await n.loadConfig(),n.setConfig(r),await i.saveProject(n),{success:!0,message:"Project configuration fully updated",data:{config:r,scope:"project",project:n.getName()}}}catch(e){return log87.error("Failed to set entire project config",e),{success:!1,error:e.message}}}async list(e,t){try{log87.info("Listing project config",{workspacePath:e,projectName:t});const r=this.workspaceAdapter.getWorkspaceAppService(),{workspace:i,project:s}=await r.loadWorkspaceAndProject(t,e);return await s.loadConfig(),{success:!0,data:{config:s.getConfig()||{},scope:"project",project:s.getName()}}}catch(e){return log87.error("Failed to list project config",e),{success:!1,error:e.message}}}async unset(e,t,r){try{log87.info("Unsetting project config",{workspacePath:e,projectName:t,key:r});const i=this.workspaceAdapter.getWorkspaceAppService(),{workspace:s,project:n}=await i.loadWorkspaceAndProject(t,e);return await n.loadConfig(),n.unsetConfigValue(r)?(await i.saveProject(n),{success:!0,message:`Configuration deleted: ${r}`,data:{key:r,project:n.getName()}}):{success:!1,error:`Configuration key not found: ${r}`}}catch(e){return log87.error("Failed to unset project config",e),{success:!1,error:e.message}}}async getConfigPath(e,t){try{const r=this.workspaceAdapter.getWorkspaceAppService(),{workspace:i,project:s}=await r.loadWorkspaceAndProject(t,e);return{success:!0,data:{path:s.getConfigPath(),project:s.getName()}}}catch(e){return log87.error("Failed to get project config path",e),{success:!1,error:e.message}}}};init_log();var log88=getDomainLogger("obsidian-project",{component:"interface"}),ObsidianProjectService=class{constructor(e){this.workspaceAdapter=e}async createProject(e){try{const{name:t,workspacePath:r,sourceFile:i,sourceFolder:s}=e;if(!t)return{success:!1,error:"Project name is required"};log88.info("Creating project from Obsidian",{name:t,workspacePath:r,hasSourceFile:!!i,hasSourceFolder:!!s});const n=this.workspaceAdapter.getWorkspaceAppService(),a=await n.loadWorkspace(r);return i?await this.createProjectFromFile(a,e):s?await this.createProjectFromFolder(a,e):await this.createEmptyProject(a,e)}catch(e){return log88.error("Failed to create project",e),{success:!1,message:"Failed to create project",error:e.message}}}async createProjectFromFile(e,t){const{name:r,sourceFile:i,theme:s,language:n,type:a="site"}=t;log88.info("Creating project from file",{name:r,sourceFile:i,type:a});const o={type:a,theme:s||"https://gohugo.net/note.zip?version=1.2",language:n||"en"},l=this.workspaceAdapter.getWorkspaceAppService(),c=await l.createProjectFromFile(e,r,i,o),h=await this.buildProjectInfo(c,o);return log88.info("Project created from file",{projectId:h.id,name:h.name,type:a}),{success:!0,message:`Project created from file: ${r}`,data:h}}async createProjectFromFolder(e,t){const{name:r,sourceFolder:i,theme:s,language:n,type:a="site"}=t;log88.info("Creating project from folder",{name:r,sourceFolder:i,type:a});const o={type:a,language:n||"en"};s&&(o.theme=s);const l=this.workspaceAdapter.getWorkspaceAppService(),c=await l.createProjectFromFolder(e,r,i,o),h=await this.buildProjectInfo(c,{...s?{theme:s}:{},language:o.language});return log88.info("Project created from folder",{projectId:h.id,name:h.name,type:a,contentLinks:h.contentLinks?.length||0,hasStaticLink:!!h.staticLink}),{success:!0,message:`Project created from folder: ${r}`,data:h}}async createEmptyProject(e,t){const{name:r,theme:i,language:s,createSampleContent:n=!0,type:a="site"}=t;log88.info("Creating empty project",{name:r,type:a});const o={type:a,language:s||"en",createSampleContent:n};i&&(o.theme=i);const l=this.workspaceAdapter.getWorkspaceAppService(),c=await l.createProject(e,r,o),h=await this.buildProjectInfo(c,{...i?{theme:i}:{},language:o.language});return log88.info("Empty project created",{projectId:h.id,name:h.name,type:a}),{success:!0,message:`Project created: ${r}`,data:h}}async buildProjectInfo(e,t){const r=e.getMetadata(),i=e.getContentLinks(),s=e.getStaticLink(),n=e.getFileLink(),a=e.getSupportedLanguagesFromLinks(),o={id:r.id,name:r.name,type:r.type,path:e.getPath(),createdAt:new Date(r.createdAt).toISOString(),updatedAt:new Date(r.updatedAt).toISOString()};t.theme&&(o.theme=t.theme),t.language&&(o.language=t.language),n&&(o.fileLink={sourcePath:n.sourcePath,targetPath:n.targetPath,isSymlink:n.isSymlink}),i&&i.length>0&&(o.contentLinks=i.map(e=>({sourcePath:e.sourcePath,languageCode:e.languageCode,weight:e.weight}))),s&&(o.staticLink={sourcePath:s.sourcePath}),a&&a.length>0&&(o.languages=a);try{await e.loadConfig();const t=e.getConfigValue("publish.method");t&&(o.publishMethod=t)}catch(e){log88.debug("Failed to get publish method from config",{error:e})}return o}async listProjects(e){try{log88.info("Listing projects from Obsidian",{workspacePath:e});const t=this.workspaceAdapter.getWorkspaceAppService(),r=(await t.loadWorkspace(e)).getProjects(),i=await Promise.all(r.map(async e=>{const t=e.getMetadata(),r=e.getContentLinks(),i=e.getStaticLink(),s=e.getFileLink(),n=e.getSupportedLanguagesFromLinks(),a={id:t.id,name:t.name,type:t.type,path:e.getPath(),createdAt:new Date(t.createdAt).toISOString(),updatedAt:new Date(t.updatedAt).toISOString()};s&&(a.fileLink={sourcePath:s.sourcePath,targetPath:s.targetPath,isSymlink:s.isSymlink}),r&&r.length>0&&(a.contentLinks=r.map(e=>({sourcePath:e.sourcePath,languageCode:e.languageCode,weight:e.weight}))),i&&(a.staticLink={sourcePath:i.sourcePath}),n&&n.length>0&&(a.languages=n);try{await e.loadConfig();const t=e.getConfigValue("publish.method");t&&(a.publishMethod=t)}catch(e){log88.debug("Failed to get publish method from config",{projectName:t.name,error:e})}return a}));return log88.info("Projects listed",{count:i.length}),{success:!0,data:i}}catch(e){return log88.error("Failed to list projects",e),{success:!1,error:e.message}}}async getProjectInfo(e,t){try{log88.info("Getting project info from Obsidian",{workspacePath:e,projectName:t});const r=this.workspaceAdapter.getWorkspaceAppService(),i=(await r.loadWorkspace(e)).findProject(t);return i?{success:!0,data:await this.buildProjectInfo(i,{})}:{success:!1,error:`Project not found: ${t}`}}catch(e){return log88.error("Failed to get project info",e),{success:!1,error:e.message}}}async deleteProject(e,t,r){try{log88.info("Deleting project from Obsidian",{workspacePath:e,projectIdOrName:t,deleteFiles:r?.deleteFiles});const i=this.workspaceAdapter.getWorkspaceAppService(),s=await i.loadWorkspace(e),n=s.findProject(t);if(!n)return{success:!1,error:`Project not found: ${t}`};const a=n.getName();return await i.deleteProject(s,t,r),log88.info("Project deleted successfully",{projectName:a,deleteFiles:r?.deleteFiles}),{success:!0,message:`Project deleted: ${a}`}}catch(e){return log88.error("Failed to delete project",e),{success:!1,error:e.message}}}async scanFolderStructure(e){try{log88.info("Scanning folder structure from Obsidian",{folderPath:e});const t=this.workspaceAdapter.getWorkspaceAppService(),r=await t.scanFolderStructure(e),i=r.getStaticFolder(),s={rootPath:r.getRootPath(),isStructured:r.getIsStructured(),contentFolders:r.getContentFolders(),staticFolder:i?{path:i.path}:void 0,isValid:r.isValid(),isMultilingual:r.isMultilingual(),supportedLanguages:r.getSupportedLanguages(),defaultLanguage:r.getDefaultContentFolder()?.languageCode,summary:r.getSummary()};return log88.info("Folder structure scanned",{isStructured:s.isStructured,contentFolders:s.contentFolders.length,isMultilingual:s.isMultilingual,languages:s.supportedLanguages}),{success:!0,message:"Folder structure scanned successfully",data:s}}catch(e){return log88.error("Failed to scan folder structure",e),{success:!1,error:e.message}}}};init_log(),init_ssg();import path40 from"path";import{promises as fs13}from"fs";var log89=getDomainLogger("obsidian-build",{component:"interface"}),ObsidianBuildService=class{constructor(e){this.workspaceAdapter=e}async buildProject(e){try{const{workspacePath:t,projectNameOrPath:r,destination:i,modulesDir:s,contentDirs:n,clean:a=!1,parallel:o=!1,snapshot:l=!1,snapshotName:c}=e;log89.info("Building project from Obsidian",{projectNameOrPath:r,parallel:o,clean:a});const h=this.workspaceAdapter.getWorkspaceAppService(),{workspace:u,project:g}=await h.loadWorkspaceAndProject(r,t);log89.info(`Building project: ${g.getName()}`),await g.loadConfig();const d=g.getPath(),p=s||u.getModulesDir(),m=i?path40.resolve(d,i):await g.getPublishDir();a&&(await this.cleanOutputDir(m),log89.info(`Cleaned output directory: ${m}`));const f=Date.now();let y=await g.getContentDirs();if(n&&n.length>0){const e=n.map(e=>path40.resolve(d,e));y=[...y,...e],log89.info(`Added extra content directories: ${n.join(", ")}`)}log89.info(`Content directories: ${y.length}`),log89.info(`Modules directory: ${p}`),log89.info(`Output directory: ${m}`),await this.syncFileLinkIfNeeded(g),o?(log89.info("🚀 Using parallel build mode"),await processSSGParallel(d,p)):await processSSG(d,p);const w=Date.now()-f;let S;if(l){const e=await h.createSnapshot(g,c);S=c?`${e.id} (${c})`:e.id,log89.info(`Snapshot created: ${S}`)}const b={timestamp:f,type:"build",success:!0,duration:w};g.addBuildHistory(b),await h.saveProject(g);const _=await h.setupProjectBaseURLStructure(g);log89.debug("baseURL structure setup complete",_),log89.info(`Build completed in ${w}ms`);let k=`Built site in ${(w/1e3).toFixed(1)}s\n`;return k+=`Project: ${g.getName()}\n`,k+=`Output: ${m}`,o&&(k+="\nUsed parallel processing"),a&&(k+="\nCleaned output directory"),S&&(k+=`\nSnapshot: ${S}`),{success:!0,message:k,data:{projectName:g.getName(),duration:w,outputDir:m,contentDirs:y,...S?{snapshot:S}:{}}}}catch(e){return log89.error("Build failed",e),{success:!1,message:"Build failed",error:e.message}}}async syncFileLinkIfNeeded(e){const t=e.getFileLink();if(t&&!t.isSymlink)try{log89.info("Syncing source file for copyFile-mode project",{source:t.sourcePath,target:t.targetPath});const e=this.workspaceAdapter.getFileSystemRepository();if(!await e.exists(t.sourcePath))return void log89.warn("Source file not found, skipping sync",{source:t.sourcePath});await e.copyFile(t.sourcePath,t.targetPath),log89.info("Source file synced successfully",{source:t.sourcePath,target:t.targetPath})}catch(e){log89.error("Failed to sync source file",e),log89.warn("Build will continue with existing file")}}async cleanOutputDir(e){try{await fs13.access(e);const t=await fs13.readdir(e);await Promise.all(t.map(t=>fs13.rm(path40.join(e,t),{recursive:!0,force:!0})))}catch(e){if("ENOENT"!==e.code)throw e}}};init_log();var log90=getDomainLogger("obsidian-serve",{component:"interface"}),ObsidianServeService=class{constructor(e,t){this.workspaceAdapter=e,this.publishAppService=t}publishAppService;coordinator;publishTimer;hasAutoPublish=!1;calculateOverallProgress(e,t){if(!this.hasAutoPublish)return t;switch(e){case"initializing":case"building":return.5*t;case"build-success":return 50;case"publishing":return 50+.5*t;case"publish-success":case"watching":return 100;default:return t}}createProgressCallback(e,t,r,i){const s={phase:e,percentage:t,overallPercentage:this.calculateOverallProgress(e,t),message:r};return i?.currentFile&&(s.currentFile=i.currentFile),i?.data&&(s.data=i.data),s}async startServer(e,t){try{const{workspacePath:r,projectName:i}=e;this.hasAutoPublish=!!e.publishConfig,log90.info("Starting server from Obsidian",{projectName:i,hasAutoPublish:this.hasAutoPublish}),t?.(this.createProgressCallback("initializing",10,"Loading project..."));const s=this.workspaceAdapter.getWorkspaceAppService(),{workspace:n,project:a}=await s.loadWorkspaceAndProject(i,r);log90.info(`Starting server for project: ${a.getName()}`);const o=e.port||8080,l=e.host||"localhost",c=e.livereloadPort||35729,h=!1!==e.livereload;t?.(this.createProgressCallback("initializing",30,"Preparing build configuration..."));const u=await s.ensureProjectBaseURLStructure(a);u.recreated&&log90.info("baseURL structure created/updated");const g=await a.getContentDirs(),d=a.getLinkDirs(),p=n.getModulesDir(),m=await a.getPublishDir(),f=a.getPath();let y=Date.now();const w={projDir:f,modulesDir:p,contentDirs:d,projContentDirs:g,publicDir:m,enableWatching:!0,batchDelay:300,progressCallback:e=>{if(t){const r={};e.currentFile&&(r.currentFile=e.currentFile),t(this.createProgressCallback("building",e.percentage,e.message,r))}},onSuccess:async()=>{const r=(Date.now()-y)/1e3;t?.(this.createProgressCallback("build-success",100,"Build completed successfully",{data:{buildTime:Number(r.toFixed(2)),filesProcessed:0}})),e.publishConfig&&this.publishAppService&&await this.autoPublish(a,e.publishConfig.method,e.publishConfig.config,e.publishConfig.delay,t),y=Date.now()}};if(h&&(w.liveReload={enabled:!0,port:o,host:l,livereloadPort:c}),e.markdown&&(w.markdown=e.markdown),await this.syncFileLinkIfNeeded(a),log90.info("Starting incremental build server..."),this.coordinator=await startIncrementalBuild(w),!this.coordinator.isInitialized())throw new Error("Failed to initialize build coordinator");const S=`http://${l}:${o}${u.baseURL}`;return log90.info(`Server running at ${S}`),{success:!0,message:`Server running at ${S}`,data:{url:S,port:o,host:l,baseURL:u.baseURL,serverRoot:u.serverRoot,...h?{livereloadPort:c}:{},...e.publishConfig?{autoPublish:e.publishConfig.method}:{}}}}catch(e){return log90.error("Failed to start server",e),t?.(this.createProgressCallback("error",0,`Failed to start server: ${e.message}`)),{success:!1,message:"Failed to start server",error:e.message}}}async stopServer(){try{return log90.info("Stopping server from Obsidian"),this.publishTimer&&(clearTimeout(this.publishTimer),this.publishTimer=void 0),this.coordinator&&(await this.coordinator.stopWatching(),this.coordinator=void 0),log90.info("Server stopped successfully"),!0}catch(e){return log90.error("Error stopping server",e),!1}}isRunning(){return this.coordinator?.isInitialized()||!1}async autoPublish(e,t,r,i,s){this.publishTimer&&clearTimeout(this.publishTimer);const n=i||2e3;this.publishTimer=setTimeout(async()=>{try{log90.info(`Auto-publishing to ${t}...`),s?.(this.createProgressCallback("publishing",0,`Publishing to ${t}...`));const i=Date.now(),n=await this.publishAppService.publish(e,r,{incremental:!0},e=>{if(s){const t={};e.currentFile&&(t.currentFile=e.currentFile),s(this.createProgressCallback("publishing",e.percentage,e.message,t))}}),a=(Date.now()-i)/1e3;if(n.success){const e=`Published to ${t.toUpperCase()} successfully`;log90.info(e,{url:n.url,filesUploaded:n.filesUploaded,bytesTransferred:n.bytesTransferred,duration:a}),s?.(this.createProgressCallback("publish-success",100,e,{data:{publishUrl:n.url,filesUploaded:n.filesUploaded,bytesTransferred:n.bytesTransferred,publishTime:Number(a.toFixed(2)),method:t}}))}else log90.error(`Publish to ${t} failed: ${n.error}`),s?.(this.createProgressCallback("error",0,`Publish failed: ${n.error}`))}catch(e){log90.error(`Publish to ${t} failed`,e),s?.(this.createProgressCallback("error",0,`Publish error: ${e.message}`))}},n)}async syncFileLinkIfNeeded(e){const t=e.getFileLink();if(t&&!t.isSymlink)try{log90.info("Syncing source file for copyFile-mode project",{source:t.sourcePath,target:t.targetPath});const e=this.workspaceAdapter.getFileSystemRepository();if(!await e.exists(t.sourcePath))return void log90.warn("Source file not found, skipping sync",{source:t.sourcePath});await e.copyFile(t.sourcePath,t.targetPath),log90.info("Source file synced successfully",{source:t.sourcePath,target:t.targetPath})}catch(e){log90.error("Failed to sync source file",e),log90.warn("Server will start with existing file")}}};init_log();var log91=getDomainLogger("obsidian-publish",{component:"interface"}),ObsidianPublishService=class{constructor(e,t){this.workspaceAdapter=t,this.publishAppService=e}publishAppService;async publish(e,t){const r=Date.now();try{const{workspacePath:i,projectName:s,method:n,config:a,force:o=!1}=e;log91.info("Publishing from Obsidian",{projectName:s,method:n});const l=this.workspaceAdapter.getWorkspaceAppService(),{workspace:c,project:h}=await l.loadWorkspaceAndProject(s,i);log91.info(`Publishing project: ${h.getName()} to ${n}`);const u=await this.publishAppService.publish(h,a,o?{force:!0}:{},t?e=>{const r={phase:e.phase,percentage:e.percentage,message:e.message};void 0!==e.currentFile&&(r.currentFile=e.currentFile),void 0!==e.filesCompleted&&(r.filesCompleted=e.filesCompleted),void 0!==e.filesTotal&&(r.filesTotal=e.filesTotal),void 0!==e.bytesTransferred&&(r.bytesTransferred=e.bytesTransferred),t(r)}:void 0),g=Date.now()-r;return u.success?{success:!0,message:`Published to ${n.toUpperCase()} successfully`,data:{url:u.url,filesUploaded:u.filesUploaded||0,bytesTransferred:u.bytesTransferred||0,duration:g}}:{success:!1,message:"Publish failed",error:u.error}}catch(e){return log91.error("Publish failed",e),{success:!1,message:"Publish failed",error:e.message}}}async testConnection(e,t,r){try{log91.info("Testing connection from Obsidian",{projectName:t,type:r.type});const i=this.workspaceAdapter.getWorkspaceAppService(),{workspace:s,project:n}=await i.loadWorkspaceAndProject(t,e),a=await this.publishAppService.testConnection(n,r);return{success:a.success,...a.error?{error:a.error}:{}}}catch(e){return log91.error("Test connection failed",e),{success:!1,error:e.message}}}},ObsidianDomainService=class{constructor(e,t){this.httpClient=e,this.identityAdapter=t}async getIdentityService(e){return await this.identityAdapter.getIdentityService(e,this.httpClient)}async getDomainInfo(e){try{const t=await this.getIdentityService(e),r=await t.getDomains();if(!r)return{success:!1,message:"No domain information found"};const i={subdomain:r.subdomain,fullDomain:r.full_domain,folder:r.folder,createdAt:"number"==typeof r.created_at?new Date(r.created_at).toISOString():r.created_at};return r.cus_domain&&(i.customDomain=r.cus_domain),{success:!0,message:"Domain information retrieved",data:i}}catch(e){const t=e.message;return t.includes("No workspace found")?{success:!1,message:"No workspace found. Please initialize workspace first.",error:t}:{success:!1,message:`Failed to get domain info: ${t}`,error:t}}}async checkSubdomain(e,t){try{const r=await this.getIdentityService(e),i=await r.checkSubdomainAvailability(t);if(!i)return{success:!1,message:"Failed to check subdomain availability"};const s={available:i.available};i.message&&(s.message=i.message);const n=i.available?`Subdomain "${t}" is available`:`Subdomain "${t}" is not available`;return{success:i.available,message:n,data:s}}catch(e){const t=e.message;return t.includes("No workspace found")?{success:!1,message:"No workspace found. Please initialize workspace first.",error:t}:{success:!1,message:`Failed to check subdomain: ${t}`,error:t}}}async updateSubdomain(e,t){try{const r=await this.getIdentityService(e),i=await r.updateSubdomain(t);return i?{success:!0,message:"Subdomain updated successfully",data:{oldSubdomain:i.old_subdomain,newSubdomain:i.new_subdomain,fullDomain:i.full_domain,message:i.message}}:{success:!1,message:"Failed to update subdomain"}}catch(e){const t=e.message;return t.includes("No workspace found")?{success:!1,message:"No workspace found. Please initialize workspace first.",error:t}:{success:!1,message:`Failed to update subdomain: ${t}`,error:t}}}async checkCustomDomain(e,t){try{const r=await this.getIdentityService(e),i=await r.checkCustomDomain(t);if(!i)return{success:!1,message:"Failed to check custom domain"};const s={ready:i.ready,dnsValid:i.dns_valid,message:i.message};return i.resolved_ips&&i.resolved_ips.length>0&&(s.resolvedIps=i.resolved_ips),{success:i.ready,message:i.ready?"Custom domain is ready":"Custom domain is not ready",data:s}}catch(e){const t=e.message;return t.includes("No workspace found")?{success:!1,message:"No workspace found. Please initialize workspace first.",error:t}:{success:!1,message:`Failed to check custom domain: ${t}`,error:t}}}async addCustomDomain(e,t){try{const r=await this.getIdentityService(e),i=await r.addCustomDomain(t);return i?{success:!0,message:"Custom domain added successfully",data:{domain:i.domain,status:i.status,message:i.message}}:{success:!1,message:"Failed to add custom domain"}}catch(e){const t=e.message;return t.includes("No workspace found")?{success:!1,message:"No workspace found. Please initialize workspace first.",error:t}:{success:!1,message:`Failed to add custom domain: ${t}`,error:t}}}async checkHttpsStatus(e,t){try{const r=await this.getIdentityService(e),i=await r.checkCustomDomainHttpsStatus(t);if(!i)return{success:!1,message:"Failed to check HTTPS status"};const s={tlsReady:i.tls_ready,dnsValid:i.dns_valid,status:i.status,message:i.message};if(i.certificate){const e={};i.certificate.issuer&&(e.issuer=i.certificate.issuer),i.certificate.valid_from&&(e.validFrom=i.certificate.valid_from),i.certificate.valid_to&&(e.validTo=i.certificate.valid_to),s.certificate=e}return{success:i.tls_ready,message:i.tls_ready?"HTTPS is ready":"HTTPS is not ready yet",data:s}}catch(e){const t=e.message;return t.includes("No workspace found")?{success:!1,message:"No workspace found. Please initialize workspace first.",error:t}:{success:!1,message:`Failed to check HTTPS status: ${t}`,error:t}}}};function createProgressEvent(e,t,r){return{type:e,message:t,progress:r?.progress,metadata:r?.metadata,timestamp:Date.now()}}function calculateProgress(e,t){return{current:e,total:t,percentage:t>0?Math.round(e/t*100):0}}init_wiki(),init_log();var log92=getDomainLogger("obsidian-wiki",{component:"interface"}),ObsidianWikiService=class{constructor(e){this.wikiAdapter=e}async ingest(e){try{const{workspacePath:t,projectName:r,filePath:i,temperature:s,onProgress:n}=e;log92.info("Starting wiki ingest",{workspacePath:t,projectName:r,filePath:i}),n?.(createProgressEvent("ingest:start",i?`Starting ingest for file: ${i}`:"Starting folder ingest"));const a=await this.wikiAdapter.createWikiService(t,r);let o;if(await a.loadKB(),i){n?.(createProgressEvent("ingest:file:start",`Processing file: ${i}`));const e={};void 0!==s&&(e.temperature=s),n&&(e.onIngestProgress=e=>{n(createProgressEvent("ingest:llm:token:usage",`Ingest LLM token usage (live) — completion: ~${e}`,{metadata:{tokenUsage:{promptTokens:0,completionTokens:e,totalTokens:e},isEstimate:!0}}))},e.onIngestTokenUsage=e=>{n(createProgressEvent("ingest:llm:token:usage",`Ingest LLM token usage — prompt: ${e.promptTokens}, completion: ${e.completionTokens}, total: ${e.totalTokens}`,{metadata:{tokenUsage:{promptTokens:e.promptTokens,completionTokens:e.completionTokens,totalTokens:e.totalTokens,model:e.model},isEstimate:!1}})),log92.info("Ingest LLM token usage (final)",e)},e.onEmbeddingUsage=e=>{n(createProgressEvent("ingest:embedding:token:usage",`Embedding token usage — prompt: ${e.promptTokens}, total: ${e.totalTokens}`,{metadata:{embeddingTokenUsage:{promptTokens:e.promptTokens,completionTokens:0,totalTokens:e.totalTokens,model:e.model}}}))}),n?.(createProgressEvent("ingest:file:reading","Reading file content"));const t=await a.ingestFile(i,e);n?.(createProgressEvent("ingest:file:complete",`File processed: ${t.extractedEntities} entities, ${t.extractedConcepts} concepts`)),o={success:t.success,sourcePath:t.sourcePath,extractedEntities:t.extractedEntities,extractedConcepts:t.extractedConcepts,extractedConnections:t.extractedConnections,timeMs:t.timeMs,pagesGenerated:0,...t.error&&{error:t.error}}}else{const e=n?e=>{n(createProgressEvent("ingest:llm:token:usage",`Ingest LLM token usage (live) — completion: ~${e}`,{metadata:{tokenUsage:{promptTokens:0,completionTokens:e,totalTokens:e},isEstimate:!0}}))}:void 0,t=n?e=>{n(createProgressEvent("ingest:llm:token:usage",`Ingest LLM token usage — prompt: ${e.promptTokens}, completion: ${e.completionTokens}, total: ${e.totalTokens}`,{metadata:{tokenUsage:{promptTokens:e.promptTokens,completionTokens:e.completionTokens,totalTokens:e.totalTokens,model:e.model},isEstimate:!1}}))}:void 0,r=n?e=>{n(createProgressEvent("ingest:embedding:token:usage",`Embedding token usage — prompt: ${e.promptTokens}, total: ${e.totalTokens}`,{metadata:{embeddingTokenUsage:{promptTokens:e.promptTokens,completionTokens:0,totalTokens:e.totalTokens,model:e.model}}}))}:void 0;o=await this.ingestFolder(a,s,n,r,t,e)}if(o.success){log92.info("Auto-generating wiki pages after ingest"),n?.(createProgressEvent("ingest:pages:generating","Generating wiki pages"));try{await a.generateAllPages();const e=a.kb,t=e?._entities?e._entities.size:0,r=e?._concepts?e._concepts.size:0;o.pagesGenerated=t+r,n?.(createProgressEvent("ingest:pages:complete",`Generated ${o.pagesGenerated} pages`)),log92.info("Wiki pages auto-generated",{pagesGenerated:o.pagesGenerated})}catch(e){log92.error("Failed to auto-generate pages",e),o.pagesGenerated=0}}return await a.saveKB(),n?.(createProgressEvent("ingest:complete","Ingest completed successfully")),log92.info("Wiki ingest completed",{result:o}),{success:!0,message:"Ingest completed",data:o}}catch(e){return log92.error("Failed to ingest",e),{success:!1,error:e.message}}}async*queryStream(e){const{workspacePath:t,projectName:r,question:i,temperature:s,maxResults:n,onProgress:a}=e;log92.info("Starting wiki query stream",{workspacePath:t,projectName:r,question:i}),a?.(createProgressEvent("query:start",`Starting query: ${i}`));const o=await this.wikiAdapter.createWikiService(t,r);await o.loadKB();const l=o.kb;l?.hasEmbeddingIndex?.()&&a?.(createProgressEvent("query:embedding:searching","Searching knowledge base with embeddings"));const c={};void 0!==s&&(c.temperature=s),void 0!==n&&(c.maxResults=n),a&&(c.onTokenUsage=e=>{a(createProgressEvent("query:token:usage",`Token usage — prompt: ${e.promptTokens}, completion: ${e.completionTokens}, total: ${e.totalTokens}`,{metadata:{tokenUsage:{promptTokens:e.promptTokens,completionTokens:e.completionTokens,totalTokens:e.totalTokens,model:e.model},isEstimate:!1}})),log92.info("Token usage (final)",e)},c.onEmbeddingUsage=e=>{a(createProgressEvent("query:embedding:token:usage",`Embedding token usage — prompt: ${e.promptTokens}, total: ${e.totalTokens}`,{metadata:{embeddingTokenUsage:{promptTokens:e.promptTokens,completionTokens:0,totalTokens:e.totalTokens,model:e.model}}})),log92.info("Embedding token usage (query)",e)});let h=0,u=!1;const g=e=>Math.max(1,Math.ceil(e.length/3));for await(const e of o.queryStream(i,c))u||(u=!0,a?.(createProgressEvent("query:llm:generating","Generating answer"))),h+=g(e),a&&a(createProgressEvent("query:token:usage",`Token usage (live) — completion: ~${h}`,{metadata:{tokenUsage:{promptTokens:0,completionTokens:h,totalTokens:h},isEstimate:!0}})),yield e;a?.(createProgressEvent("query:complete","Query completed"))}async saveConversation(e){try{const{workspacePath:t,projectName:r,question:i,answer:s,title:n,topic:a,conversationHistory:o,filename:l,sources:c,autoIngest:h=!0}=e;log92.info("Saving conversation",{workspacePath:t,projectName:r});const u=await this.wikiAdapter.createWikiService(t,r);let g;if(await u.loadKB(),o&&o.length>0){const e=n||o.map((e,t)=>`Q${t+1}: ${e.question}`).join("\n\n"),t=o.map((e,t)=>`A${t+1}: ${e.answer}`).join("\n\n"),r={};c&&(r.sources=c),g=await u.saveConversation(e,t,r)}else{if(!i||!s)throw new Error("Either conversationHistory or (question, answer) must be provided");{const e={};c&&(e.sources=c),g=await u.saveConversation(i,s,e)}}const d=await this.wikiAdapter.getBasename(g);if(h){log92.info("Starting auto-ingest of conversation",{filePath:g});const e=await u.ingestFile(g);log92.info("Auto-ingest result",{success:e.success,entities:e.extractedEntities,concepts:e.extractedConcepts,connections:e.extractedConnections}),e.success&&(log92.info("Auto-generating pages after conversation ingest"),await u.generateAllPages()),await u.saveKB(),log92.info("KB saved after auto-ingest")}return{success:!0,message:"Conversation saved",data:{savedPath:g,filePath:g,filename:d}}}catch(e){return log92.error("Failed to save conversation",e),{success:!1,error:e.message}}}async generatePages(e){try{const{workspacePath:t,projectName:r}=e;log92.info("Starting wiki page generation",{workspacePath:t,projectName:r});const i=Date.now(),s=await this.wikiAdapter.createWikiService(t,r);await s.loadKB(),await s.generateAllPages();const n=Date.now()-i,a=s.config?.paths?.wikiDir||"",o=s.kb,l=(o?.entities?Object.keys(o.entities).length:0)+(o?.concepts?Object.keys(o.concepts).length:0);return log92.info("Wiki page generation completed",{pageCount:l,timeMs:n}),{success:!0,message:"Wiki pages generated",data:{success:!0,pageCount:l,outputDir:a,timeMs:n}}}catch(e){return log92.error("Failed to generate wiki pages",e),{success:!1,error:e.message}}}async ingestFolder(e,t,r,i,s,n){const a=e.config?.paths?.sourcePath||"",o=await this.wikiAdapter.listMarkdownFiles(a),l=(o.length,Date.now()),c={temperature:t};n&&(c.onIngestProgress=n),s&&(c.onIngestTokenUsage=s),i&&(c.onEmbeddingUsage=i);const h=await e.ingestFolderIncremental(o,c,async(e,t,i,s)=>{const n=await this.wikiAdapter.getBasename(i);r?.(s?createProgressEvent("ingest:file:start",`[new] Processing file ${e}/${t}: ${n}`,{progress:calculateProgress(e,t)}):createProgressEvent("ingest:file:skip",`[skip] Already ingested: ${n}`,{progress:calculateProgress(e,t)}))}),{newFiles:u,skippedFiles:g}=h;return u.length>0?r?.(createProgressEvent("ingest:file:complete",`Processed ${u.length} new file(s), skipped ${g.length} already-ingested file(s)`)):r?.(createProgressEvent("ingest:file:complete",`No new files found (${g.length} file(s) already up-to-date)`)),{success:!0,sourcePath:a,extractedEntities:h.extractedEntities,extractedConcepts:h.extractedConcepts,extractedConnections:h.extractedConnections,timeMs:Date.now()-l,pagesGenerated:0,newFilesCount:u.length,skippedFilesCount:g.length}}calculateCost(e){try{const{provider:t,model:r,inputTokens:i,outputTokens:s}=e,n=estimateCost(t,r,i,s);return n?(log92.info("Cost calculated",{provider:t,model:r,inputTokens:i,outputTokens:s,totalCost:n.totalCost}),{success:!0,data:n}):{success:!1,error:`No pricing data found for provider "${t}". Check MODEL_PRICING or use getPricingTable().`}}catch(e){return log92.error("Failed to calculate cost",e),{success:!1,error:e.message}}}getPricingTable(){return MODEL_PRICING}};function createObsidianWorkspaceAppService(){return createWorkspaceAppService()}async function createObsidianIdentityService(e,t){const r=createWorkspaceAppService(),i=await r.loadWorkspace(e),s=r.createIdentityStorage(i),n=new UserFactory({httpClient:t,storageProvider:s}),a=new IdentityAppService({userFactory:n});return await a.initialize(),a}async function getIdentityService(e,t){return await createObsidianIdentityService(e,t)}init_identity2(),init_identity3(),init_container(),init_container();var DesktopIdentityAdapter=class{async getIdentityService(e,t){return await createObsidianIdentityService(e,t)}};init_node_file_system();var DesktopWorkspaceAdapter=class{workspaceAppService;workspaceFactory;fileSystemRepo;getWorkspaceAppService(){return this.workspaceAppService||(this.workspaceAppService=createWorkspaceAppService()),this.workspaceAppService}getWorkspaceFactory(){return this.workspaceFactory||(this.workspaceFactory=createWorkspaceFactory()),this.workspaceFactory}getFileSystemRepository(){return this.fileSystemRepo||(this.fileSystemRepo=new NodeFileSystemRepository),this.fileSystemRepo}};init_wiki();var DEFAULT_WIKI_SERVICE_CONFIG={outputLanguage:"English",ingestTemperature:.1,queryTemperature:.7,maxQueryResults:10},WikiService=class{factory;kb=null;config;constructor(e,t){this.factory=e,this.config=t,this.config.wiki={...DEFAULT_WIKI_SERVICE_CONFIG,...t.wiki}}get llmProvider(){return this.config.llm.provider}get embeddingProvider(){return this.config.embedding?.provider}get fileSystem(){return this.config.infrastructure.fileSystem}get pathService(){return this.config.infrastructure.pathService}get cryptoService(){return this.config.infrastructure.cryptoService}get conversationRepo(){return this.config.infrastructure.conversationRepo}async loadKB(){const e=await this.factory.load();if(e){if(this.kb=e,this.embeddingProvider&&!this.kb.hasEmbeddingIndex())try{await this.buildEmbeddingIndexForKB()}catch(e){console.warn("Failed to build embedding index on load",e)}return!0}return this.kb=this.factory.create(),!1}async saveKB(){if(!this.kb)throw new Error("No KB to save");if(this.kb.hasEmbeddingIndex())try{await this.kb.saveEmbeddingIndex(this.fileSystem,this.pathService)}catch(e){console.warn("Failed to save embedding index",e)}await this.factory.save(this.kb)}getStats(){if(!this.kb)throw new Error("KB not loaded");return this.kb.getStats()}getKnowledgeBase(){if(!this.kb)throw new Error("KB not loaded");return this.kb}async ingestFile(e,t){if(!this.kb)throw new Error("KB not loaded. Call loadKB() first.");try{const r=await this.fileSystem.readFile(e,"utf-8"),i=this.config.llm.defaultModel,s=t?.temperature??this.config.wiki.ingestTemperature,n=this.config.llm.defaultMaxTokens??32768,a=this.config.wiki.outputLanguage,o={llmProvider:this.llmProvider,model:i,temperature:s,maxTokens:n,outputLanguage:a,fileSystem:this.fileSystem,crypto:this.cryptoService,...t?.onIngestTokenUsage?{onIngestTokenUsage:t.onIngestTokenUsage}:{},...t?.onIngestProgress?{onIngestProgress:t.onIngestProgress}:{}},l=await this.kb.ingestFromSource(e,r,o);if(l.success&&this.embeddingProvider)try{await this.buildEmbeddingIndexForKB(t?.onEmbeddingUsage)}catch(e){console.warn("Failed to update embedding index after ingest",e)}return{...l,sourcePath:e}}catch(t){return console.error("❌ Ingest failed:",t.message),{success:!1,sourcePath:e,extractedEntities:0,extractedConcepts:0,extractedConnections:0,timeMs:0,error:t.message||"Unknown error"}}}async ingestFolderIncremental(e,t,r){if(!this.kb)throw new Error("KB not loaded. Call loadKB() first.");const i=[],s=[];let n=0,a=0,o=0;const l=Date.now();for(let l=0;l<e.length;l++){const c=e[l],h=this.kb.isNewSource(c);if(await(r?.(l+1,e.length,c,h)),!h){s.push(c);continue}i.push(c);const u=await this.ingestFile(c,t);u.success&&(n+=u.extractedEntities,a+=u.extractedConcepts,o+=u.extractedConnections)}return{newFiles:i,skippedFiles:s,extractedEntities:n,extractedConcepts:a,extractedConnections:o,timeMs:Date.now()-l}}async query(e,t){if(!this.kb)throw new Error("KB not loaded. Call loadKB() first.");const r={llmProvider:this.llmProvider,model:this.config.llm.defaultModel,temperature:t?.temperature??this.config.wiki.queryTemperature,maxResults:t?.maxResults??this.config.wiki.maxQueryResults};return this.embeddingProvider&&(r.embeddingProvider=this.embeddingProvider,r.embeddingModel=this.config.embedding?.defaultModel),await this.kb.query(e,r)}async*queryStream(e,t){if(!this.kb)throw new Error("KB not loaded. Call loadKB() first.");const r={llmProvider:this.llmProvider,model:this.config.llm.defaultModel,temperature:t?.temperature??this.config.wiki.queryTemperature,maxResults:t?.maxResults??this.config.wiki.maxQueryResults};this.embeddingProvider&&(r.embeddingProvider=this.embeddingProvider,r.embeddingModel=this.config.embedding?.defaultModel),t?.onTokenUsage&&(r.onTokenUsage=t.onTokenUsage),t?.onEmbeddingUsage&&(r.onEmbeddingUsage=t.onEmbeddingUsage),yield*this.kb.queryStream(e,r)}async generateAllPages(){if(!this.kb)throw new Error("KB not loaded. Call loadKB() first.");const e={wikiPageRepo:this.factory.getWikiPageRepository(),pathService:this.pathService,fileSystem:this.fileSystem};void 0!==this.config.paths.sourcePath&&(e.sourcePath=this.config.paths.sourcePath),await this.kb.generateWikiPages(e)}async lint(){if(!this.kb)throw new Error("KB not loaded. Call loadKB() first.");return this.kb.lint()}calculateCost(e,t,r,i){return estimateCost(e,t,r,i)}getPricingTable(){return MODEL_PRICING}findModelPricing(e,t){return findPricing(e,t)}async buildEmbeddingIndexForKB(e){if(!this.kb)return void console.warn("[wiki-service] buildEmbeddingIndexForKB: KB is null, skipping");if(!this.embeddingProvider)return void console.warn("[wiki-service] buildEmbeddingIndexForKB: embeddingProvider is null/undefined, skipping");const t=this.config.paths.embeddingsPath;await this.kb.buildEmbeddingIndex({embeddingProvider:this.embeddingProvider,model:this.config.embedding.defaultModel,cachePath:t,fileSystem:this.fileSystem,...e?{onEmbeddingUsage:e}:{}})}async buildEmbeddingIndex(){await this.buildEmbeddingIndexForKB()}async saveConversation(e,t,r){const i=Conversation.create(e,t,{sources:r?.sources||[],retrieval:r?.retrieval||{entityCount:0,conceptCount:0,totalResults:0}});return await this.conversationRepo.save(i)}async listConversations(){return(await this.conversationRepo.list()).map(e=>e.getMetadata())}};init_wiki(),init_wiki_config(),init_node(),init_ollama_embedding_provider(),init_ollama_provider(),init_provider2(),init_fetch_http_client();var OpenAICompatibleProvider=class{name;baseURL;apiKey;defaultModel;customHeaders;httpClient;constructor(e){this.baseURL=e.baseURL.replace(/\/$/,""),this.name=e.providerName||"OpenAI-Compatible",e.apiKey&&(this.apiKey=e.apiKey),e.defaultModel&&(this.defaultModel=e.defaultModel),this.customHeaders=e.customHeaders||{},this.httpClient=e.httpClient||createDefaultLLMHttpClient()}async*complete(e,t,r){const i=`${this.baseURL}/chat/completions`,s=[];t.systemMessage&&s.push({role:"system",content:t.systemMessage}),s.push({role:"user",content:e});const n={model:t.model||this.defaultModel||"gpt-3.5-turbo",messages:s,stream:!0,temperature:t.temperature??.7,max_tokens:t.maxTokens??4096,stream_options:{include_usage:!0}},a={"Content-Type":"application/json",...this.customHeaders};let o;(this.apiKey||t.apiKey)&&(a.Authorization=`Bearer ${t.apiKey||this.apiKey}`);try{const e={url:i,method:"POST",headers:a,body:JSON.stringify(n)};r&&(e.signal=r),o=await this.httpClient.fetch(e)}catch(e){if("AbortError"===e.name)throw new LLMAbortError(this.name);throw new LLMConnectError(this.name,e)}if(!o.ok){const e=await o.text().catch(()=>"Unknown error");throw new LLMHttpError(this.name,o.status,`${o.statusText}: ${e}`)}if(!o.body)throw new LLMConnectError(this.name,new Error("No response body"));const l=o.body.getReader(),c=new TextDecoder;try{let e,r="",i=!1;for(;;){const{done:s,value:n}=await l.read();if(s)break;r+=c.decode(n,{stream:!0});const a=r.split("\n");r=a.pop()||"";for(const r of a){const s=r.trim();if(s&&"data: [DONE]"!==s&&s.startsWith("data: ")){const r=s.slice(6);try{const s=JSON.parse(r),n=s.choices?.[0]?.delta?.content||"",a=s.choices?.[0]?.finish_reason;if(s.usage){const r=s.model||t.model||this.defaultModel;e={promptTokens:s.usage.prompt_tokens,completionTokens:s.usage.completion_tokens,totalTokens:s.usage.total_tokens,...r?{model:r}:{}}}n&&(yield{text:n,done:!1}),a&&(i=!0)}catch(e){console.warn("Failed to parse chunk:",r)}}}}yield{text:"",done:!0,...e?{usage:e}:{}}}finally{l.releaseLock()}}async completeSync(e,t,r,i){let s="";for await(const n of this.complete(e,t,r))n.done?n.usage&&i&&i(n.usage):s+=n.text;return s.trim()}async healthCheck(){try{const e=`${this.baseURL}/models`,t={};return this.apiKey&&(t.Authorization=`Bearer ${this.apiKey}`),(await this.httpClient.fetch({url:e,method:"GET",headers:t})).ok}catch{return!1}}};init_lmstudio_provider(),init_log();var log93=getDomainLogger("desktop-wiki-adapter",{component:"interface"}),DesktopWikiAdapter=class{constructor(e,t){this.workspaceAdapter=e,this.httpClient=t}fileSystem=new NodeFileSystem;pathService=new NodePathService;cryptoService=new NodeCryptoService;async createWikiService(e,t){log93.info("Creating WikiService",{workspacePath:e,projectName:t});const r=this.workspaceAdapter.getWorkspaceAppService(),{workspace:i,project:s}=await r.loadWorkspaceAndProject(t,e),n=await i.getConfig("llm")||{},a=await i.getConfig("wiki.outputLanguage")||"en";await s.loadConfig();const o=s.getConfigValue("outputDir"),l=s.getPath();if(!o)throw new Error(`Project ${t} does not have 'outputDir' configured`);const c=createWikiConfig(o),h=s.getFilePath(c.kbPath),u=s.getFilePath(c.embeddingsPath),g=function(e,t){switch(e.type){case"lmstudio":return function(e="http://localhost:1234/v1",t,r){const i={baseURL:e,providerName:"LM Studio"};return t&&(i.defaultModel=t),r&&(i.httpClient=r),new OpenAICompatibleProvider(i)}(e.baseURL,e.defaultModel,t);case"ollama":return new OllamaProvider(e.baseURL);case"openai":if(!e.apiKey)throw new Error("OpenAI requires an API key");return function(e,t,r){const i={baseURL:"https://api.openai.com/v1",apiKey:e,providerName:"OpenAI",defaultModel:t||"gpt-4-turbo-preview"};return r&&(i.httpClient=r),new OpenAICompatibleProvider(i)}(e.apiKey,e.defaultModel,t);case"glm":if(!e.apiKey)throw new Error("GLM requires an API key");return function(e,t,r){const i={baseURL:"https://open.bigmodel.cn/api/paas/v4",apiKey:e,providerName:"GLM (智谱AI)",defaultModel:t||"glm-4"};return r&&(i.httpClient=r),new OpenAICompatibleProvider(i)}(e.apiKey,e.defaultModel,t);case"deepseek":if(!e.apiKey)throw new Error("DeepSeek requires an API key");return function(e,t,r){const i={baseURL:"https://api.deepseek.com/v1",apiKey:e,providerName:"DeepSeek",defaultModel:t||"deepseek-chat"};return r&&(i.httpClient=r),new OpenAICompatibleProvider(i)}(e.apiKey,e.defaultModel,t);case"moonshot":if(!e.apiKey)throw new Error("Moonshot requires an API key");return function(e,t,r){const i={baseURL:"https://api.moonshot.cn/v1",apiKey:e,providerName:"Moonshot (Kimi)",defaultModel:t||"moonshot-v1-8k"};return r&&(i.httpClient=r),new OpenAICompatibleProvider(i)}(e.apiKey,e.defaultModel,t);case"custom":{const r={baseURL:e.baseURL,providerName:"Custom",...e.apiKey&&{apiKey:e.apiKey},...e.defaultModel&&{defaultModel:e.defaultModel},...e.customHeaders&&{customHeaders:e.customHeaders},...t&&{httpClient:t}};return new OpenAICompatibleProvider(r)}default:throw new Error(`Unknown LLM service type: ${e.type}`)}}(n,this.httpClient);let d;if(n.embeddingModel){const e=n.embeddingType||n.type||"lmstudio",t=n.embeddingBaseUrl||n.embeddingBaseURL||n.baseUrl||n.baseURL,r=n.embeddingApiKey||n.apiKey;d=function(e,t){if(!e||"none"===e.type)return null;switch(e.type){case"lmstudio":return new OpenAICompatibleEmbeddingProvider(e.baseURL||"http://localhost:1234/v1",e.model||"text-embedding-nomic-embed-text-v2-moe",t,e.apiKey,"LMStudio");case"ollama":return new OllamaEmbeddingProvider({baseUrl:e.baseURL||"http://localhost:11434",model:e.model||"nomic-embed-text"});case"openai":if(!e.apiKey)throw new Error("OpenAI embedding requires an API key");return new OpenAICompatibleEmbeddingProvider(e.baseURL||"https://api.openai.com/v1",e.model||"text-embedding-3-small",t,e.apiKey,"OpenAI");case"glm":if(!e.apiKey)throw new Error("GLM embedding requires an API key");return new OpenAICompatibleEmbeddingProvider(e.baseURL||"https://open.bigmodel.cn/api/paas/v4",e.model||"embedding-3",t,e.apiKey,"GLM");case"deepseek":if(!e.apiKey)throw new Error("DeepSeek embedding requires an API key");return new OpenAICompatibleEmbeddingProvider(e.baseURL||"https://api.deepseek.com/v1",e.model||"deepseek-embedding",t,e.apiKey,"DeepSeek");case"moonshot":if(!e.apiKey)throw new Error("Moonshot embedding requires an API key");return new OpenAICompatibleEmbeddingProvider(e.baseURL||"https://api.moonshot.cn/v1",e.model||"moonshot-v1-embedding",t,e.apiKey,"Moonshot");case"custom":return new OpenAICompatibleEmbeddingProvider(e.baseURL||"",e.model||"",t,e.apiKey,"Custom");default:throw new Error(`Unknown embedding service type: ${e.type}`)}}({type:e,baseURL:t,model:n.embeddingModel,apiKey:r},this.httpClient),log93.info("Embedding provider created",{type:e,model:n.embeddingModel,baseURL:t})}else log93.info("Embedding provider not configured (no embeddingModel in llm config)");const p=new NodeKBRepository(h,this.fileSystem,this.pathService),m=new NodeWikiPageRepository(o,this.fileSystem,this.pathService),f=new NodeConversationRepository(c.conversationsDir,this.fileSystem,this.pathService),y=new WikiFactory({kbRepo:p,wikiPageRepo:m}),w={llm:{provider:g,defaultModel:n.model||g.defaultModel||"default",defaultMaxTokens:n.maxTokens||32768},wiki:{outputLanguage:a,ingestTemperature:.3,queryTemperature:.7,maxQueryResults:10},infrastructure:{fileSystem:this.fileSystem,pathService:this.pathService,cryptoService:this.cryptoService,conversationRepo:f},paths:{kbPath:h,embeddingsPath:u,wikiDir:o,conversationsDir:c.conversationsDir,sourcePath:l}};return d?(w.embedding={provider:d,defaultModel:n.embeddingModel,cacheEnabled:!0},log93.info("Embedding configured in WikiService",{model:n.embeddingModel,embeddingsPath:u})):console.warn(`[wiki-adapter] No embedding provider (llmConfig.embeddingModel=${n.embeddingModel})`),log93.info("WikiService created successfully",{kbPath:h,embeddingsPath:u,wikiDir:o,conversationsDir:c.conversationsDir}),new WikiService(y,w)}async listMarkdownFiles(e){const t=[],r=await this.fileSystem.readdir(e);for(const i of r){const r=this.pathService.join(e,i);if((await this.fileSystem.stat(r)).isDirectory()){const e=await this.listMarkdownFiles(r);t.push(...e)}else i.endsWith(".md")&&t.push(r)}return t}async getBasename(e){return this.pathService.basename(e)}};function createObsidianWorkspaceService(){const e=new DesktopWorkspaceAdapter;return new ObsidianWorkspaceService(e)}function createObsidianAuthService(e){const t=new DesktopIdentityAdapter;return new ObsidianAuthService(e,t)}function createObsidianLicenseService(e){const t=new DesktopIdentityAdapter;return new ObsidianLicenseService(e,t)}function createObsidianGlobalConfigService(){const e=new DesktopWorkspaceAdapter;return new ObsidianGlobalConfigService(e)}function createObsidianProjectConfigService(){const e=new DesktopWorkspaceAdapter;return new ObsidianProjectConfigService(e)}function createObsidianProjectService(){const e=new DesktopWorkspaceAdapter;return new ObsidianProjectService(e)}function createObsidianBuildService(){const e=new DesktopWorkspaceAdapter;return new ObsidianBuildService(e)}function createObsidianServeService(e){const t=new DesktopWorkspaceAdapter;let r;if(e){const i=new NodeManifestRepository,s=new PublisherFactory(i,e),n=t.getWorkspaceAppService();r=new PublishAppService(s,n)}return new ObsidianServeService(t,r)}function createObsidianPublishService(e){const t=new DesktopWorkspaceAdapter,r=new NodeManifestRepository,i=new PublisherFactory(r,e),s=t.getWorkspaceAppService(),n=new PublishAppService(i,s);return new ObsidianPublishService(n,t)}function createObsidianDomainService(e){const t=new DesktopIdentityAdapter;return new ObsidianDomainService(e,t)}function createObsidianWikiService(e){const t=new DesktopWorkspaceAdapter,r=new DesktopWikiAdapter(t,e);return new ObsidianWikiService(r)}init_publish2(),init_publish(),init_infrastructure(),init_wiki();export{AutoIDGenerator,FetchHttpClient,IdentityAppService,IncrementalBuildCoordinator,LogLevel,Logger,ObsidianBuildService,ObsidianDomainService,ObsidianProjectService,ObsidianPublishService,ObsidianServeService,Project,PublishAppService,Workspace,WorkspaceAppService,calculateProgress,createDefaultLLMHttpClient,createIdentityService,createObsidianAuthService,createObsidianBuildService,createObsidianDomainService,createObsidianGlobalConfigService,createObsidianIdentityService,createObsidianLicenseService,createObsidianProjectConfigService,createObsidianProjectService,createObsidianPublishService,createObsidianServeService,createObsidianWikiService,createObsidianWorkspaceAppService,createObsidianWorkspaceService,createProgressEvent,createPublishAppService,createWorkspaceAppService,createWorkspaceFactory,generateStaticSite,getComponentLogger,getDomainLogger,getIdentityService,initLogger,processSSG,processSSGParallel,processSSGWithProgress,setGlobalLogLevel,startIncrementalBuild};