debug-web 1.0.1 → 2.1.0

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.

Potentially problematic release.


This version of debug-web might be problematic. Click here for more details.

package/README.zh.md CHANGED
@@ -1,11 +1,15 @@
1
1
  # Debug Web
2
- 轻量级浏览器调试库。
3
2
 
4
- **优点**:
5
- - 🚀 **无依赖** — 仅使用纯 TypeScript;
6
- - 📦 **大小约 3.0 kB** — 对打包体积影响极小;
7
- - 🎨 **控制台输出样式** — 彩色格式化,便于快速识别;
8
- - 💾 **全局存储**通过 `window` 访问调试数据。
3
+ 用于浏览器调试的 NPM 包,具有可自定义的日志级别(log、warn、error、debug)。\
4
+ 轻量且易于使用。
5
+
6
+ **特点**:
7
+ - 🚀 **无依赖** TypeScript 编写;
8
+ - 📦 **体积 ~3.4 kB** — 对打包体积影响极小;
9
+ - 🏅 **SonarQube `A` 评级** — 最高级别的代码质量和可靠性;
10
+ - 🎨 **控制台输出样式** — 彩色格式化,便于快速识别;
11
+ - 💾 **全局存储** — 通过 `window` 访问调试数据;
12
+ - 🔧 **灵活配置** — 支持日志级别、样式、别名及继承。
9
13
 
10
14
  ---
11
15
 
