UNPKG

@compass-aiden/helpers

Version:
3 lines (2 loc) 35.7 kB
function e(e,t,r=/v/gi){if("string"!=typeof e||"string"!=typeof t)throw new Error("版本号必须为字符串类型");if(!e.trim()||!t.trim())throw new Error("版本号不能为空");const n=e.replace(r,"").trim(),o=t.replace(r,"").trim(),s=/^[0-9]+(\.[0-9]+)*$/;if(!s.test(n))throw new Error(`无效的版本号格式: ${e}`);if(!s.test(o))throw new Error(`无效的版本号格式: ${t}`);const i=n.split("."),a=o.split("."),c=Math.max(i.length,a.length);for(let e=0;e<c;e+=1){const t=parseInt(i[e]||"0",10),r=parseInt(a[e]||"0",10);if(t>r)return 1;if(t<r)return-1}return 0}const t={"zh-CN":["日","一","二","三","四","五","六"],"en-US":["Sun","Mon","Tue","Wed","Thu","Fri","Sat"]};function r(e){!function(e){if(null==e)throw new Error("日期参数不能为空");if("string"==typeof e&&""===e.trim())throw new Error("日期字符串不能为空");if("number"==typeof e&&(!isFinite(e)||isNaN(e)))throw new Error("时间戳必须为有效数字")}(e);const t=e instanceof Date?e:new Date(e);if(isNaN(t.getTime()))throw new Error(`无效的日期格式: ${String(e)}`);return t}function n(e,t,r,n){return t?e.toString().padStart(n,r):e.toString()}function o(e,o="YYYY-MM-DD hh:mm:ss",s={}){const{isPadStart:i=!0,padSymbol:a="0",locale:c="zh-CN"}=s;try{let s;if(0===arguments.length)s=new Date;else{if(void 0===e)throw new Error("日期参数不能为空");s=e}const l=r(s),u=l.getFullYear(),h=l.getMonth()+1,f=l.getDate(),d=l.getHours(),m=l.getMinutes(),g=l.getSeconds(),p=l.getMilliseconds(),w=function(e){return Math.ceil(e/3)}(h),y=l.getDay(),b=function(e,r){return(t[r]||t["zh-CN"])[e]||e.toString()}(y,c),E=0===d?12:d>12?d-12:d,k={YYYY:n(u,i,a,4),MM:n(h,i,a,2),DD:n(f,i,a,2),hh:n(d,i,a,2),HH:n(E,i,a,2),mm:n(m,i,a,2),ss:n(g,i,a,2),SSS:n(p,i,a,3),Q:w.toString(),d:y.toString(),W:b},v=Object.keys(k).sort((e,t)=>t.length-e.length);let C=o;for(const e of v){const t=new RegExp(`\\b${e}\\b|(?<![A-Za-z])${e}(?![A-Za-z])`,"g");C=C.replace(t,k[e])}return C}catch(e){if(e instanceof Error)throw new Error(`时间格式化失败: ${e.message}`);throw new Error("时间格式化失败: 未知错误")}}function s(e){if("number"!=typeof e)throw new Error("列数值必须为数字类型");if(!Number.isInteger(e))throw new Error("列数值必须为整数");if(e<1)throw new Error("列数值必须大于0(Excel列从1开始)");let t=e,r="";for(;t>0;){t-=1;const e=t%26;t=Math.floor(t/26);r=String.fromCharCode(65+e)+r}return r}function i(e,t){if(null==e||"function"!=typeof e.then)throw new TypeError("第一个参数必须是一个有效的 Promise 对象");if(void 0!==t&&("object"!=typeof t||null===t))throw new TypeError("errorExt 参数必须是一个对象或 undefined");return e.then(e=>[null,e]).catch(e=>{let r;if(e instanceof Error?r=e:"string"==typeof e?r=new Error(e):e&&"object"==typeof e&&"message"in e?(r=new Error(String(e.message)),r.name="name"in e?String(e.name):"Error"):(r=new Error("未知错误"),r.name="UnknownError"),t){const e=new Error(r.message);return e.name=r.name,e.stack=r.stack,Object.keys(t).forEach(r=>{"name"!==r&&"message"!==r&&"stack"!==r&&(e[r]=t[r])}),[e,null]}return[r,null]})}function a(e){return null===e?"null":void 0===e?"undefined":String(e)}function c(e,t){const[r,n]=t,o=r.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),s=n.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),i=e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");return new RegExp(`${o}\\s*(${i})\\s*${s}`,"g")}function l(e,t,r={}){const{wrapper:n=["{{","}}"],strict:o=!1,defaultValue:s=""}=r;try{if(function(e,t){if("string"!=typeof e)throw new Error("模板字符串必须为字符串类型");if(!t||"object"!=typeof t||Array.isArray(t))throw new Error("参数对象必须为有效的对象类型")}(e,t),!Array.isArray(n)||2!==n.length)throw new Error("包裹符号必须为包含2个元素的数组");const i=Object.keys(t);if(0===i.length&&o){const[t,r]=n,o=t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),s=r.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");if(new RegExp(`${o}\\s*\\w+\\s*${s}`).test(e))throw new Error("严格模式下不允许存在未定义的变量")}const l=i.sort((e,t)=>t.length-e.length);let u=e;for(const e of l){const r=t[e],o=c(e,n),s=a(r);u=u.replace(o,s)}if(o||void 0!==r.defaultValue){const[e,t]=n,r=e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),i=t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),a=new RegExp(`${r}\\s*(\\w+)\\s*${i}`,"g");if(o){const e=u.match(a);if(e&&e.length>0){const t=e.map(e=>e.replace(a,"$1")).join(", ");throw new Error(`严格模式下存在未定义的变量: ${t}`)}}else u=u.replace(a,s)}return u}catch(e){if(e instanceof Error)throw new Error(`变量替换失败: ${e.message}`);throw new Error("变量替换失败: 未知错误")}}function u(e,t){let r;return r=null===e?"null":void 0===e?"undefined":String(e),t?encodeURIComponent(r):r}function h(e,t){const r=t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),n=e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");return new RegExp(`${r}${n}\\b`,"g")}function f(e,t,r={}){const{prefix:n=":",strict:o=!1,defaultValue:s="",encodeValue:i=!1}=r;try{if(function(e,t){if("string"!=typeof e)throw new Error("路径字符串必须为字符串类型");if(!t||"object"!=typeof t||Array.isArray(t))throw new Error("参数对象必须为有效的对象类型")}(e,t),"string"!=typeof n||0===n.length)throw new Error("前缀必须为非空字符串");const a=Object.keys(t);if(0===a.length&&o){const t=n.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");if(new RegExp(`${t}\\w+`).test(e))throw new Error("严格模式下不允许存在未定义的路径变量")}const c=a.sort((e,t)=>t.length-e.length);let l=e;for(const e of c){const r=t[e],o=h(e,n),s=u(r,i);l=l.replace(o,s)}if(o||void 0!==r.defaultValue){const e=n.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),t=new RegExp(`${e}(\\w+)\\b`,"g");if(o){const e=Array.from(l.matchAll(t));if(e.length>0){const t=e.map(e=>`${n}${e[1]}`).join(", ");throw new Error(`严格模式下存在未定义的路径变量: ${t}`)}}else l=l.replace(t,()=>i?encodeURIComponent(s):s)}return l}catch(e){if(e instanceof Error)throw new Error(`路径变量替换失败: ${e.message}`);throw new Error("路径变量替换失败: 未知错误")}}const d={DEBUG:0,LOG:1,INFO:2,SUCCESS:3,WARN:4,ERROR:5},m="",g="",p="",w="",y="",b="",E="",k="";function v(){return"undefined"!=typeof window&&"undefined"!=typeof document}function C(e){try{return globalThis[e]}catch{return}}function S(){if(v())return!0;const e=C("process");return!!e&&(!!e.env?.FORCE_COLOR||!e.env?.NO_COLOR&&!e.env?.NODE_DISABLE_COLORS&&(e.stdout?.isTTY&&!1!==e.stdout?.hasColors?.()))}function $(...e){return e.join("")}function T(){return{debug:{browser:"padding: 2px 6px; border-radius: 2px; background-color: #6b7280; color: #fff; font-weight: 600;",node:$(k,g)},log:{browser:"padding: 2px 6px; border-radius: 2px; background-color: #374151; color: #fff; font-weight: 600;",node:$(p)},info:{browser:"padding: 2px 6px; border-radius: 2px; background-color: #3b82f6; color: #fff; font-weight: 600;",node:$(E)},success:{browser:"padding: 2px 6px; border-radius: 2px; background-color: #10b981; color: #fff; font-weight: 600;",node:$(y)},warn:{browser:"padding: 2px 6px; border-radius: 2px; background-color: #f59e0b; color: #fff; font-weight: 600;",node:$(b)},error:{browser:"padding: 2px 6px; border-radius: 2px; background-color: #ef4444; color: #fff; font-weight: 600;",node:$(w)}}}function x(){return{subject:"",logLevel:"LOG",prefix:"",suffix:"",dateFormat:!1,isDatePadZero:!0,enableStyling:S(),showStackTrace:!1,styles:T(),afterPrint:()=>{}}}function O(e,t,r){const n=d[t.logLevel];if((d[e.toUpperCase()]??d.LOG)<n)return;const s=function(e){if(!e.dateFormat)return;const t="string"==typeof e.dateFormat?e.dateFormat:"YYYY-MM-DD hh:mm:ss";return o(new Date,t,{isPadStart:e.isDatePadZero})}(t),i=r[0],a="string"==typeof i?i:"",c="string"==typeof i?r.slice(1):r,l=function(e){const{level:t,message:r="",timestamp:n,subject:o,prefix:s,suffix:i}=e;return[s,n,o,t.toUpperCase(),i,r].filter(Boolean).join(" ")}({level:e,message:a,timestamp:s,subject:t.subject,prefix:t.prefix,suffix:t.suffix}),u=console["success"===e?"log":e];if(t.enableStyling){const r=t.styles[e];if(r)if(v()){u(`%c${l}`,r.browser,...c)}else{const e=function(e,t){return t?t+e+m:e}(l,r.node);u(e,...c)}else u(l,...c)}else u(l,...c);if(t.showStackTrace&&"error"===e){const e=function(){try{throw new Error}catch(e){const t=e.stack;if(!t)return;return t.split("\n").slice(4).join("\n")}}();e&&(console.groupCollapsed("Stack Trace"),console.log(e),console.groupEnd())}try{t.afterPrint(e,l,...c)}catch(e){console.warn("Logger afterPrint hook error:",e)}}class M{static staticConfig=x();config;static originalErrorLevel=d.ERROR;constructor(e={}){const t=T(),r=this.mergeStyles(t,e.styles||{});this.config={...x(),...e,styles:{...t,...r}}}mergeStyles(e,t){const r={...e};for(const[n,o]of Object.entries(t)){const t=n,s=e[t];"string"==typeof o?r[t]={browser:o,node:o}:o&&"object"==typeof o&&(r[t]={browser:o.browser||s.browser,node:o.node||s.node})}return r}static get currentConfig(){return{...this.staticConfig}}get currentConfig(){return{...this.config}}static updateConfig(e){const t=this.mergeStylesStatic(this.staticConfig.styles,e.styles||{});this.staticConfig={...this.staticConfig,...e,styles:{...this.staticConfig.styles,...t}}}static mergeStylesStatic(e,t){const r={...e};for(const[n,o]of Object.entries(t)){const t=n,s=e[t];"string"==typeof o?r[t]={browser:o,node:o}:o&&"object"==typeof o&&(r[t]={browser:o.browser||s.browser,node:o.node||s.node})}return r}updateConfig(e){const t=this.mergeStyles(this.config.styles,e.styles||{});this.config={...this.config,...e,styles:{...this.config.styles,...t}}}static resetConfig(){this.staticConfig=x()}resetConfig(){this.config=x()}static debug(...e){O("debug",this.staticConfig,e)}static log(...e){O("log",this.staticConfig,e)}static info(...e){O("info",this.staticConfig,e)}static success(...e){O("success",this.staticConfig,e)}static warn(...e){O("warn",this.staticConfig,e)}static error(...e){O("error",this.staticConfig,e)}debug(...e){O("debug",this.config,e)}log(...e){O("log",this.config,e)}info(...e){O("info",this.config,e)}success(...e){O("success",this.config,e)}warn(...e){O("warn",this.config,e)}error(...e){O("error",this.config,e)}static group(e){console.group&&console.group(e)}group(e){M.group(e)}static groupCollapsed(e){console.groupCollapsed&&console.groupCollapsed(e)}groupCollapsed(e){M.groupCollapsed(e)}static groupEnd(){console.groupEnd&&console.groupEnd()}groupEnd(){M.groupEnd()}static time(e){console.time&&console.time(e)}time(e){M.time(e)}static timeEnd(e){console.timeEnd&&console.timeEnd(e)}timeEnd(e){M.timeEnd(e)}static timeLog(e,...t){console.timeLog&&console.timeLog(e,...t)}timeLog(e,...t){M.timeLog(e,...t)}static assert(e,t,...r){console.assert&&console.assert(e,t,...r)}assert(e,t,...r){M.assert(e,t,...r)}static table(e,t){console.table&&console.table(e,t)}table(e,t){M.table(e,t)}static clear(){console.clear&&console.clear()}clear(){M.clear()}static count(e){console.count&&console.count(e)}count(e){M.count(e)}static countReset(e){console.countReset&&console.countReset(e)}countReset(e){M.countReset(e)}static getSupportedLevels(){return Object.keys(d)}static isLevelEnabled(e){const t=d[this.staticConfig.logLevel];return d[e]>=t}isLevelEnabled(e){const t=d[this.config.logLevel];return d[e]>=t}createChild(e={}){const t=this.mergeStyles(this.config.styles,e.styles||{});return new M({...this.config,...e,styles:{...this.config.styles,...t}})}static disable(){this.updateConfig({logLevel:"ERROR"}),Object.defineProperty(d,"ERROR",{value:Number.MAX_SAFE_INTEGER,writable:!0,configurable:!0})}static enable(){Object.defineProperty(d,"ERROR",{value:this.originalErrorLevel,writable:!0,configurable:!0}),this.updateConfig({logLevel:"DEBUG"})}static supportsColor(){return S()}supportsColor(){return S()}static getEnvironmentInfo(){if(v())return{isBrowser:!0,supportsColor:!0,platform:"browser"};const e=C("process");return{isBrowser:!1,supportsColor:S(),platform:"node",colorDepth:e?.stdout?.getColorDepth?.()||0}}getEnvironmentInfo(){return M.getEnvironmentInfo()}}function R(e,t={}){!function(e){if("string"!=typeof e)throw new Error("手机号码必须是字符串类型");if(!e||0===e.trim().length)throw new Error("手机号码不能为空");if(!/\d/.test(e))throw new Error("手机号码必须包含至少一个数字")}(e);const r={maskLength:4,startOffset:3,isInternational:!1,internationalSeparator:" ",maskChar:"*",...t};try{const t=function(e,t){if(!t.isInternational)return{countryCode:"",phoneNumber:e.trim(),separator:""};const r=e.split(t.internationalSeparator);if(r.length<2)throw new Error(`国际号码格式错误,缺少分隔符 "${t.internationalSeparator}"`);const[n,...o]=r,s=o.join(t.internationalSeparator);if(!s||0===s.trim().length)throw new Error("国际号码中缺少有效的手机号码部分");return{countryCode:n.trim(),phoneNumber:s.trim(),separator:t.internationalSeparator}}(e,r),n=function(e,t){const r=e.replace(/\s/g,""),n=r.length,o=Math.max(0,Math.min(t.startOffset,n-1)),s=n-o,i=Math.max(0,Math.min(t.maskLength,s));if(0===i||o>=n)return e;const a=r.slice(0,o),c=t.maskChar.repeat(i),l=r.slice(o+i);return a+c+l}(t.phoneNumber,r);return r.isInternational?`${t.countryCode}${t.separator}${n}`:n}catch(e){throw new Error(`手机号码掩码处理失败: ${e instanceof Error?e.message:"未知错误"}`)}}function D(e,t={}){!function(e){if("string"!=typeof e)throw new Error("输入必须是字符串类型");if(0===e.length)throw new Error("输入字符串不能为空")}(e);const r={maskLength:4,startOffset:3,maskChar:"*",preserveEdges:t.preserveEdges,...t};try{return function(e,t){const r=e.length;if(t.preserveEdges){const{start:n,end:o}=t.preserveEdges;if(n<0||o<0)throw new Error("preserveEdges的start和end值不能为负数");if(n+o>=r)return e;const s=r-n-o;return e.slice(0,n)+t.maskChar.repeat(s)+e.slice(-o)}const n=Math.max(0,Math.min(t.startOffset,r-1)),o=r-n,s=Math.max(0,Math.min(t.maskLength,o));if(0===s||n>=r)return e;const i=e.slice(0,n),a=t.maskChar.repeat(s),c=e.slice(n+s);return i+a+c}(e,r)}catch(e){throw new Error(`字符串掩码处理失败: ${e instanceof Error?e.message:"未知错误"}`)}}function A(e,t,r){const{childrenKey:n="children"}=r||{},o=Array.isArray(e)?e:[e];for(const e of o){if(t(e))return e;const o=e[n];if(Array.isArray(o)&&o.length>0){const e=A(o,t,r);if(e)return e}}}function L(e,t,r){const n=Array.isArray(e)?e:[e],{childrenKey:o}={childrenKey:"children",...r};n.forEach(e=>{t(e);const n=e[o];Array.isArray(n)&&n.length>0&&L(n,t,r)})}function j(e,t,r){const{childrenKey:n}={childrenKey:"children",...r},o=e=>{const o=t(e),s=e[n];return s&&Array.isArray(s)&&(o[n]=j(s,t,r)),o};return Array.isArray(e)?e.map(o):o(e)}function I(e){return Object.entries(e).map(([e,t])=>`${e}: ${t}`).join(";")}function P(e){return"string"==typeof e&&e.trim().length>0&&!/[<>"'&]/.test(e)}class U{options;systemTheme;styleSheet;styleElement;container;themeMap=new Map;eventListeners=new Map;mediaQuery;isDestroyed=!1;boundSystemThemeHandler;constructor(e={}){this.options=e,this.validateEnvironment(),this.container=this.initializeContainer(),this.styleElement=this.createStyleElement(),this.styleSheet=this.styleElement.sheet,this.mediaQuery=window.matchMedia("(prefers-color-scheme: light)"),this.systemTheme=this.mediaQuery.matches?"light":"dark",this.boundSystemThemeHandler=this.handleSystemThemeChange.bind(this),this.setupSystemThemeListener(),this.applyDefaultTheme()}get currentSystemTheme(){return this.systemTheme}validateEnvironment(){if("undefined"==typeof window||"undefined"==typeof document)throw new Error("ThemeManager requires a browser environment")}initializeContainer(){let e=null;if(void 0===this.options.root)e=document.documentElement||document.querySelector("html");else if("string"==typeof this.options.root){if(e=document.querySelector(this.options.root),!e)throw new Error(`Container element not found: ${this.options.root}`)}else this.options.root instanceof Element&&(e=this.options.root);if(!e)throw new Error("Invalid container element");return e}createStyleElement(){const e=document.createElement("style");return e.setAttribute("data-theme-manager","true"),e.textContent="/* Theme Manager Styles */",this.container.insertBefore(e,this.container.firstChild),e}handleSystemThemeChange(e){const t=e.matches?"light":"dark";this.systemTheme=t,this.applyDefaultTheme(),this.emit("systemThemeChange",t)}setupSystemThemeListener(){this.mediaQuery.addEventListener("change",this.boundSystemThemeHandler)}applyDefaultTheme(){if(this.options.disableFollowSystemTheme)return;const e=this.getCurrentTheme();if(!e||"default"===e){const e=this.getThemeData(this.systemTheme);e&&(this.unregister("default"),this.register("default",e),this.toggle("default"))}}rebuildRuleIndexes(){const e=Array.from(this.themeMap.entries());for(;this.styleSheet.cssRules.length>0;)this.styleSheet.deleteRule(0);e.forEach(([e,t])=>{const r={...this.options.baseVariables,...t.data},n=this.styleSheet.insertRule(`[data-theme="${e}"] {${I(r)}}`,this.styleSheet.cssRules.length);t.index=n})}emit(e,...t){const r=this.eventListeners.get(e);r&&r.forEach(r=>{try{r(...t)}catch(t){console.error(`Error in ${e} event listener:`,t)}})}checkDestroyed(){if(this.isDestroyed)throw new Error("ThemeManager has been destroyed")}register(e,t){if(this.checkDestroyed(),!P(e))throw new Error(`Invalid theme name: ${e}`);if(!function(e){return!(!e||"object"!=typeof e)&&Object.entries(e).every(([e,t])=>"string"==typeof e&&e.trim().length>0&&("string"==typeof t||"number"==typeof t))}(t))throw new Error(`Invalid theme data for theme: ${e}`);this.themeMap.has(e)&&this.unregister(e);const r={...this.options.baseVariables,...t};try{const n=this.styleSheet.insertRule(`[data-theme="${e}"] {${I(r)}}`,this.styleSheet.cssRules.length);this.themeMap.set(e,{index:n,data:t}),this.emit("themeRegister",e,t),this.getCurrentTheme()===e&&this.applyDefaultTheme()}catch(t){throw new Error(`Failed to register theme "${e}": ${t.message}`)}return this}registerBatch(e){return this.checkDestroyed(),Object.entries(e).forEach(([e,t])=>{this.register(e,t)}),this}unregister(e){this.checkDestroyed();const t=this.themeMap.get(e);if(!t)return this;try{this.styleSheet.deleteRule(t.index),this.themeMap.delete(e),this.rebuildRuleIndexes(),this.emit("themeUnregister",e),this.getCurrentTheme()===e&&this.toggle()}catch(t){console.error(`Failed to unregister theme "${e}":`,t)}return this}toggle(e){if(this.checkDestroyed(),e&&null!==e){if(!P(e))throw new Error(`Invalid theme name: ${e}`);if(!this.themeMap.has(e))throw new Error(`Theme "${e}" is not registered`);this.container.setAttribute("data-theme",e);const t=this.themeMap.get(e),r={...this.options.baseVariables,...t?.data};this.emit("themeChange",e,r)}else this.container.removeAttribute("data-theme"),this.emit("themeChange",null,null);return this}getCurrentTheme(){return this.checkDestroyed(),this.container.getAttribute("data-theme")}getThemeData(e){this.checkDestroyed();const t=e||this.getCurrentTheme();if(!t||!this.themeMap.has(t))return null;const r=this.themeMap.get(t);return r?{...this.options.baseVariables,...r.data}:null}getAllThemes(){this.checkDestroyed();const e=this.getCurrentTheme();return Array.from(this.themeMap.entries()).map(([t,r])=>({name:t,data:{...this.options.baseVariables,...r.data},isActive:t===e}))}hasTheme(e){return this.checkDestroyed(),this.themeMap.has(e)}getThemeNames(){return this.checkDestroyed(),Array.from(this.themeMap.keys())}cloneTheme(e,t,r={}){this.checkDestroyed();const n=this.themeMap.get(e)?.data;if(!n)throw new Error(`Source theme "${e}" not found`);const o={...n,...r};return this.register(t,o)}on(e,t){return this.checkDestroyed(),this.eventListeners.has(e)||this.eventListeners.set(e,new Set),this.eventListeners.get(e).add(t),this}off(e,t){this.checkDestroyed();const r=this.eventListeners.get(e);return r&&r.delete(t),this}clearListeners(e){return this.checkDestroyed(),e?this.eventListeners.delete(e):this.eventListeners.clear(),this}updateBaseVariables(e){return this.checkDestroyed(),this.options.baseVariables={...this.options.baseVariables,...e},this.rebuildRuleIndexes(),this}destroy(){if(!this.isDestroyed)try{this.mediaQuery.removeEventListener("change",this.boundSystemThemeHandler),this.themeMap.clear(),this.styleElement&&this.styleElement.parentNode&&this.styleElement.parentNode.removeChild(this.styleElement),this.container.removeAttribute("data-theme"),this.eventListeners.clear(),this.isDestroyed=!0}catch(e){console.error("Error during ThemeManager destruction:",e)}}getStatus(){return{isDestroyed:this.isDestroyed,registeredThemes:this.themeMap.size,currentTheme:this.isDestroyed?null:this.getCurrentTheme(),systemTheme:this.systemTheme,followSystemTheme:!this.options.disableFollowSystemTheme,eventListeners:Array.from(this.eventListeners.values()).reduce((e,t)=>e+t.size,0)}}}function B(e,t={}){const{timeout:r,transferable:n=!0}=t;let o=0;const s=new Map;let i=null,a=null;try{const t=`\n // 用户提供的函数\n const userFunction = ${e.toString()};\n\n // 消息处理器\n self.onmessage = async function(event) {\n const [id, args] = event.data;\n\n try {\n // 执行用户函数\n const result = await Promise.resolve(userFunction.apply(null, args));\n\n // 检测可传输对象\n const transferable = [];\n if (result instanceof ArrayBuffer) {\n transferable.push(result);\n } else if (result instanceof MessagePort) {\n transferable.push(result);\n } else if (typeof ImageBitmap !== 'undefined' && result instanceof ImageBitmap) {\n transferable.push(result);\n }\n\n // 发送成功结果\n self.postMessage([id, 'success', result], transferable);\n } catch (error) {\n // 发送错误结果\n self.postMessage([id, 'error', {\n message: error.message || String(error),\n name: error.name || 'Error',\n stack: error.stack\n }]);\n }\n };\n\n // 错误处理\n self.onerror = function(error) {\n console.error('Worker error:', error);\n };\n `,r=new Blob([t],{type:"application/javascript"});a=URL.createObjectURL(r),i=new Worker(a),i.onmessage=e=>{const[t,r,n]=e.data,o=s.get(t);if(o)if(o.timeout&&clearTimeout(o.timeout),s.delete(t),"success"===r)o.resolve(n);else{const e=new Error(n?.message||"Worker task failed");e.name=n?.name||"WorkerError",n?.stack&&(e.stack=n.stack),o.reject(e)}else console.warn(`Received message for unknown promise ID: ${t}`)},i.onerror=e=>{console.error("Worker error:",e),s.forEach(t=>{t.timeout&&clearTimeout(t.timeout),t.reject(new Error(`Worker error: ${e.message||"Unknown error"}`))}),s.clear()}}catch(e){throw new Error(`Failed to create worker: ${e.message}`)}const c=(...e)=>i?new Promise((t,a)=>{const c=++o;let l;r&&r>0&&(l=setTimeout(()=>{s.get(c)&&(s.delete(c),a(new Error(`Worker task timed out after ${r}ms`)))},r)),s.set(c,{resolve:e=>t(e),reject:a,timeout:l});try{const t=(e=>n?e.filter(e=>e instanceof ArrayBuffer||e instanceof MessagePort||"undefined"!=typeof ImageBitmap&&e instanceof ImageBitmap||"undefined"!=typeof OffscreenCanvas&&e instanceof OffscreenCanvas):[])(e);i.postMessage([c,e],t)}catch(e){l&&clearTimeout(l),s.delete(c),a(new Error(`Failed to send message to worker: ${e.message}`))}}):Promise.reject(new Error("Worker has been terminated"));return c.terminate=()=>{i&&(s.forEach(e=>{e.timeout&&clearTimeout(e.timeout),e.reject(new Error("Worker was terminated"))}),s.clear(),i.terminate(),i=null),a&&(URL.revokeObjectURL(a),a=null)},c.isActive=()=>null!==i,c}function F(e,t=4,r={}){const n=[];let o=0;for(let o=0;o<t;o++)n.push(B(e,r));const s=(...e)=>{const r=n[o];return o=(o+1)%t,r(...e)};return s.terminate=()=>{n.forEach(e=>e.terminate()),n.length=0},s.isActive=()=>n.some(e=>e.isActive()),s}function N(){return"undefined"!=typeof window&&"undefined"!=typeof document}function W(e){return e.length>0&&!/[\s\t\n\r\f;,=]/.test(e)}function _(e){try{return decodeURIComponent(e)}catch{return e}}function z(e){if(!N())return console.warn("getCookie: Not in browser environment"),null;if(!W(e))return console.warn(`getCookie: Invalid cookie name "${e}"`),null;try{const t=document.cookie.split(";");for(const r of t){const[t,...n]=r.trim().split("=");if(t===e){const e=n.join("=");return e?_(e):""}}return null}catch(e){return console.error("getCookie: Failed to parse cookies",e),null}}function H(e,t,r={}){if(!N())return console.warn("setCookie: Not in browser environment"),!1;if(!W(e))return console.warn(`setCookie: Invalid cookie name "${e}"`),!1;try{const{path:n="/",domain:o,expiresIn:s,expires:i,secure:a,httpOnly:c,sameSite:l}=r;let u=`${e}=${function(e){return encodeURIComponent(e)}(t)}`;if(n&&(u+=`; Path=${n}`),o&&(u+=`; Domain=${o}`),i)u+=`; Expires=${i.toUTCString()}`;else if(void 0!==s&&s>0){const e=new Date;e.setTime(e.getTime()+s),u+=`; Expires=${e.toUTCString()}`}return a&&(u+="; Secure"),c&&(u+="; HttpOnly"),l&&(u+=`; SameSite=${l}`),document.cookie=u,!0}catch(e){return console.error("setCookie: Failed to set cookie",e),!1}}function V(e,t={}){return H(e,"",{...t,expiresIn:-1})}function Y(){if(!N())return console.warn("getAllCookies: Not in browser environment"),{};try{const e={},t=document.cookie;return t?(t.split(";").forEach(t=>{const[r,...n]=t.trim().split("=");if(r){const t=n.join("=");e[r]=t?_(t):""}}),e):e}catch(e){return console.error("getAllCookies: Failed to parse cookies",e),{}}}function G(e){const t=[];if(!e?.trim())return t;try{e.split(";").forEach(e=>{const[r,...n]=e.trim().split("=");if(r){const e=n.join("=");t.push({name:r.trim(),value:e?_(e):""})}})}catch(e){console.error("parseCookies: Failed to parse cookie string",e)}return t}function K(){if(!N())return!1;try{const e="__cookie_test__",t="test";H(e,t);const r=z(e);return V(e),r===t}catch{return!1}}function Q(e={}){if(!N())return console.warn("clearAllCookies: Not in browser environment"),0;try{const t=Y();let r=0;for(const n of Object.keys(t))V(n,e)&&r++;return r}catch(e){return console.error("clearAllCookies: Failed to clear cookies",e),0}}class Z{defaultOptions;constructor(e={}){this.defaultOptions=e}get(e){return z(e)}set(e,t,r={}){return H(e,t,{...this.defaultOptions,...r})}delete(e,t={}){return V(e,{path:t.path||this.defaultOptions.path,domain:t.domain||this.defaultOptions.domain})}getAll(){return Y()}clearAll(){return Q({path:this.defaultOptions.path,domain:this.defaultOptions.domain})}updateDefaults(e){this.defaultOptions={...this.defaultOptions,...e}}}let q=null,J=null;function X(){if("undefined"==typeof window||"undefined"==typeof screen)return{width:0,height:0,pixelRatio:1,availableWidth:0,availableHeight:0,colorDepth:24,orientation:"unknown"};const{width:e,height:t,availWidth:r,availHeight:n,colorDepth:o}=screen,s=window.devicePixelRatio||1;let i="unknown";return void 0!==window.screen.orientation?i=window.screen.orientation.angle%180==0?"portrait":"landscape":e&&t&&(i=e>t?"landscape":"portrait"),{width:e,height:t,pixelRatio:s,availableWidth:r,availableHeight:n,colorDepth:o,orientation:i}}function ee(e={}){const{userAgent:t,enableCache:r=!0}=e;if("undefined"==typeof navigator||"string"!=typeof navigator.userAgent)return console.warn("`getDeviceInfo` is intended for browser environments. Returning a default desktop object."),{platform:"desktop",os:"desktop",device:"desktop",osVersion:"",userAgent:"",browser:{name:"unknown",version:"",engine:"unknown",isMobile:!1},screen:{width:0,height:0,pixelRatio:1,availableWidth:0,availableHeight:0,colorDepth:24,orientation:"unknown"},isMobile:!1,isTablet:!1,isDesktop:!0,isAndroid:!1,isHarmonyOS:!1,isIPhone:!1,isIPad:!1,isAndroidTablet:!1,isHarmonyOSTablet:!1,isIPadOS13Plus:!1,isMac:!1,isWindows:!1,isLinux:!1,isTouchDevice:!1,isPWA:!1};const n=t||navigator.userAgent;if(r&&q&&J===n)return q;const o=n.toLowerCase(),s=o.includes("android"),i=o.includes("harmonyos")||o.includes("hos"),a=o.includes("iphone"),c=o.includes("ipad")||o.includes("macintosh")&&navigator.maxTouchPoints>1,l=o.includes("macintosh")&&!c,u=o.includes("windows"),h=o.includes("linux")&&!s,f=c||(s||i)&&!o.includes("mobile"),d=a||(s||i)&&o.includes("mobile"),m=!d&&!f,g=s&&f,p=i&&f,w=s&&d,y=i&&d,b=c&&!o.includes("ipad"),E=i?"harmonyos":s?"android":a||c?"ios":l?"macos":u?"windows":h?"linux":"desktop",k=d?"mobile":f?"tablet":"desktop",v=a?"iphone":c?"ipad":p?"harmonyos_tablet":g?"android_tablet":y?"harmonyos_phone":w?"android_phone":"desktop",C=function(e,t){const r=e.toLowerCase();switch(t){case"android":{const e=r.match(/android\s([\d.]+)/);return e?e[1]:""}case"ios":{const e=r.match(/os\s([\d_]+)/);return e?e[1].replace(/_/g,"."):""}case"harmonyos":{const e=r.match(/harmonyos\s([\d.]+)/)||r.match(/hos\s([\d.]+)/);return e?e[1]:""}case"macos":{const e=r.match(/mac os x\s([\d_]+)/);return e?e[1].replace(/_/g,"."):""}case"windows":{const e=r.match(/windows nt\s([\d.]+)/);return e?e[1]:""}default:return""}}(n,E),S=function(e){const t=e.toLowerCase();let r="unknown",n="",o="unknown";if(t.includes("edg/")){r="edge";const e=t.match(/edg\/([\d.]+)/);n=e?e[1]:"",o="blink"}else if(t.includes("chrome/")&&!t.includes("edg/")){r="chrome";const e=t.match(/chrome\/([\d.]+)/);n=e?e[1]:"",o="blink"}else if(t.includes("firefox/")){r="firefox";const e=t.match(/firefox\/([\d.]+)/);n=e?e[1]:"",o="gecko"}else if(t.includes("safari/")&&!t.includes("chrome/")){r="safari";const e=t.match(/version\/([\d.]+)/);n=e?e[1]:"",o="webkit"}else if(t.includes("opera/")||t.includes("opr/")){r="opera";const e=t.match(/(opera|opr)\/([\d.]+)/);n=e?e[2]:"",o="blink"}else if(t.includes("msie")||t.includes("trident/")){r="ie";const e=t.match(/(msie\s|rv:)([\d.]+)/);n=e?e[2]:"",o="trident"}return{name:r,version:n,engine:o,isMobile:t.includes("mobile")||t.includes("android")}}(n),$=X(),T="undefined"!=typeof window&&!!("ontouchstart"in window||navigator.maxTouchPoints>0||navigator.msMaxTouchPoints>0),x="undefined"!=typeof window&&!!(window.matchMedia("(display-mode: standalone)").matches||window.navigator.standalone||document.referrer.includes("android-app://")),O={platform:k,os:E,device:v,osVersion:C,userAgent:n,browser:S,screen:$,isMobile:d,isTablet:f,isDesktop:m,isAndroid:s,isHarmonyOS:i,isIPhone:a,isIPad:c,isAndroidTablet:g,isHarmonyOSTablet:p,isIPadOS13Plus:b,isMac:l,isWindows:u,isLinux:h,isTouchDevice:T,isPWA:x};return r&&(q=O,J=n),O}function te(){q=null,J=null}function re(e,t){const r=ee(t);switch(e){case"mobile":return r.isMobile;case"tablet":return r.isTablet;case"desktop":return r.isDesktop;case"android":return r.isAndroid;case"ios":return r.isIPhone||r.isIPad;case"harmonyos":return r.isHarmonyOS;case"macos":return r.isMac;case"windows":return r.isWindows;case"linux":return r.isLinux;default:return!1}}function ne(){return"undefined"!=typeof window&&"undefined"!=typeof document&&!!(window.URL&&window.URL.createObjectURL&&document.createElement&&"download"in document.createElement("a"))}function oe(e){if(!e||"string"!=typeof e)return!1;if(/[<>:"/\\|?*\u0000-\u001f]/.test(e))return!1;if(e.length>255)return!1;return!/^(CON|PRN|AUX|NUL|COM[1-9]|LPT[1-9])(\.|$)/i.test(e)}function se(e,t="datetime"){const r=new Date,n=e.includes(".")?e.substring(e.lastIndexOf(".")):"",o=n?e.substring(0,e.lastIndexOf(".")):e;let s;switch(t){case"date":s=r.toISOString().split("T")[0];break;case"time":s=r.toTimeString().split(" ")[0].replace(/:/g,"-");break;case"unix":s=Math.floor(r.getTime()/1e3).toString();break;default:s=r.toISOString().replace(/[:.]/g,"-").split("T").join("_").slice(0,-1)}return`${o}_${s}${n}`}function ie(e,t){if(e instanceof Blob)return e;if(e instanceof File)return new Blob([e],t);if(e instanceof ArrayBuffer)return new Blob([e],t);if("string"==typeof e)return new Blob([e],{type:"text/plain;charset=utf-8",...t});if("object"==typeof e){const r=JSON.stringify(e,null,2);return new Blob([r],{type:"application/json;charset=utf-8",...t})}const r=String(e);return new Blob([r],{type:"text/plain;charset=utf-8",...t})}function ae(e){if(0===e)return"0 B";const t=Math.floor(Math.log(e)/Math.log(1024));return`${parseFloat((e/Math.pow(1024,t)).toFixed(2))} ${["B","KB","MB","GB","TB"][t]}`}async function ce(e,t){if(!ne()){const e=new Error("Current environment does not support file download");return t.onError?.(e),{success:!1,filename:t.filename,size:0,error:e}}if(!e){const e=new Error("Download data cannot be empty");return t.onError?.(e),{success:!1,filename:t.filename,size:0,error:e}}if(!oe(t.filename)){const e=new Error(`Invalid filename: ${t.filename}`);return t.onError?.(e),{success:!1,filename:t.filename,size:0,error:e}}let r=t.filename;if(t.addTimestamp&&(r=se(t.filename,t.timestampFormat)),t.showConfirm){const e=t.confirmMessage||`确定要下载文件 "${r}" 吗?`;if(!window.confirm(e)){return{success:!1,filename:r,size:0,error:new Error("Download cancelled by user")}}}try{const n=ie(e,t.blobOptions),o=await function(e,t){return new Promise((r,n)=>{try{const n=window.URL.createObjectURL(e),o=document.createElement("a");o.style.display="none",o.href=n,o.download=t,document.body.appendChild(o),o.click(),setTimeout(()=>{document.body.removeChild(o),window.URL.revokeObjectURL(n),r({success:!0,filename:t,size:e.size})},100)}catch(e){n(e instanceof Error?e:new Error("Unknown download error"))}})}(n,r);return t.onSuccess?.(),o}catch(e){const n=e instanceof Error?e:new Error("Unknown download error");return t.onError?.(n),{success:!1,filename:r,size:0,error:n}}}async function le(e,t,r="utf-8"){return ce(e,{filename:t,blobOptions:{type:`text/plain;charset=${r}`}})}async function ue(e,t,r=2){return ce(JSON.stringify(e,null,r),{filename:t.endsWith(".json")?t:`${t}.json`,blobOptions:{type:"application/json;charset=utf-8"}})}async function he(e,t,r=","){return ce(e.map(e=>e.map(e=>{const t=String(e);return t.includes(r)||t.includes("\n")||t.includes('"')?`"${t.replace(/"/g,'""')}"`:t}).join(r)).join("\n"),{filename:t.endsWith(".csv")?t:`${t}.csv`,blobOptions:{type:"text/csv;charset=utf-8"}})}async function fe(e,t){return ce(e,{filename:t||(e instanceof File?e.name:"download")})}async function de(e,t,r){let n=e,o=r;if(e.startsWith("data:")){const t=e.match(/^data:([^;]+);base64,(.+)$/);t&&(o=t[1],n=t[2])}o||(o="application/octet-stream");try{const e=window.atob(n),r=new Uint8Array(e.length);for(let t=0;t<e.length;t++)r[t]=e.charCodeAt(t);return ce(r.buffer,{filename:t,blobOptions:{type:o}})}catch(e){throw new Error(`Failed to decode Base64 data: ${e.message}`)}}async function me(e,t=500){const r=[];for(let n=0;n<e.length;n++){const{data:o,options:s}=e[n];try{const i=await ce(o,s);r.push(i),n<e.length-1&&t>0&&await new Promise(e=>setTimeout(e,t))}catch(e){r.push({success:!1,filename:s.filename,size:0,error:e instanceof Error?e:new Error("Unknown error")})}}return r}export{Z as CookieManager,M as Logger,U as ThemeManager,se as addTimestampToFilename,Q as clearAllCookies,te as clearDeviceInfoCache,e as compareVersion,ie as convertToBlob,F as createWorkerPool,B as createWorkerTask,V as deleteCookie,de as downloadBase64File,fe as downloadBlob,he as downloadCsvFile,ce as downloadFile,ue as downloadJsonFile,me as downloadMultipleFiles,le as downloadTextFile,A as findTree,L as forEachTree,o as formatDate,ae as formatFileSize,Y as getAllCookies,z as getCookie,ee as getDeviceInfo,ne as isBrowserSupported,K as isCookieSupported,re as isDeviceType,j as mapTree,R as maskPhoneNumber,D as maskString,s as numberToExcelColumn,G as parseCookies,i as promiseTask,l as replaceVariablesInString,f as replaceVarsInPath,H as setCookie,oe as validateFilename}; //# sourceMappingURL=browser.js.map