unist-plugin-log-tree 1.0.1

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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 ipikuka
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,392 @@
1
+ **A robust Next.js newsletter `Next.js Weekly` is sponsoring me** 💖
2
+ [![NextjsWeekly banner](./assets/next-js-weekly.png)](https://nextjsweekly.com/)
3
+
4
+ ### [Become a sponsor](https://github.com/sponsors/ipikuka) 🚀
5
+
6
+ If you find **`unist-plugin-log-tree`** useful in your projects, consider supporting my work.
7
+ Your sponsorship means a lot 💖
8
+
9
+ My sponsors are going to be featured here and on [my sponsor wall](https://github.com/sponsors/ipikuka).
10
+
11
+ A warm thanks 🙌 to [@ErfanEbrahimnia](https://github.com/ErfanEbrahimnia), [@recepkyk](https://github.com/recepkyk), and [@LSeaburg](https://github.com/LSeaburg) for the support!
12
+
13
+ Thank you for supporting open source! 🙌
14
+
15
+ # unist-plugin-log-tree
16
+
17
+ [![npm version][badge-npm-version]][url-npm-package]
18
+ [![npm downloads][badge-npm-download]][url-npm-package]
19
+ [![publish to npm][badge-publish-to-npm]][url-publish-github-actions]
20
+ [![code-coverage][badge-codecov]][url-codecov]
21
+ [![type-coverage][badge-type-coverage]][url-github-package]
22
+ [![typescript][badge-typescript]][url-typescript]
23
+ [![license][badge-license]][url-license]
24
+
25
+ This package is a [**unified**][unified] ([**remark**][remark]) plugin **to log and optionally filter unist syntax trees for debugging purposes.** It is debugging plugin for the unified ecosystem that logs unist syntax trees without transforming.
26
+
27
+ [**unified**][unified] is a project that transforms content with abstract syntax trees (ASTs) using the new parser [**micromark**][micromark]. [**remark**][remark] adds support for markdown to unified. [**mdast**][mdast] is the Markdown Abstract Syntax Tree (AST) which is a specification for representing markdown in a syntax tree. **[rehype][rehype]** is a tool that transforms HTML with plugins. **[hast][hast]** stands for HTML Abstract Syntax Tree (HAST) that rehype uses. **[recma][recma]** adds support for producing a javascript code by transforming **[esast][esast]** which stands for Ecma Script Abstract Syntax Tree (AST) that is used in production of compiled source for the **[MDX][MDX]**.
28
+
29
+ **This plugin is a universal syntax tree (unist) plugin for mdast, hast, estree, and other unist-based trees. It does not transform the tree; it only inspects and logs it for debugging.**
30
+
31
+ # unist-plugin-log-tree
32
+
33
+ A debugging plugin for the unified ecosystem that logs unist syntax trees without transforming them.
34
+
35
+ ## When should I use this?
36
+
37
+ **`unist-plugin-log-tree`** is useful when you want to **inspect, debug, or snapshot syntax trees** during a unified processing pipeline.
38
+
39
+ It works with any unist-compatible tree:
40
+
41
+ - mdast (remark)
42
+ - hast (rehype)
43
+ - estree / recma
44
+ - any custom unist-based AST
45
+
46
+ This plugin:
47
+
48
+ - ✅ Logs the syntax tree to the console
49
+ - ✅ Optionally filters nodes using `test`
50
+ - ✅ Preserves parent chains when filtering
51
+ - ✅ Optionally preserves full subtrees
52
+ - ✅ Can hide `position` data
53
+ - ❌ Does **not** transform or mutate the original tree
54
+
55
+ It is purely a debugging utility.
56
+
57
+ ## Installation
58
+
59
+ This package is ESM only.
60
+
61
+ In Node.js (version 16+), install with npm:
62
+
63
+ ```bash
64
+ npm install unist-plugin-log-tree
65
+ ```
66
+
67
+ or
68
+
69
+ ```bash
70
+ yarn add unist-plugin-log-tree
71
+ ```
72
+
73
+ ## Usage
74
+
75
+ ### ⚠️ Important: Factory Pattern Usage
76
+
77
+ This plugin follows a **factory pattern**.
78
+
79
+ Unlike typical unified plugins that are used like this:
80
+
81
+ ```js
82
+ .use(plugin, options)
83
+ ```
84
+
85
+ this plugin **must be used like this**:
86
+
87
+ ```js
88
+ .use(plugin(options))
89
+ ```
90
+
91
+ ### Why?
92
+
93
+ The plugin is implemented as a factory so that it can be used multiple times in a single unified pipeline — for example, to log different stages (mdast, hast, etc.) independently.
94
+
95
+ Because of this structure, it returns a configured plugin instance immediately, which is why `.use(plugin(options))` is required.
96
+
97
+ ### Basic usage (log full tree)
98
+
99
+ ```js
100
+ import { read } from "to-vfile";
101
+ import { unified } from "unified";
102
+ import remarkParse from "remark-parse";
103
+ import logTree from "unist-plugin-log-tree";
104
+
105
+ const file = await unified()
106
+ .use(remarkParse)
107
+ .use(logTree()) // ← factory call
108
+ .process(await read("example.md"));
109
+ ```
110
+
111
+ Running this will print the full mdast to the console.
112
+
113
+ ### With filtering
114
+
115
+ You can pass a `test` option (powered by `unist-util-is`) to log only specific nodes.
116
+
117
+ ```js
118
+ .use(logTree({ test: "heading" }))
119
+ ```
120
+
121
+ This will:
122
+
123
+ - Keep only `heading` nodes
124
+ - Preserve their parent chain
125
+ - Remove unrelated branches
126
+
127
+ ### With label
128
+
129
+ ```js
130
+ .use(logTree({ label: "Remark AST" }))
131
+ ```
132
+
133
+ Console output:
134
+
135
+ ```
136
+ [unist-log-tree] Remark AST
137
+ { ...tree }
138
+ ```
139
+
140
+ ### In a full pipeline (remark → rehype)
141
+
142
+ ```js
143
+ import remarkParse from "remark-parse";
144
+ import remarkRehype from "remark-rehype";
145
+ import rehypeStringify from "rehype-stringify";
146
+ import logTree from "unist-plugin-log-tree";
147
+
148
+ await unified()
149
+ .use(remarkParse)
150
+ .use(logTree({ label: "MDAST" }))
151
+ .use(remarkRehype)
152
+ .use(logTree({ label: "HAST" }))
153
+ .use(rehypeStringify)
154
+ .process("# Hello");
155
+ ```
156
+
157
+ This logs both the mdast and hast trees.
158
+
159
+ ## Options
160
+
161
+ All options are optional.
162
+
163
+ ```ts
164
+ type UnistLogTreeOptions = {
165
+ test?: Test;
166
+ preserveSubtree?: boolean;
167
+ preservePositions?: boolean;
168
+ depth?: number | null;
169
+ indentation?: number;
170
+ label?: string;
171
+ enabled?: boolean;
172
+ };
173
+ ```
174
+
175
+ ### `test`
176
+
177
+ Type: `Test` (from `unist-util-is`)
178
+ Default: `undefined`
179
+
180
+ Filters the tree. Only matching nodes and their parent chain are kept.
181
+
182
+ Examples:
183
+
184
+ ```js
185
+ test: "heading"
186
+ test: ["heading", "paragraph"]
187
+ test: (node) => node.type === "link"
188
+ ```
189
+
190
+ If `test` is `undefined` or `null`, the full tree is logged.
191
+
192
+ ### `preserveSubtree`
193
+
194
+ Type: `boolean`
195
+ Default: `true`
196
+
197
+ Controls behavior when a node matches `test`.
198
+
199
+ - `true` → Keep the entire subtree of the matched node.
200
+ - `false` → Recursively filter its children as well.
201
+
202
+ Example:
203
+
204
+ ```js
205
+ .use(logTree({
206
+ test: "heading",
207
+ preserveSubtree: false
208
+ }))
209
+ ```
210
+
211
+ ### `preservePositions`
212
+
213
+ Type: `boolean`
214
+ Default: `false`
215
+
216
+ Controls whether `position` data is included in the output.
217
+
218
+ ```js
219
+ .use(logTree({ preservePositions: true }))
220
+ ```
221
+
222
+ ### `depth`
223
+
224
+ Type: `number | null`
225
+ Default: `null`
226
+
227
+ Passed to `console.dir` as the `depth` option.
228
+
229
+ ```js
230
+ .use(logTree({ depth: 4 }))
231
+ ```
232
+
233
+ ### `indentation`
234
+
235
+ Type: `number`
236
+ Default: `2`
237
+
238
+ Controls JSON indentation size before printing.
239
+
240
+ ### `label`
241
+
242
+ Type: `string`
243
+ Default: `undefined`
244
+
245
+ Adds a label before the logged tree.
246
+
247
+ ```js
248
+ .use(logTree({ label: "Rehype AST" }))
249
+ ```
250
+
251
+ ### `enabled`
252
+
253
+ Type: `boolean`
254
+ Default: `true`
255
+
256
+ Allows turning the logger off without removing it from the pipeline.
257
+
258
+ ```js
259
+ .use(logTree({ enabled: false }))
260
+ ```
261
+
262
+ Useful in CI or production builds.
263
+
264
+ ## Filtering Behavior
265
+
266
+ When `test` is provided:
267
+
268
+ - Matching nodes are kept.
269
+ - Parent nodes are preserved if any descendant matches.
270
+ - Non-matching branches are removed.
271
+ - The original AST is never mutated.
272
+
273
+ The plugin internally clones the tree before pruning.
274
+
275
+ ## Syntax Tree
276
+
277
+ This plugin does **not** transform the syntax tree. It:
278
+
279
+ - Clones the tree (when filtering)
280
+ - Optionally prunes branches
281
+ - Logs the result
282
+ - Leaves the original AST untouched
283
+
284
+ ## Types
285
+
286
+ This package is fully typed with TypeScript. The options type is exported as:
287
+
288
+ ```ts
289
+ UnistLogTreeOptions
290
+ ```
291
+
292
+ ## Compatibility
293
+
294
+ This plugin works with unified version `6+`, and any unist-compatible trees in a plugin chain of remark, rehype, recma.
295
+
296
+ ## Security
297
+
298
+ This plugin does not generate HTML, execute user code, or manipulate output content. It only logs syntax trees to the console. There are no XSS or runtime security concerns.
299
+
300
+ ## My Plugins
301
+
302
+ I like to contribute the Unified / Remark / MDX ecosystem, so I recommend you to have a look my plugins.
303
+
304
+ ### My Remark Plugins
305
+
306
+ - [`remark-flexible-code-titles`](https://www.npmjs.com/package/remark-flexible-code-titles)
307
+ – Remark plugin to add titles or/and containers for the code blocks with customizable properties
308
+ - [`remark-flexible-containers`](https://www.npmjs.com/package/remark-flexible-containers)
309
+ – Remark plugin to add custom containers with customizable properties in markdown
310
+ - [`remark-ins`](https://www.npmjs.com/package/remark-ins)
311
+ – Remark plugin to add `ins` element in markdown
312
+ - [`remark-flexible-paragraphs`](https://www.npmjs.com/package/remark-flexible-paragraphs)
313
+ – Remark plugin to add custom paragraphs with customizable properties in markdown
314
+ - [`remark-flexible-markers`](https://www.npmjs.com/package/remark-flexible-markers)
315
+ – Remark plugin to add custom `mark` element with customizable properties in markdown
316
+ - [`remark-flexible-toc`](https://www.npmjs.com/package/remark-flexible-toc)
317
+ – Remark plugin to expose the table of contents via `vfile.data` or via an option reference
318
+ - [`remark-mdx-remove-esm`](https://www.npmjs.com/package/remark-mdx-remove-esm)
319
+ – Remark plugin to remove import and/or export statements (mdxjsEsm)
320
+ - [`remark-mdx-remove-expressions`](https://www.npmjs.com/package/remark-mdx-remove-expressions)
321
+ – Remark plugin to remove MDX expressions within curlybraces {} in MDX content
322
+
323
+ ### My Rehype Plugins
324
+
325
+ - [`rehype-pre-language`](https://www.npmjs.com/package/rehype-pre-language)
326
+ – Rehype plugin to add language information as a property to `pre` element
327
+ - [`rehype-highlight-code-lines`](https://www.npmjs.com/package/rehype-highlight-code-lines)
328
+ – Rehype plugin to add line numbers to code blocks and allow highlighting of desired code lines
329
+ - [`rehype-code-meta`](https://www.npmjs.com/package/rehype-code-meta)
330
+ – Rehype plugin to copy `code.data.meta` to `code.properties.metastring`
331
+ - [`rehype-image-toolkit`](https://www.npmjs.com/package/rehype-image-toolkit)
332
+ – Rehype plugin to enhance Markdown image syntax `![]()` and Markdown/MDX media elements (`<img>`, `<audio>`, `<video>`) by auto-linking bracketed or parenthesized image URLs, wrapping them in `<figure>` with optional captions, unwrapping images/videos/audio from paragraph, parsing directives in title for styling and adding attributes, and dynamically converting images into `<video>` or `<audio>` elements based on file extension.
333
+
334
+ ### My Recma Plugins
335
+
336
+ - [`recma-mdx-escape-missing-components`](https://www.npmjs.com/package/recma-mdx-escape-missing-components)
337
+ – Recma plugin to set the default value `() => null` for the Components in MDX in case of missing or not provided so as not to throw an error
338
+ - [`recma-mdx-change-props`](https://www.npmjs.com/package/recma-mdx-change-props)
339
+ – Recma plugin to change the `props` parameter into the `_props` in the `function _createMdxContent(props) {/* */}` in the compiled source in order to be able to use `{props.foo}` like expressions. It is useful for the `next-mdx-remote` or `next-mdx-remote-client` users in `nextjs` applications.
340
+ - [`recma-mdx-change-imports`](https://www.npmjs.com/package/recma-mdx-change-imports)
341
+ – Recma plugin to convert import declarations for assets and media with relative links into variable declarations with string URLs, enabling direct asset URL resolution in compiled MDX.
342
+ - [`recma-mdx-import-media`](https://www.npmjs.com/package/recma-mdx-import-media)
343
+ – Recma plugin to turn media relative paths into import declarations for both markdown and html syntax in MDX.
344
+ - [`recma-mdx-import-react`](https://www.npmjs.com/package/recma-mdx-import-react)
345
+ – Recma plugin to ensure getting `React` instance from the arguments and to make the runtime props `{React, jsx, jsxs, jsxDev, Fragment}` is available in the dynamically imported components in the compiled source of MDX.
346
+ - [`recma-mdx-html-override`](https://www.npmjs.com/package/recma-mdx-html-override)
347
+ – Recma plugin to allow selected raw HTML elements to be overridden via MDX components.
348
+ - [`recma-mdx-interpolate`](https://www.npmjs.com/package/recma-mdx-interpolate)
349
+ – Recma plugin to enable interpolation of identifiers wrapped in curly braces within the `alt`, `src`, `href`, and `title` attributes of markdown link and image syntax in MDX.
350
+
351
+ ### My Unist Utils and Plugins
352
+
353
+ I also build low-level utilities and plugins for the Unist ecosystem that can be used across Remark, Rehype, Recma, and other syntax trees.
354
+
355
+ - [`unist-util-find-between-all`](https://www.npmjs.com/package/unist-util-find-between-all)
356
+ – Unist utility to find the nodes between two nodes.
357
+ - [`unist-plugin-log-tree`](https://www.npmjs.com/package/unist-plugin-log-tree)
358
+ – Debugging plugin for the unified ecosystem that logs abstract syntax trees (ASTs) without transforming.
359
+
360
+ ## License
361
+
362
+ [MIT License](./LICENSE) © ipikuka
363
+
364
+ [unified]: https://github.com/unifiedjs/unified
365
+ [micromark]: https://github.com/micromark/micromark
366
+ [remark]: https://github.com/remarkjs/remark
367
+ [mdast]: https://github.com/syntax-tree/mdast
368
+ [rehype]: https://github.com/rehypejs/rehype
369
+ [hast]: https://github.com/syntax-tree/hast
370
+ [recma]: https://mdxjs.com/docs/extending-mdx/#list-of-plugins
371
+ [esast]: https://github.com/syntax-tree/esast
372
+ [MDX]: https://mdxjs.com/
373
+
374
+ [badge-npm-version]: https://img.shields.io/npm/v/unist-plugin-log-tree
375
+ [badge-npm-download]:https://img.shields.io/npm/dt/unist-plugin-log-tree
376
+ [url-npm-package]: https://www.npmjs.com/package/unist-plugin-log-tree
377
+ [url-github-package]: https://github.com/ipikuka/unist-plugin-log-tree
378
+
379
+ [badge-license]: https://img.shields.io/github/license/ipikuka/unist-plugin-log-tree
380
+ [url-license]: https://github.com/ipikuka/unist-plugin-log-tree/blob/main/LICENSE
381
+
382
+ [badge-publish-to-npm]: https://github.com/ipikuka/unist-plugin-log-tree/actions/workflows/publish.yml/badge.svg
383
+ [url-publish-github-actions]: https://github.com/ipikuka/unist-plugin-log-tree/actions/workflows/publish.yml
384
+
385
+ [badge-typescript]: https://img.shields.io/npm/types/unist-plugin-log-tree
386
+ [url-typescript]: https://www.typescriptlang.org/
387
+
388
+ [badge-codecov]: https://codecov.io/gh/ipikuka/unist-plugin-log-tree/graph/badge.svg?token=bzXcCBzY4P
389
+ [url-codecov]: https://codecov.io/gh/ipikuka/unist-plugin-log-tree
390
+
391
+ [badge-type-coverage]: https://img.shields.io/badge/dynamic/json.svg?label=type-coverage&prefix=%E2%89%A5&suffix=%&query=$.typeCoverage.atLeast&uri=https%3A%2F%2Fraw.githubusercontent.com%2Fipikuka%2Funist-plugin-log-tree%2Fmaster%2Fpackage.json
392
+
@@ -0,0 +1,28 @@
1
+ import type { Plugin } from "unified";
2
+ import type { Node as UnistNode } from "unist";
3
+ import type { Test } from "unist-util-is";
4
+ export interface Node extends UnistNode {
5
+ [key: string]: unknown;
6
+ }
7
+ export type UnistLogTreeOptions = {
8
+ depth?: number | null;
9
+ indentation?: number;
10
+ preservePositions?: boolean;
11
+ test?: Test;
12
+ preserveSubtree?: boolean;
13
+ label?: string;
14
+ enabled?: boolean;
15
+ };
16
+ /**
17
+ * Debug utility plugin for unified processors.
18
+ *
19
+ * Logs the current unist tree (mdast, hast, estree, etc.)
20
+ * with optional filtering and formatting controls.
21
+ *
22
+ * If `test` is provided, only matching nodes and their
23
+ * parent chain are preserved in the output.
24
+ *
25
+ * The original tree is never mutated.
26
+ */
27
+ export default function plugin(options?: UnistLogTreeOptions): Plugin<[], Node>;
28
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,SAAS,CAAC;AACtC,OAAO,KAAK,EAAE,IAAI,IAAI,SAAS,EAAE,MAAM,OAAO,CAAC;AAC/C,OAAO,KAAK,EAAE,IAAI,EAAE,MAAM,eAAe,CAAC;AAO1C,MAAM,WAAW,IAAK,SAAQ,SAAS;IACrC,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO,CAAC;CACxB;AAED,MAAM,MAAM,mBAAmB,GAAG;IAChC,KAAK,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;IACtB,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB,iBAAiB,CAAC,EAAE,OAAO,CAAC;IAC5B,IAAI,CAAC,EAAE,IAAI,CAAC;IACZ,eAAe,CAAC,EAAE,OAAO,CAAC;IAC1B,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,OAAO,CAAC,EAAE,OAAO,CAAC;CACnB,CAAC;AAmBF;;;;;;;;;;GAUG;AACH,MAAM,CAAC,OAAO,UAAU,MAAM,CAAC,OAAO,CAAC,EAAE,mBAAmB,GAAG,MAAM,CAAC,EAAE,EAAE,IAAI,CAAC,CAqJ9E"}
package/dist/index.js ADDED
@@ -0,0 +1,140 @@
1
+ import { is } from "unist-util-is";
2
+ const DEFAULT_SETTINGS = {
3
+ depth: null,
4
+ indentation: 2,
5
+ preservePositions: false,
6
+ test: undefined,
7
+ preserveSubtree: true,
8
+ label: undefined,
9
+ enabled: true,
10
+ };
11
+ /**
12
+ * Debug utility plugin for unified processors.
13
+ *
14
+ * Logs the current unist tree (mdast, hast, estree, etc.)
15
+ * with optional filtering and formatting controls.
16
+ *
17
+ * If `test` is provided, only matching nodes and their
18
+ * parent chain are preserved in the output.
19
+ *
20
+ * The original tree is never mutated.
21
+ */
22
+ export default function plugin(options) {
23
+ return function attacher() {
24
+ const settings = Object.assign({}, DEFAULT_SETTINGS, options);
25
+ // early exit
26
+ if (!settings.enabled) {
27
+ return function transformer(tree) {
28
+ return tree;
29
+ };
30
+ }
31
+ /*
32
+ * Type guard to check if an array of Node
33
+ */
34
+ function isNodeArray(value) {
35
+ return (Array.isArray(value) &&
36
+ value.every((item) => item && typeof item === "object" && "type" in item));
37
+ }
38
+ /*
39
+ * Type guard to check if a node is a unist Node
40
+ */
41
+ function isNode(value) {
42
+ return !!value && typeof value === "object" && "type" in value;
43
+ }
44
+ /**
45
+ * Builds a minimal subtree that keeps only nodes matching the test and their parent chain.
46
+ * It uses prune algoritm that works on children key, so with mdast and hast okey but with esast doesn't work
47
+ */
48
+ // function buildFilteredTreeEx(root: Node, test: Test): Node {
49
+ // const cloned = structuredClone(root);
50
+ // function prune(node: Node): boolean {
51
+ // const matched = is(node, test);
52
+ // if (isParent(node)) {
53
+ // if (matched && settings.preserveSubtree !== false) {
54
+ // return true; // don't touch subtree
55
+ // }
56
+ // node.children = node.children.filter((child) => prune(child));
57
+ // }
58
+ // if (matched) return true;
59
+ // if (isParent(node)) {
60
+ // return node.children.length > 0;
61
+ // }
62
+ // return false;
63
+ // }
64
+ // const keepRoot = prune(cloned);
65
+ // if (!keepRoot && isParent(cloned)) {
66
+ // cloned.children = [];
67
+ // }
68
+ // return cloned;
69
+ // }
70
+ /**
71
+ * Builds a minimal subtree that keeps only nodes matching the test and their parent chain.
72
+ * It is a universal travel algoritim works with any AST like mdast, hast, esast and others
73
+ */
74
+ function buildFilteredTree(root, test) {
75
+ const cloned = structuredClone(root);
76
+ function prune(node) {
77
+ const matched = is(node, test);
78
+ let hasChildMatch = false;
79
+ for (const key in node) {
80
+ if (key === "position")
81
+ continue;
82
+ const value = node[key];
83
+ if (!value)
84
+ continue;
85
+ if (isNodeArray(value)) {
86
+ let containsNode = false;
87
+ for (let i = value.length - 1; i >= 0; i--) {
88
+ const item = value[i];
89
+ /* v8 ignore next -- @preserve */
90
+ if (isNode(item)) {
91
+ containsNode = true;
92
+ const keep = prune(item);
93
+ if (!keep) {
94
+ value.splice(i, 1);
95
+ }
96
+ else {
97
+ hasChildMatch = true;
98
+ }
99
+ }
100
+ }
101
+ if (containsNode && value.length === 0) {
102
+ node[key] = [];
103
+ }
104
+ }
105
+ else if (isNode(value)) {
106
+ const keep = prune(value);
107
+ if (!keep) {
108
+ delete node[key];
109
+ }
110
+ else {
111
+ hasChildMatch = true;
112
+ }
113
+ }
114
+ }
115
+ if (matched && settings.preserveSubtree !== false) {
116
+ return true; // don't touch subtree
117
+ }
118
+ if (matched)
119
+ return true;
120
+ return hasChildMatch;
121
+ }
122
+ prune(cloned);
123
+ return cloned;
124
+ }
125
+ return function transformer(tree) {
126
+ const targetTree = settings.test != null ? buildFilteredTree(tree, settings.test) : tree;
127
+ if (settings.label) {
128
+ console.log(`[unist-log-tree] ${settings.label}`);
129
+ }
130
+ const output = JSON.parse(JSON.stringify(targetTree, (key, value) => {
131
+ if (!settings.preservePositions && key === "position") {
132
+ return undefined;
133
+ }
134
+ return value;
135
+ }));
136
+ console.dir(output, { depth: settings.depth });
137
+ };
138
+ };
139
+ }
140
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,EAAE,EAAE,MAAM,eAAe,CAAC;AAoBnC,MAA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,CAAC,CAAC;QACjD,CAAC,CAAC;IACJ,CAAC,CAAC;AACJ,CAAC","sourcesContent":["import type { Plugin } from \"unified\";\nimport type { Node as UnistNode } from \"unist\";\nimport type { Test } from \"unist-util-is\";\nimport { is } from \"unist-util-is\";\n\ntype Prettify<T> = { [K in keyof T]: T[K] } & {};\n\ntype PartiallyRequired<T, K extends keyof T> = Omit<T, K> & Required<Pick<T, K>>;\n\nexport interface Node extends UnistNode {\n [key: string]: unknown;\n}\n\nexport type UnistLogTreeOptions = {\n depth?: number | null;\n indentation?: number;\n preservePositions?: boolean;\n test?: Test;\n preserveSubtree?: boolean;\n label?: string;\n enabled?: boolean;\n};\n\nconst DEFAULT_SETTINGS: UnistLogTreeOptions = {\n depth: null,\n indentation: 2,\n preservePositions: false,\n test: undefined,\n preserveSubtree: true,\n label: undefined,\n enabled: true,\n};\n\ntype PartiallyRequiredOptions = Prettify<\n PartiallyRequired<\n UnistLogTreeOptions,\n \"depth\" | \"indentation\" | \"preservePositions\" | \"enabled\"\n >\n>;\n\n/**\n * Debug utility plugin for unified processors.\n *\n * Logs the current unist tree (mdast, hast, estree, etc.)\n * with optional filtering and formatting controls.\n *\n * If `test` is provided, only matching nodes and their\n * parent chain are preserved in the output.\n *\n * The original tree is never mutated.\n */\nexport default function plugin(options?: UnistLogTreeOptions): Plugin<[], Node> {\n return function attacher() {\n const settings = Object.assign({}, DEFAULT_SETTINGS, options) as PartiallyRequiredOptions;\n\n // early exit\n if (!settings.enabled) {\n return function transformer(tree: Node) {\n return tree;\n };\n }\n\n /*\n * Type guard to check if an array of Node\n */\n function isNodeArray(value: unknown): value is Node[] {\n return (\n Array.isArray(value) &&\n (value as unknown[]).every((item) => item && typeof item === \"object\" && \"type\" in item)\n );\n }\n\n /*\n * Type guard to check if a node is a unist Node\n */\n function isNode(value: unknown): value is Node {\n return !!value && typeof value === \"object\" && \"type\" in value;\n }\n\n /**\n * Builds a minimal subtree that keeps only nodes matching the test and their parent chain.\n * It uses prune algoritm that works on children key, so with mdast and hast okey but with esast doesn't work\n */\n // function buildFilteredTreeEx(root: Node, test: Test): Node {\n // const cloned = structuredClone(root);\n\n // function prune(node: Node): boolean {\n // const matched = is(node, test);\n\n // if (isParent(node)) {\n // if (matched && settings.preserveSubtree !== false) {\n // return true; // don't touch subtree\n // }\n\n // node.children = node.children.filter((child) => prune(child));\n // }\n\n // if (matched) return true;\n\n // if (isParent(node)) {\n // return node.children.length > 0;\n // }\n\n // return false;\n // }\n\n // const keepRoot = prune(cloned);\n\n // if (!keepRoot && isParent(cloned)) {\n // cloned.children = [];\n // }\n\n // return cloned;\n // }\n\n /**\n * Builds a minimal subtree that keeps only nodes matching the test and their parent chain.\n * It is a universal travel algoritim works with any AST like mdast, hast, esast and others\n */\n function buildFilteredTree(root: Node, test: Test): Node {\n const cloned = structuredClone(root);\n\n function prune(node: Node): boolean {\n const matched = is(node, test);\n\n let hasChildMatch = false;\n\n for (const key in node) {\n if (key === \"position\") continue;\n\n const value = node[key];\n\n if (!value) continue;\n\n if (isNodeArray(value)) {\n let containsNode = false;\n\n for (let i = value.length - 1; i >= 0; i--) {\n const item = value[i];\n\n /* v8 ignore next -- @preserve */\n if (isNode(item)) {\n containsNode = true;\n\n const keep = prune(item);\n\n if (!keep) {\n value.splice(i, 1);\n } else {\n hasChildMatch = true;\n }\n }\n }\n\n if (containsNode && value.length === 0) {\n node[key] = [];\n }\n } else if (isNode(value)) {\n const keep = prune(value);\n\n if (!keep) {\n delete node[key];\n } else {\n hasChildMatch = true;\n }\n }\n }\n\n if (matched && settings.preserveSubtree !== false) {\n return true; // don't touch subtree\n }\n\n if (matched) return true;\n\n return hasChildMatch;\n }\n\n prune(cloned);\n return cloned;\n }\n\n return function transformer(tree: Node) {\n const targetTree = settings.test != null ? buildFilteredTree(tree, settings.test) : tree;\n\n if (settings.label) {\n console.log(`[unist-log-tree] ${settings.label}`);\n }\n\n const output: Node = JSON.parse(\n JSON.stringify(targetTree, (key: string, value: unknown) => {\n if (!settings.preservePositions && key === \"position\") {\n return undefined;\n }\n return value;\n }),\n );\n\n console.dir(output, { depth: settings.depth });\n };\n };\n}\n"]}
@@ -0,0 +1 @@
1
+ {"root":["../src/index.ts"],"version":"5.9.3"}
package/package.json ADDED
@@ -0,0 +1,92 @@
1
+ {
2
+ "name": "unist-plugin-log-tree",
3
+ "version": "1.0.1",
4
+ "description": "A debugging plugin for the unified ecosystem that logs unist syntax trees without transforming.",
5
+ "type": "module",
6
+ "main": "./dist/index.js",
7
+ "types": "./dist/index.d.ts",
8
+ "exports": {
9
+ ".": {
10
+ "types": "./dist/index.d.ts",
11
+ "import": "./dist/index.js",
12
+ "default": "./dist/index.js"
13
+ }
14
+ },
15
+ "scripts": {
16
+ "build": "rimraf dist && tsc --build && type-coverage",
17
+ "format": "npm run prettier && npm run lint",
18
+ "prettier": "prettier --write .",
19
+ "lint": "eslint .",
20
+ "test": "vitest run",
21
+ "test:watch": "vitest",
22
+ "test:file": "vitest test.plugin.spec.ts",
23
+ "test-coverage": "vitest run --coverage",
24
+ "prepack": "npm run build",
25
+ "prepublishOnly": "npm run format && npm run test-coverage"
26
+ },
27
+ "files": [
28
+ "dist/",
29
+ "LICENSE",
30
+ "README.md"
31
+ ],
32
+ "repository": {
33
+ "type": "git",
34
+ "url": "git+https://github.com/ipikuka/unist-plugin-log-tree.git"
35
+ },
36
+ "keywords": [
37
+ "unified",
38
+ "mdast",
39
+ "markdown",
40
+ "MDX",
41
+ "remark",
42
+ "plugin",
43
+ "remark plugin",
44
+ "remark marker",
45
+ "remark markers",
46
+ "remark flexible markers"
47
+ ],
48
+ "author": "ipikuka <talatkuyuk@gmail.com>",
49
+ "license": "MIT",
50
+ "homepage": "https://github.com/ipikuka/unist-plugin-log-tree#readme",
51
+ "bugs": {
52
+ "url": "https://github.com/ipikuka/unist-plugin-log-tree/issues"
53
+ },
54
+ "devDependencies": {
55
+ "@eslint/js": "^10.0.1",
56
+ "@types/node": "^24.10.13",
57
+ "@vitest/coverage-v8": "^4.0.18",
58
+ "@vitest/eslint-plugin": "^1.6.9",
59
+ "dedent": "^1.7.1",
60
+ "eslint": "^10.0.0",
61
+ "eslint-config-prettier": "^10.1.8",
62
+ "eslint-plugin-prettier": "^5.5.5",
63
+ "globals": "^17.3.0",
64
+ "prettier": "^3.8.1",
65
+ "rimraf": "^6.1.3",
66
+ "type-coverage": "^2.29.7",
67
+ "typescript": "^5.9.3",
68
+ "typescript-eslint": "^8.56.0",
69
+ "unified": "^11.0.5",
70
+ "vitest": "^4.0.18"
71
+ },
72
+ "dependencies": {
73
+ "@types/mdast": "^4.0.4",
74
+ "unist-builder": "^4.0.0",
75
+ "unist-util-find-after": "^5.0.0",
76
+ "unist-util-find-all-after": "^5.0.0",
77
+ "unist-util-find-all-before": "^5.0.0",
78
+ "unist-util-find-between-all": "^1.1.6",
79
+ "unist-util-visit": "^5.1.0"
80
+ },
81
+ "peerDependencies": {
82
+ "unified": "^11"
83
+ },
84
+ "sideEffects": false,
85
+ "typeCoverage": {
86
+ "atLeast": 100,
87
+ "detail": true,
88
+ "ignoreAsAssertion": true,
89
+ "ignoreCatch": true,
90
+ "strict": true
91
+ }
92
+ }