@@ -15,12 +19,16 @@
15
19
  - [日志级别](#日志级别-)
16
20
  - [选项](#选项-)
17
21
  - [默认样式](#默认样式-)
18
- - [使用方法](#使用方法-)
19
- - [样式自定义](#样式自定义-)
20
22
  - [API](#api-)
21
- - [扩展功能](#扩展功能)
23
+ - [createDebug](#createdebug-函数)
24
+ - [日志记录方法](#日志记录方法)
25
+ - [数据处理](#数据处理)
26
+ - [级别管理](#级别管理)
27
+ - [调试数据](#调试数据)
28
+ - [支持](#支持-)
29
+ - [许可证](#许可证)
22
30
 
23
- ## 其他语言版本
31
+ ## 翻译版本
24
32
 
25
33
  [English](README.md), [Español](README.es.md), [Deutsch](README.de.md), [中文](README.zh.md), [Русский](README.ru.md)
26
34
 
@@ -37,25 +45,28 @@ yarn add debug-web
37
45
 
38
46
  ## 日志级别 🔧
39
47
 
40
- 优先级(从低到高):
48
+ 优先级(从低到高):
41
49
 
42
50
  1. `debug` (0) — 调试信息 (`console.debug`);
43
- 2. `log` (1) — 基本消息 (`console.log`)
44
- 3. `info` (2) — 信息性消息 (`console.info`)
51
+ 2. `log` (1) — 基础消息 (`console.log`)
52
+ 3. `info` (2) — 提示信息 (`console.info`)
45
53
  4. `warn` (3) — 警告 (`console.warn`)
46
54
  5. `error` (4) — 错误 (`console.error`)
47
55
 
48
- ℹ️ 自定义级别: 任何字符串值(包括 `success`)都将被视为 `info` 级别。
56
+ ℹ️ 自定义级别:任何字符串值(例如 `success`、`focus`)都将作为 `info` 级别处理,并且可以拥有独立的样式。
49
57
 
50
58
  ## 选项 ⚙️
51
59
 
52
- | 参数 | 类型 | 默认值 | 描述 |
53
- |---------|---------------------------------|-------------------|-----------------------------------------|
54
- | `app` | `string` \| `null` | `'__web_debug__'` | 用于区分不同应用数据的唯一应用名称 |
55
- | `level` | `DebugLogLevel` | `'log'` | 最低日志级别(低于此级别的消息不会打印) |
56
- | `prop` | `string` \| `null` | `'info'` | 用于通过 `window[prop]` 访问数据的全局变量名 |
57
- | `data` | `Record<string, unknown>` | — | 初始化后立即保存的初始调试数据 |
58
- | `style` | `Record<DebugLogLevel, string>` | 参见 [下方](#默认样式-) | 为不同级别的消息自定义 CSS 样式 |
60
+ | 参数 | 类型 | 默认值 | 描述 |
61
+ |-----------|---------------------------------|----------------|-------------------------------------------------|
62
+ | `app` | `string` \| `null` | `'_debug_web'` | 唯一的应用程序名称,用于分离数据 |
63
+ | `level` | `DebugLogLevel` | `'log'` | 最低日志级别(低于此级别的消息将不会输出) |
64
+ | `prop` | `string` \| `null` | `'info'` | 用于访问数据的全局变量名(`null` 不创建) |
65
+ | `data` | `Record<string, unknown>` | — | 初始调试数据 |
66
+ | `local` | `boolean` | `false` | 将级别保存在 `localStorage` 中(否则保存在 `sessionStorage`) |
67
+ | `native` | `boolean` | `false` | 使用原生控制台方法(不带样式) |
68
+ | `aliases` | `Record<string, DebugLogLevel>` | '{}' | `createDebug` 的自定义别名 |
69
+ | `style` | `Record<DebugLogLevel, string>` | 见 [下方](#默认样式-) | 日志级别的 CSS 样式 |
59
70
 
60
71
  ```typescript
61
72
  type DebugLogLevel = 'debug' | 'log' | 'info' | 'success' | 'warn' | 'error' | string;
@@ -66,108 +77,118 @@ type DebugLogLevel = 'debug' | 'log' | 'info' | 'success' | 'warn' | 'error' | s
66
77
  | 级别 | 样式 (CSS) |
67
78
  |-----------|----------------------------------------------------------------------------|
68
79
  | `info` | `background-color: #155adc; color: #fff; padding: 2px; border-radius: 3px` |
80
+ | `mark` | `background-color: #695aff; color: #fff; padding: 2px; border-radius: 3px` |
69
81
  | `success` | `background-color: #13a10e; color: #fff; padding: 2px; border-radius: 3px` |
70
- | `warn` | `background-color: #ffa500; color: #fff; padding: 2px; border-radius: 3px` |
71
- | `error` | `background-color: #dc143c; color: #fff; padding: 2px; border-radius: 3px` |
72
-
73
- ## 使用方法 💡
82
+ | `focus` | `background-color: #881798; color: #fff; padding: 2px; border-radius: 3px` |
83
+ | `alert` | `background-color: #ffa500; color: #fff; padding: 2px; border-radius: 3px` |
84
+ | `danger` | `background-color: #dc143c; color: #fff; padding: 2px; border-radius: 3px` |
74
85
 
75
- ### 初始化
86
+ ## 如何使用 💡
76
87
 
77
- 在应用程序入口点(`main.js` / `app.js`)调用一次:
78
-
79
- ```javascript
80
- import { debugInit } from 'debug-web';
88
+ ### 创建实例
81
89
 
82
- debugInit({
83
- level: isDev ? 'debug' : 'error',
84
- data: { version: env.VERSION, buildTime: env.BUILD_TIMESTAMP }
90
+ ```typescript
91
+ // debug.ts
92
+ import { DebugWeb } from 'debug-web';
93
+
94
+ export const debug = new DebugWeb({
95
+ app: 'my-app',
96
+ level: process.env.NODE_ENV === 'development' ? 'log' : 'error',
97
+ data: { version: APP_VERSION },
98
+ aliases: { s: 'success', f: 'focus' },
99
+ local: true,
85
100
  });
86
101
  ```
87
102
 
88
- ### 日志记录
103
+ ### API 📚
89
104
 
90
- 在应用程序的任何位置使用以输出消息:
105
+ #### `createDebug` 函数
91
106
 
92
- ```javascript
93
- import { debug, log, info, success, warn, error } from 'debug-web';
94
-
95
- debug('调试消息');
96
- log('常规消息');
97
- info('信息性消息');
98
- success('成功!');
99
- warn('警告!');
100
- error(new Error());
101
- ```
107
+ 创建一个支持别名和自定义级别的代理。
102
108
 
103
- ### 调试数据
104
-
105
- 保存调试数据,可通过全局变量访问:
106
-
107
- ```javascript
108
- import { debugData } from 'debug-web';
109
-
110
- debugData({ lastError: null, prevRoute: '/home', bus: ['ui:modal-opened'] });
109
+ ```typescript
110
+ <T extends typeof DebugWeb>( options?: CreateDebugOptions, DebugClass?: T ) => CustomLogLevels & InstanceType<T>;
111
111
  ```
112
112
 
113
- 💡 提示: DevTools 中输入 `info`(或其他 `prop` 值)以获取所有保存的数据。
113
+ 默认别名: `d` `debug`, `l` `log`, `i` → `info`, `w` → `warn`, `e` → `error`
114
+
115
+ #### 日志记录方法
116
+
117
+ | 级别 | 类型 |
118
+ |--------------|------------------------------------------------------------------------|
119
+ | `debug` | `(message?: unknown, ...attrs: unknown[]) => void` |
120
+ | `log` | `(...attrs: unknown[]) => void` |
121
+ | `info` | `(...attrs: unknown[]) => void` |
122
+ | `warn` | `(...attrs: unknown[]) => void` |
123
+ | `error` | `(...attrs: unknown[]) => void` |
124
+ | `group` | `(open?: boolean, level?: DebugLogLevel, ...attrs: unknown[]) => void` |
125
+ | `groupEnd` | `(level?: DebugLogLevel) => void` |
126
+ | `dir` | `(value: unknown, options?: unknown) => void` |
127
+ | `dirxml` | `(...attrs: unknown[]) => void` |
128
+ | `trace` | `(...attrs: unknown[]) => void` |
129
+ | `table` | `(data: unknown, properties?: string[]) => void` |
130
+ | `count` | `(label?: string) => void` |
131
+ | `countReset` | `(label?: string) => void` |
132
+ | `time` | `(label?: string) => void` |
133
+ | `timeLog` | `(label?: string, ...attrs: unknown[]) => void` |
134
+ | `timeEnd` | `(label?: string) => void` |
135
+
136
+ #### 数据处理
137
+
138
+ | 方法 | 类型 | 注释 |
139
+ |--------|---------------------------------------------------|-------------------------------|
140
+ | `set` | `(data: DebugWebData) => void` | 保存调试数据(合并数据) |
141
+ | `get` | `(api?: boolean) => DebugWebData \| undefined` | 返回所有数据的副本。如果传入 `true`,则添加辅助方法 |
142
+ | `dump` | `(keys: string[], options?: DumpOptions) => void` | 以表格形式输出数据(忽略日志级别) |
114
143
 
115
- ## 样式自定义 🖌️
116
144
 
117
- ```javascript
118
- import { debugSetStyle } from 'debug-web';
119
-
120
- // 更改特定级别的样式
121
- debugSetStyle('info', 'color: purple; font-weight: bold;');
145
+ ```typescript
146
+ type DebugWebData = Record<string, unknown>
122
147
 
123
- // 或同时更改多个级别
124
- debugSetStyle({ info: 'color: #9b59b6;', success: 'color: #27ae60;' });
148
+ type DumpOptions = {
149
+ level?: DebugLogLevel;
150
+ title?: string | ((data: DebugWebData) => string);
151
+ open?: boolean;
152
+ }
125
153
  ```
126
154
 
127
- ## API 📚
128
-
129
- ### 日志方法
155
+ #### 级别管理
130
156
 
131
- 支持所有主要的 `console` 方法:
157
+ | 方法 | 类型 | 注释 |
158
+ |------------------|-----------------|----------|
159
+ | `level` (getter) | `DebugLogLevel` | 获取当前日志级别 |
160
+ | `level` (setter) | `DebugLogLevel` | 设置当前日志级别 |
132
161
 
133
- - `debug`, `log`, `info`, `warn`, `error`;
134
- - `group` (`groupCollapsed`), `groupEnd`;
135
- - `trace`, `count`, `countReset`;
136
- - `time`, `timeLog`, `timeEnd`;
137
- - `dir`, `dirxml`, `table`.
162
+ #### 样式设置
138
163
 
139
- ### 辅助方法
164
+ | 方法 | 类型 | 注释 |
165
+ |------------------|-----------------------------------|--------------|
166
+ | `style` (getter) | `() => DebugWebStyle` | 获取当前样式映射表 |
167
+ | `style` (setter) | `(styles: DebugWebStyle) => void` | 更新样式映射表(将合并) |
140
168
 
141
- - `debugData` — 添加调试数据(与现有数据合并);
142
- - `debugSetStyle` 更改日志级别的 CSS 样式;
143
- - `debugGetStyle` — 获取当前样式设置;
144
- - `debugReset`.
169
+ ```typescript
170
+ type DebugWebStyle = Record<DebugLogLevel, string | undefined>
171
+ ```
145
172
 
146
- ## 扩展功能
173
+ ### 调试数据
147
174
 
148
- 您可以创建自己的类以添加自定义日志方法:
175
+ 保存任意数据并在控制台中查看:
149
176
 
150
- ```ts
151
- export class CustomDebug extends WebDebug {
152
- static {
153
- // 为自定义级别添加新样式
154
- CustomDebug.setStyle({ ...WebDebug._style, 'customEvent': 'color: #00ff00' });
155
- }
177
+ ```javascript
178
+ debug.set({ error: null, user: { id: 1, name: 'John' } });
179
+ ```
156
180
 
157
- // 创建新的日志方法
158
- static customEvent(...attrs: unknown[]) {
159
- // 检查是否允许 'info' 级别(自定义级别等同于该级别)
160
- if (!CustomDebug.can('info')) return;
181
+ 可以通过 `window[prop]`(默认是 `info`)访问数据。
182
+ 在浏览器控制台中输入:
161
183
 
162
- // 使用内部方法进行格式化和输出
163
- CustomDebug.print('info', 'customEvent', attrs);
164
- }
165
- }
184
+ ```javascript
185
+ info // { error: null, user: {...}, setLevel: f }
186
+ info.setLevel() // 修改日志级别
166
187
  ```
167
188
 
168
- ## 支持
189
+ ## 支持 ❤️
169
190
 
170
- 如果您觉得这个库有用,请考虑支持其开发:
191
+ 如果这个库对您有帮助,请考虑支持它的开发。
171
192
 
172
193
  - [Patreon](https://www.patreon.com/collection/1924882)
173
194
  - [Boosty](https://boosty.to/karlen/donate)
package/dist/index.cjs CHANGED
@@ -1 +1 @@
1
- "use strict";const e=(e,t="#fff")=>`background-color: ${e}; color: ${t}; padding: 2px; border-radius: 3px;`,t={info:e("#155adc"),success:e("#13a10e"),warn:e("#ffa500"),error:e("#dc143c")},o=e=>void 0!==e,s=(e,t=!1)=>t?Symbol.for(e):e,r="__web_debug__",c="info";class n{static _level=0;static _app=r;static _prop=c;static _style=t;static _levelMap={debug:0,log:1,info:2,warn:3,error:4};constructor(){}static init(e){e&&(e.app?.trim()&&(n._app=e.app),o(e.level)&&(n._level=n.getLevel(e.level)),o(e.prop)&&(n._prop=e.prop),e.style&&n.setStyle(e.style),e.data&&n.set(e.data)),n.attach()}static attach(){n._prop&&o(window)&&Object.defineProperty(window,n._prop,{get:()=>n.get(),configurable:!0})}static log(...e){n.can()&&n.print("log","log",e)}static info(...e){n.can("info")&&n.print("info","info",e)}static success(...e){n.can("success")&&n.print("info","success",e)}static warn(...e){n.can("warn")&&console.warn(...e)}static error(e,...t){n.can("error")&&(e instanceof Error?n._level<4&&e.stack?console.error(e.message,e.stack,...t):console.error(e.message,...t):console.error(e,...t))}static debug(e,...t){n.can("debug")&&console.debug(e,...t)}static group(e,t="log",...o){n.can()&&n.print(e?"groupCollapsed":"group",t,o)}static groupEnd(){n.can()&&console.groupEnd()}static dir(e,t){n.can()&&console.dir(e,t)}static dirxml(...e){n.can()&&console.dirxml(...e)}static count(e){n.can()&&console.count(e)}static countReset(e){n.can()&&console.countReset(e)}static table(e,t){n.can("info")&&console.table(e,t)}static time(e){n.can("info")&&console.time(e)}static timeLog(e,...t){n.can("info")&&console.timeLog(e,...t)}static timeEnd(e){n.can("info")&&console.timeEnd(e)}static trace(e,...t){n.can()&&console.trace(e,...t)}static set(e){if(!o(window))return;const t=s(n._app,!0);Object.defineProperty(window,t,{value:Object.assign(window[t]||{},e),writable:!0,enumerable:!1,configurable:!0})}static get(){return o(window)?window[s(n._app,!0)]:void 0}static setStyle(e,t){"string"==typeof e?n._style[e]=t:Object.assign(n._style,e)}static getStyle(){return n._style}static reset(){o(window)&&(delete window[s(n._app,!0)],delete window[s(n._prop)]),n._level=0,n._app=r,n._prop=c}static can(e="log"){return n.getLevel(e)>=n._level}static getLevel(e){return n._levelMap[e]??2}static print(e,t,o){console[e](...((e,t)=>{return t&&e?.length?[...(o=e[0],s=t,[s.includes("background")?`%c ${o} `:`%c${o}`,s]),...e.slice(1)]:e;var o,s})(o,n._style[t]))}}const a=n.log,i=n.info,l=n.success,p=n.warn,d=n.error,g=n.debug,u=n.group,b=n.groupEnd,w=n.dir,x=n.dirxml,_=n.table,f=n.count,m=n.countReset,y=n.time,v=n.timeLog,E=n.timeEnd,S=n.trace,L=n.set,R=n.init,j=n.reset,k=n.getStyle,O=n.setStyle;exports.DebugWeb=n,exports.count=f,exports.countReset=m,exports.debug=g,exports.debugData=L,exports.debugGetStyle=k,exports.debugInit=R,exports.debugReset=j,exports.debugSetStyle=O,exports.dir=w,exports.dirxml=x,exports.error=d,exports.group=u,exports.groupEnd=b,exports.info=i,exports.log=a,exports.success=l,exports.table=_,exports.time=y,exports.timeEnd=E,exports.timeLog=v,exports.trace=S,exports.warn=p;
1
+ "use strict";const t=()=>"undefined"==typeof window,l=t=>void 0!==t,e=t=>"function"==typeof t,i=t=>`${t}:level`,s=(t,l)=>Symbol.for(t),o=(t=!1)=>"group"+(t?"":"Collapsed"),n=(l,e)=>{try{return t()?void 0:l(window[(e?"local":"session")+"Storage"])}catch(t){return}},r="background",a=(t,l)=>[l.includes(r)?`%c ${t} `:`%c${t}`,l],c=(t,l="#fff")=>`${t?`${r}:${t};`:""}color:${l};padding:2px;border-radius:3px`,h="log",d="info",u="debug",p="warn",v="error",g={[u]:0,[h]:1,[d]:2,[p]:3,[v]:4},_={d:u,l:h,i:d,w:p,e:v,update:"set"},f={[d]:c("#155adc"),mark:c("#695aff"),success:c("#13a10e"),focus:c("#881798"),alert:c("#ffa500"),danger:c("#dc143c")};class b{constructor(t){this.init(t),this.attach()}attach(){this._prop&&!t()&&Object.defineProperty(window,this._prop,{get:()=>this.get(!0),configurable:!0})}log(...t){this.call(h,t,h,!0)}info(...t){this.call(d,t,d,!0)}warn(...t){this.call(p,t,p)}error(...t){this.call(v,t,v)}debug(t,...l){this.call(u,[t,...l],u)}group(t,l=h,...e){this.call(o(t),e,l,!0)}groupEnd(t=h){this.call("groupEnd",[],t)}dir(t,l){this.call("dir",[t,l],h)}dirxml(...t){this.call("dirxml",t,h)}count(t){this.call("count",t,h)}countReset(t){this.call("countReset",t,h)}trace(...t){this.call("trace",t)}table(t,l){this.call("table",[t,l])}time(t){this.call("time",t)}timeLog(t,...l){this.call("timeLog",[t,...l])}timeEnd(t){this.call("timeEnd",t)}set(l){if(t())return;const e=s(this._app),i=Object.assign(window[e]||{},l);Object.keys(i).forEach(t=>{void 0===i[t]&&delete i[t]}),Object.defineProperty(window,e,{value:i,writable:!0,enumerable:!1,configurable:!0})}set level(t){this._lvl=t}get level(){return this._lvl}get style(){return this._style}set style(t){Object.assign(this._style,t)}get(l){if(t())return;const e={...window[s(this._app)]};return l&&(e.setLevel=this.setLvl.bind(this)),e}dump(t,i){const s=this.get();if(!s||!t.length)return;const n=!(null==i?void 0:i.title);this.call(o(null==i?void 0:i.open),[n?s[t[0]]||t[0]:e(i.title)?i.title(s):i.title],null==i?void 0:i.level,!0,!0),this.call("table",[t.reduce((t,e,i)=>(n&&0===i||!l(s[e])||(t[e]=s[e]),t),{})],null==i?void 0:i.level,!1,!0),this.call("groupEnd",[],null==i?void 0:i.level,!1,!0)}call(t,l,e,i=!1,s=!1){const o=this._map[d];var n;!s&&this.getLvl(e,o)<this.getLvl(this._lvl,o)||this.print(t,(n=l,Array.isArray(n)?n:[n]),e,!!i&&!this._native)}init(t){var e,s;this._app=(null==t?void 0:t.app)||"_debug_web",this._prop=l(null==t?void 0:t.prop)?t.prop:d,this._map=g,this._lvl=(e=this._app,s=this._local,n(t=>null==t?void 0:t.getItem(i(e)),s)||(null==t?void 0:t.level)||h),this._native=(null==t?void 0:t.native)||!1,this._local=(null==t?void 0:t.local)||!1,this._style={...f,...null==t?void 0:t.style},(null==t?void 0:t.data)&&this.set(t.data)}getLvl(t,e=-1){const i=t?this._map[t]:void 0;return l(i)?i:e}setLvl(t=!0){this._lvl=!0===t?h:t,((t,l,e)=>{n(e=>(l?null==e||e.setItem(i(t),l):null==e||e.removeItem(i(t)),!0),e)})(this._app,this._lvl,this._local)}print(t,l,e=d,i){const s=i?((t,l)=>l&&(null==t?void 0:t.length)&&"string"==typeof t[0]?[...a(t[0],l),...t.slice(1)]:t)(l,this._style[e]):l;console[t](...s)}}exports.DebugWeb=b,exports.createDebug=function(t,l=b){const i=new l(t),s={..._,...null==t?void 0:t.aliases};return new Proxy(i,{get(t,l){const i=s[l]||l;return t[i]?e(t[i])?t[i].bind(t):t[i]:(...l)=>t.call(d,l,i,!0)}})},exports.getStyle=c,exports.stylizeMsg=a;
package/dist/index.d.ts CHANGED
@@ -1,7 +1,6 @@
1
- type ConsoleMethod = 'debug' | 'log' | 'info' | 'warn' | 'error' | 'group' | 'groupCollapsed';
2
1
  type DebugWebLogLevel = 'debug' | 'log' | 'info' | 'success' | 'warn' | 'error' | string;
3
2
  type DebugWebData = Record<string, unknown>;
4
- type DebugWebStyle = Partial<Record<DebugWebLogLevel, string | null>>;
3
+ type DebugWebStyle = Partial<Record<DebugWebLogLevel, string | undefined>>;
5
4
  interface DebugWebOptions {
6
5
  /** Unique application name
7
6
  * @desc Required to separate data of different applications in the same environment */
@@ -16,128 +15,122 @@ interface DebugWebOptions {
16
15
  data?: DebugWebData;
17
16
  /** Styles map for different logging levels */
18
17
  style?: DebugWebStyle;
18
+ /** Use localStorage instead of sessionStorage
19
+ * @default false */
20
+ local?: boolean;
21
+ /** Use native console methods without styling
22
+ * @default false */
23
+ native?: boolean;
19
24
  }
20
- /**
21
- * Class for centralized collection and output of debugging information
22
- * @singleton
23
- */
25
+ type DebugWebAliasMap = Record<string, DebugWebLogLevel>;
26
+ type CreateDebugOptions = DebugWebOptions & {
27
+ aliases?: DebugWebAliasMap;
28
+ };
29
+ type CustomLogLevels = Record<string, (...attrs: unknown[]) => void>;
30
+ type ConsoleMethod = 'debug' | 'log' | 'info' | 'warn' | 'error' | 'dir' | 'dirxml' | 'count' | 'countReset' | 'table' | 'group' | 'groupCollapsed' | 'groupEnd' | 'time' | 'timeLog' | 'timeEnd' | 'trace';
31
+
32
+ /** Class for centralized collection and output of debugging information */
24
33
  declare class DebugWeb {
25
- protected static _level: number;
26
- protected static _app: string;
27
- protected static _prop: string | null;
28
- protected static _style: DebugWebStyle;
29
- protected static _levelMap: Partial<Record<DebugWebLogLevel, number>>;
30
- protected constructor();
31
- /**
32
- * Creates a Debug instance
33
- * @desc Called once at the application entry point
34
- * @example WebDebug.init({ level: 'error' })
35
- */
36
- static init(options?: DebugWebOptions): void;
37
- /** Create window.info property for data access */
38
- static attach(): void;
39
- /** Output message to Web console
40
- * @see {@link https://developer.mozilla.org/en-US/docs/Web/API/console/log_static console.log} */
41
- static log(...attrs: unknown[]): void;
42
- /** Output informational message
43
- * @see {@link https://developer.mozilla.org/en-US/docs/Web/API/console/info_static console.info} */
44
- static info(...attrs: unknown[]): void;
45
- /** Output success message
46
- * @desc Uses the `console.info` */
47
- static success(...attrs: unknown[]): void;
48
- /** Output warning message
49
- * @desc Method is not styled
50
- * @see {@link https://developer.mozilla.org/en-US/docs/Web/API/console/warn_static console.warn} */
51
- static warn(...attrs: unknown[]): void;
52
- /** Output error message
53
- * @desc Method is not styled
54
- * @see {@link https://developer.mozilla.org/en-US/docs/Web/API/console/error_static console.error} */
55
- static error(error: Error | string, ...attrs: unknown[]): void;
56
- /** Output debug message with low priority
57
- * @see {@link https://developer.mozilla.org/en-US/docs/Web/API/console/debug_static console.debug} */
58
- static debug(message?: unknown, ...attrs: unknown[]): void;
59
- /** Open a group (level: log)
60
- * @desc level only for styling, does not affect logging
61
- * @see {@link https://developer.mozilla.org/en-US/docs/Web/API/console/group_static console.group} */
62
- static group(collapsed?: boolean, level?: DebugWebLogLevel, ...attrs: unknown[]): void;
63
- /** Close the group (level: log)
64
- * @see {@link https://developer.mozilla.org/en-US/docs/Web/API/console/groupEnd_static console.groupEnd} */
65
- static groupEnd(): void;
66
- /** Output an object (level: log)
67
- * @see {@link https://developer.mozilla.org/en-US/docs/Web/API/console/dir_static console.dir} */
68
- static dir(value: unknown, options?: Parameters<typeof console.dir>[1]): void;
69
- /** Output XML/HTML tree of elements (level: log)
70
- * @see {@link https://developer.mozilla.org/en-US/docs/Web/API/console/dirxml_static console.dirxml} */
71
- static dirxml(...attrs: unknown[]): void;
72
- /** Log number of times called with given label (level: log)
73
- * @see {@link https://developer.mozilla.org/en-US/docs/Web/API/console/count_static console.count} */
74
- static count(label?: string): void;
75
- /** Reset counter for the given label (level: log)
76
- * @see {@link https://developer.mozilla.org/en-US/docs/Web/API/console/countReset_static console.countReset} */
77
- static countReset(label?: string): void;
78
- /** Output a table (level: info)
79
- * @see {@link https://developer.mozilla.org/en-US/docs/Web/API/console/table_static console.table} */
80
- static table(data: unknown, properties?: Parameters<typeof console.table>[1]): void;
81
- /** Start timer for execution time measurement (level: info)
82
- * @see {@link https://developer.mozilla.org/en-US/docs/Web/API/console/time_static console.time} */
83
- static time(label?: string): void;
84
- /** Output current timer value (level: info)
85
- * @see {@link https://developer.mozilla.org/en-US/docs/Web/API/console/timeLog_static console.timeLog} */
86
- static timeLog(label?: string, ...attrs: unknown[]): void;
87
- /** Finish execution time measurement (level: info)
88
- * @see {@link https://developer.mozilla.org/en-US/docs/Web/API/console/timeEnd_static console.timeEnd} */
89
- static timeEnd(label?: string): void;
90
- /** Output stack trace (level: log)
91
- * @see {@link https://developer.mozilla.org/en-US/docs/Web/API/console/trace_static console.trace} */
92
- static trace(message?: unknown, ...attrs: unknown[]): void;
93
- /**
94
- * Update debugging data
95
- * @desc Data is stored in the window object
96
- * @example WebDebug.add({ mode })
97
- */
98
- static set(data: DebugWebData): void;
34
+ protected _lvl: DebugWebLogLevel;
35
+ protected _app: string;
36
+ protected _prop: string | null;
37
+ protected _style: DebugWebStyle;
38
+ protected _native: boolean;
39
+ protected _local: boolean;
40
+ /** Log levels mapping */
41
+ protected _map: Partial<Record<DebugWebLogLevel, number>>;
42
+ constructor(options?: DebugWebOptions);
43
+ /** Create window property for data access */
44
+ attach(): void;
45
+ /** Output message to Web console */
46
+ log(...attrs: unknown[]): void;
47
+ /** Output informational message */
48
+ info(...attrs: unknown[]): void;
49
+ /** Output warning message */
50
+ warn(...attrs: unknown[]): void;
51
+ /** Output error message */
52
+ error(...attrs: unknown[]): void;
53
+ /** Output debug message with low priority */
54
+ debug(message?: unknown, ...attrs: unknown[]): void;
55
+ /** Open a group */
56
+ group(open?: boolean, level?: DebugWebLogLevel, ...attrs: unknown[]): void;
57
+ /** Close the group */
58
+ groupEnd(level?: DebugWebLogLevel): void;
59
+ /** Output an object */
60
+ dir(value: unknown, options?: unknown): void;
61
+ /** Output XML/HTML tree of elements */
62
+ dirxml(...attrs: unknown[]): void;
63
+ /** Log number of times called with given label */
64
+ count(label?: string): void;
65
+ /** Reset counter for the given label */
66
+ countReset(label?: string): void;
67
+ /** Output stack trace */
68
+ trace(...attrs: unknown[]): void;
69
+ /** Output a table */
70
+ table(data: unknown, properties?: string[]): void;
71
+ /** Start timer for execution time measurement */
72
+ time(label?: string): void;
73
+ /** Output current timer value */
74
+ timeLog(label?: string, ...attrs: unknown[]): void;
75
+ /** Finish execution time measurement */
76
+ timeEnd(label?: string): void;
77
+ /** Update debugging data */
78
+ set(data: DebugWebData): void;
79
+ /** Persist log level */
80
+ set level(level: DebugWebLogLevel);
81
+ /** Get current log level as string */
82
+ get level(): DebugWebLogLevel;
83
+ /** Get styles map by logging level */
84
+ get style(): DebugWebStyle;
85
+ /** Update styles map by logging level or entirely */
86
+ set style(style: DebugWebStyle);
99
87
  /** Get all collected debugging data */
100
- static get(): any;
101
- /**
102
- * Update styles map by logging level or entirely
103
- * @example WebDebug.setStyle('info', 'color: #155adc')
104
- * @example WebDebug.setStyle({ info: 'color: #155adc', warn: 'color: #ffa500' })
88
+ get(api?: boolean): DebugWebData | undefined;
89
+ /** Display a formatted dump of debugging data by selected keys
90
+ * @param keys - Array of property names to include in the dump
91
+ * @param options - Configuration options for the dump display
92
+ * @param options.level - Logging level for the dump (default: 'info')
93
+ * @param options.title - Custom title or function that returns title based on data
94
+ * @param options.open - If true opens group expanded, if false collapsed (default: false)
95
+ * @desc Groups related debug data into a collapsible console section with table view
105
96
  */
106
- static setStyle(levelOrMap: DebugWebLogLevel | DebugWebStyle, style?: string | null): void;
107
- /** Get styles map by logging level */
108
- static getStyle(): DebugWebStyle;
109
- /** Clear all debugging data and remove global references */
110
- static reset(): void;
111
- /** Check if logging level is enabled */
112
- protected static can(level?: DebugWebLogLevel): boolean;
97
+ dump(keys: string[], options?: {
98
+ level?: DebugWebLogLevel;
99
+ title?: string | ((data: DebugWebData) => string);
100
+ open?: boolean;
101
+ }): void;
102
+ /** Core method for logging with level filtering and formatting
103
+ * @param method - Console method to use (log, info, warn, etc.)
104
+ * @param attrs - Single value or array of values to log
105
+ * @param level - Logging level for filtering (default: based on method)
106
+ * @param stylize - Apply CSS styling to the output (default: false)
107
+ * @param force - Bypass level filtering and always output (default: false)
108
+ * @returns void, exits early if level is below current threshold (unless forced)
109
+ */
110
+ call(method: ConsoleMethod, attrs: unknown | unknown[], level?: DebugWebLogLevel, stylize?: boolean, force?: boolean): void;
111
+ /** Configure instance */
112
+ protected init(options?: DebugWebOptions): void;
113
113
  /** Get logging level priority number */
114
- protected static getLevel(level: DebugWebLogLevel): number;
114
+ protected getLvl(level?: DebugWebLogLevel, defaultValue?: number): number;
115
+ /** Set log level and persist to storage for browser debugging
116
+ * @param level - Target log level or true to reset to default ('log')
117
+ */
118
+ protected setLvl(level?: DebugWebLogLevel | true): void;
115
119
  /** Format and output data using specified console method and level styling */
116
- protected static print(method: ConsoleMethod, level: DebugWebLogLevel, attrs: unknown[]): void;
120
+ protected print(method: ConsoleMethod, attrs: unknown[], level?: DebugWebLogLevel, stylize?: boolean): void;
117
121
  }
118
122
 
119
- declare const log: typeof DebugWeb.log;
120
- declare const info: typeof DebugWeb.info;
121
- declare const success: typeof DebugWeb.success;
122
- declare const warn: typeof DebugWeb.warn;
123
- declare const error: typeof DebugWeb.error;
124
- declare const debug: typeof DebugWeb.debug;
125
- declare const group: typeof DebugWeb.group;
126
- declare const groupEnd: typeof DebugWeb.groupEnd;
127
- declare const dir: typeof DebugWeb.dir;
128
- declare const dirxml: typeof DebugWeb.dirxml;
129
- declare const table: typeof DebugWeb.table;
130
- declare const count: typeof DebugWeb.count;
131
- declare const countReset: typeof DebugWeb.countReset;
132
- declare const time: typeof DebugWeb.time;
133
- declare const timeLog: typeof DebugWeb.timeLog;
134
- declare const timeEnd: typeof DebugWeb.timeEnd;
135
- declare const trace: typeof DebugWeb.trace;
136
- declare const debugData: typeof DebugWeb.set;
137
- declare const debugInit: typeof DebugWeb.init;
138
- declare const debugReset: typeof DebugWeb.reset;
139
- declare const debugGetStyle: typeof DebugWeb.getStyle;
140
- declare const debugSetStyle: typeof DebugWeb.setStyle;
123
+ /** Creates a proxy for DebugWeb instance that allows dynamic logging levels */
124
+ declare function createDebug<T extends typeof DebugWeb>(options?: CreateDebugOptions, DebugClass?: T): CustomLogLevels & InstanceType<T>;
125
+
126
+ /**
127
+ * Style a message for console
128
+ * @desc CSS-style format: `background-color: red; color: white`
129
+ * @example console.log(...stylizeMessage('Error', 'color:red'))
130
+ */
131
+ declare const stylizeMsg: (message: unknown, style: string) => [string, string];
132
+ /** Generate simple CSS styles */
133
+ declare const getStyle: (bg?: string, color?: string) => string;
141
134
 
142
- export { DebugWeb, count, countReset, debug, debugData, debugGetStyle, debugInit, debugReset, debugSetStyle, dir, dirxml, error, group, groupEnd, info, log, success, table, time, timeEnd, timeLog, trace, warn };
143
- export type { DebugWebData, DebugWebLogLevel, DebugWebOptions };
135
+ export { DebugWeb, createDebug, getStyle, stylizeMsg };
136
+ export type { ConsoleMethod, CreateDebugOptions, CustomLogLevels, DebugWebAliasMap, DebugWebData, DebugWebLogLevel, DebugWebOptions, DebugWebStyle };
package/dist/index.mjs CHANGED
@@ -1 +1 @@
1
- const t=(t,e="#fff")=>`background-color: ${t}; color: ${e}; padding: 2px; border-radius: 3px;`,e={info:t("#155adc"),success:t("#13a10e"),warn:t("#ffa500"),error:t("#dc143c")},o=t=>void 0!==t,c=(t,e=!1)=>e?Symbol.for(t):t,n="__web_debug__",s="info";class a{static _level=0;static _app=n;static _prop=s;static _style=e;static _levelMap={debug:0,log:1,info:2,warn:3,error:4};constructor(){}static init(t){t&&(t.app?.trim()&&(a._app=t.app),o(t.level)&&(a._level=a.getLevel(t.level)),o(t.prop)&&(a._prop=t.prop),t.style&&a.setStyle(t.style),t.data&&a.set(t.data)),a.attach()}static attach(){a._prop&&o(window)&&Object.defineProperty(window,a._prop,{get:()=>a.get(),configurable:!0})}static log(...t){a.can()&&a.print("log","log",t)}static info(...t){a.can("info")&&a.print("info","info",t)}static success(...t){a.can("success")&&a.print("info","success",t)}static warn(...t){a.can("warn")&&console.warn(...t)}static error(t,...e){a.can("error")&&(t instanceof Error?a._level<4&&t.stack?console.error(t.message,t.stack,...e):console.error(t.message,...e):console.error(t,...e))}static debug(t,...e){a.can("debug")&&console.debug(t,...e)}static group(t,e="log",...o){a.can()&&a.print(t?"groupCollapsed":"group",e,o)}static groupEnd(){a.can()&&console.groupEnd()}static dir(t,e){a.can()&&console.dir(t,e)}static dirxml(...t){a.can()&&console.dirxml(...t)}static count(t){a.can()&&console.count(t)}static countReset(t){a.can()&&console.countReset(t)}static table(t,e){a.can("info")&&console.table(t,e)}static time(t){a.can("info")&&console.time(t)}static timeLog(t,...e){a.can("info")&&console.timeLog(t,...e)}static timeEnd(t){a.can("info")&&console.timeEnd(t)}static trace(t,...e){a.can()&&console.trace(t,...e)}static set(t){if(!o(window))return;const e=c(a._app,!0);Object.defineProperty(window,e,{value:Object.assign(window[e]||{},t),writable:!0,enumerable:!1,configurable:!0})}static get(){return o(window)?window[c(a._app,!0)]:void 0}static setStyle(t,e){"string"==typeof t?a._style[t]=e:Object.assign(a._style,t)}static getStyle(){return a._style}static reset(){o(window)&&(delete window[c(a._app,!0)],delete window[c(a._prop)]),a._level=0,a._app=n,a._prop=s}static can(t="log"){return a.getLevel(t)>=a._level}static getLevel(t){return a._levelMap[t]??2}static print(t,e,o){console[t](...((t,e)=>{return e&&t?.length?[...(o=t[0],c=e,[c.includes("background")?`%c ${o} `:`%c${o}`,c]),...t.slice(1)]:t;var o,c})(o,a._style[e]))}}const r=a.log,i=a.info,l=a.success,p=a.warn,d=a.error,g=a.debug,u=a.group,_=a.groupEnd,w=a.dir,f=a.dirxml,b=a.table,m=a.count,v=a.countReset,y=a.time,E=a.timeLog,x=a.timeEnd,L=a.trace,S=a.set,j=a.init,k=a.reset,O=a.getStyle,$=a.setStyle;export{a as DebugWeb,m as count,v as countReset,g as debug,S as debugData,O as debugGetStyle,j as debugInit,k as debugReset,$ as debugSetStyle,w as dir,f as dirxml,d as error,u as group,_ as groupEnd,i as info,r as log,l as success,b as table,y as time,x as timeEnd,E as timeLog,L as trace,p as warn};
1
+ const t=()=>"undefined"==typeof window,l=t=>void 0!==t,e=t=>"function"==typeof t,i=t=>`${t}:level`,s=(t,l)=>Symbol.for(t),n=(t=!1)=>"group"+(t?"":"Collapsed"),o=(l,e)=>{try{return t()?void 0:l(window[(e?"local":"session")+"Storage"])}catch(t){return}},a="background",r=(t,l)=>[l.includes(a)?`%c ${t} `:`%c${t}`,l],c=(t,l="#fff")=>`${t?`${a}:${t};`:""}color:${l};padding:2px;border-radius:3px`,h="log",d="info",u="debug",p="warn",v="error",g={[u]:0,[h]:1,[d]:2,[p]:3,[v]:4},_={d:u,l:h,i:d,w:p,e:v,update:"set"},f={[d]:c("#155adc"),mark:c("#695aff"),success:c("#13a10e"),focus:c("#881798"),alert:c("#ffa500"),danger:c("#dc143c")};class b{constructor(t){this.init(t),this.attach()}attach(){this._prop&&!t()&&Object.defineProperty(window,this._prop,{get:()=>this.get(!0),configurable:!0})}log(...t){this.call(h,t,h,!0)}info(...t){this.call(d,t,d,!0)}warn(...t){this.call(p,t,p)}error(...t){this.call(v,t,v)}debug(t,...l){this.call(u,[t,...l],u)}group(t,l=h,...e){this.call(n(t),e,l,!0)}groupEnd(t=h){this.call("groupEnd",[],t)}dir(t,l){this.call("dir",[t,l],h)}dirxml(...t){this.call("dirxml",t,h)}count(t){this.call("count",t,h)}countReset(t){this.call("countReset",t,h)}trace(...t){this.call("trace",t)}table(t,l){this.call("table",[t,l])}time(t){this.call("time",t)}timeLog(t,...l){this.call("timeLog",[t,...l])}timeEnd(t){this.call("timeEnd",t)}set(l){if(t())return;const e=s(this._app),i=Object.assign(window[e]||{},l);Object.keys(i).forEach(t=>{void 0===i[t]&&delete i[t]}),Object.defineProperty(window,e,{value:i,writable:!0,enumerable:!1,configurable:!0})}set level(t){this._lvl=t}get level(){return this._lvl}get style(){return this._style}set style(t){Object.assign(this._style,t)}get(l){if(t())return;const e={...window[s(this._app)]};return l&&(e.setLevel=this.setLvl.bind(this)),e}dump(t,i){const s=this.get();if(!s||!t.length)return;const o=!(null==i?void 0:i.title);this.call(n(null==i?void 0:i.open),[o?s[t[0]]||t[0]:e(i.title)?i.title(s):i.title],null==i?void 0:i.level,!0,!0),this.call("table",[t.reduce((t,e,i)=>(o&&0===i||!l(s[e])||(t[e]=s[e]),t),{})],null==i?void 0:i.level,!1,!0),this.call("groupEnd",[],null==i?void 0:i.level,!1,!0)}call(t,l,e,i=!1,s=!1){const n=this._map[d];var o;!s&&this.getLvl(e,n)<this.getLvl(this._lvl,n)||this.print(t,(o=l,Array.isArray(o)?o:[o]),e,!!i&&!this._native)}init(t){var e,s;this._app=(null==t?void 0:t.app)||"_debug_web",this._prop=l(null==t?void 0:t.prop)?t.prop:d,this._map=g,this._lvl=(e=this._app,s=this._local,o(t=>null==t?void 0:t.getItem(i(e)),s)||(null==t?void 0:t.level)||h),this._native=(null==t?void 0:t.native)||!1,this._local=(null==t?void 0:t.local)||!1,this._style={...f,...null==t?void 0:t.style},(null==t?void 0:t.data)&&this.set(t.data)}getLvl(t,e=-1){const i=t?this._map[t]:void 0;return l(i)?i:e}setLvl(t=!0){this._lvl=!0===t?h:t,((t,l,e)=>{o(e=>(l?null==e||e.setItem(i(t),l):null==e||e.removeItem(i(t)),!0),e)})(this._app,this._lvl,this._local)}print(t,l,e=d,i){const s=i?((t,l)=>l&&(null==t?void 0:t.length)&&"string"==typeof t[0]?[...r(t[0],l),...t.slice(1)]:t)(l,this._style[e]):l;console[t](...s)}}function m(t,l=b){const i=new l(t),s={..._,...null==t?void 0:t.aliases};return new Proxy(i,{get(t,l){const i=s[l]||l;return t[i]?e(t[i])?t[i].bind(t):t[i]:(...l)=>t.call(d,l,i,!0)}})}export{b as DebugWeb,m as createDebug,c as getStyle,r as stylizeMsg};