@md-plugins/shared 0.1.0-alpha.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.md ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2024-present, Jeff Galbraith
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
13
+ all 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
21
+ THE SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,103 @@
1
+ # @md-plugins/shared
2
+
3
+ The `@md-plugins/shared` package provides common utilities, types, and helpers used across various Markdown-It plugins in the `@md-plugins` ecosystem. It serves as a foundational package to ensure consistency and reduce code duplication across the plugins.
4
+
5
+ ## Features
6
+
7
+ - Shared TypeScript types for plugin environments.
8
+ - Common utility functions for Markdown-It processing.
9
+ - Centralized definitions for easier maintenance and reusability.
10
+ - Lightweight and dependency-free.
11
+
12
+ ## Installation
13
+
14
+ Install the plugin via your preferred package manager:
15
+
16
+ ```bash
17
+ # With npm:
18
+ npm install @md-plugins/shared
19
+ # Or with Yarn:
20
+ yarn add @md-plugins/shared
21
+ # Or with pnpm:
22
+ pnpm add @md-plugins/shared
23
+ ```
24
+
25
+ ## Usage
26
+
27
+ The `@md-plugins/shared` package is not intended to be used directly by end-users but as a dependency for other `@md-plugins` packages. However, if you’re developing a custom plugin or extending existing functionality, you can import and use the utilities provided.
28
+
29
+ ## Example: Accessing Types
30
+
31
+ ```ts
32
+ import type { MarkdownItEnv } from '@md-plugins/shared';
33
+
34
+ const env: MarkdownItEnv = {
35
+ toc: [],
36
+ frontmatter: {},
37
+ };
38
+ ```
39
+
40
+ ## Example: Utility Function
41
+
42
+ ```ts
43
+ import { resolveTitleFromToken } from '@md-plugins/shared';
44
+
45
+ const token = { content: 'My Title' };
46
+ const title = resolveTitleFromToken(token, {
47
+ shouldAllowHtml: false,
48
+ shouldEscapeText: true,
49
+ });
50
+
51
+ console.log(title); // "My Title"
52
+ ```
53
+
54
+ ## Provided Types
55
+
56
+ The `shared` package defines common types used across plugins. Here are some examples:
57
+
58
+ ### `MarkdownItEnv`
59
+
60
+ ```ts
61
+ export interface MarkdownItEnv {
62
+ toc?: Array<Record<string, any>>; // Extracted table of contents
63
+ frontmatter?: Record<string, unknown>; // Frontmatter data
64
+ pageScripts?: Set<string>; // Scripts to be included in the page
65
+ content?: string; // Markdown content excluding frontmatter
66
+ title?: string; // Extracted title
67
+ }
68
+ ```
69
+
70
+ This type allows consistent management of the Markdown-It environment.
71
+
72
+ ## Utility Functions
73
+
74
+ ### `resolveTitleFromToken`
75
+
76
+ A utility function to resolve the title from a Markdown-It token.
77
+
78
+ ```ts
79
+ function resolveTitleFromToken(
80
+ token: Token,
81
+ options: { shouldAllowHtml: boolean; shouldEscapeText: boolean }
82
+ ): string;
83
+ ```
84
+
85
+ - Parameters:
86
+ - token: The Markdown-It token to extract the title from.
87
+ - options: Configuration for allowing HTML or escaping text.
88
+ - Returns: The resolved title as a string
89
+
90
+ ### `slugify`
91
+
92
+ Provides a standard implementation of slugification for plugins:
93
+
94
+ ```ts
95
+ function slugify(str: string): string;
96
+ ```
97
+
98
+ - Converts a string into a URL-friendly slug.
99
+ - Removes special characters and replaces spaces with hyphens.
100
+
101
+ ## License
102
+
103
+ This package is licensed under the MIT License. See the [LICENSE](./LICENSE) file for details.
@@ -0,0 +1,100 @@
1
+ import Token from 'markdown-it/lib/token.mjs';
2
+
3
+ /**
4
+ * Escape html chars
5
+ */
6
+ declare const htmlEscape: (str: string) => string;
7
+
8
+ /**
9
+ * Unescape html chars
10
+ */
11
+ declare const htmlUnescape: (str: string) => string;
12
+
13
+ interface MarkdownItEnv {
14
+ plugins?: Record<string, unknown>;
15
+ }
16
+ interface MarkdownItHeader {
17
+ /**
18
+ * The slug of the header
19
+ *
20
+ * Typically the `id` attr of the header anchor
21
+ */
22
+ id: string;
23
+ /**
24
+ * The level of the header
25
+ *
26
+ * `1` to `6` for `<h1>` to `<h6>`
27
+ */
28
+ level: number;
29
+ /**
30
+ * The title of the header
31
+ */
32
+ title: string;
33
+ /**
34
+ * Link of the header
35
+ *
36
+ * Typically using `#${slug}` as the anchor hash
37
+ */
38
+ link: string;
39
+ /**
40
+ * The children of the header
41
+ */
42
+ children: MarkdownItHeader[];
43
+ }
44
+
45
+ interface ResolveTitleOptions {
46
+ /**
47
+ * Should allow inline HTML tags or not.
48
+ *
49
+ * If the result is going to be used as Vue template, it should allow inline
50
+ * HTML tags so that Vue custom components would be kept.
51
+ */
52
+ shouldAllowHtml: boolean;
53
+ /**
54
+ * Should escape the text content or not.
55
+ *
56
+ * If the result is going to be used in HTML directly, it should be escaped
57
+ * so that the text content won't be wrongly treated as HTML tags.
58
+ */
59
+ shouldEscapeText: boolean;
60
+ }
61
+ /**
62
+ * Resolve header title from markdown-it token
63
+ *
64
+ * Typically using the next token of `heading_open` token
65
+ */
66
+ declare const resolveTitleFromToken: (token: Token, { shouldAllowHtml, shouldEscapeText }: ResolveTitleOptions) => string;
67
+
68
+ interface ResolveHeadersOptions extends ResolveTitleOptions {
69
+ /**
70
+ * Heading level that going to be resolved
71
+ */
72
+ level: number[];
73
+ /**
74
+ * Should allow headers inside nested blocks or not
75
+ *
76
+ * If set to `true`, headers inside blockquote, list, etc. would also be resolved.
77
+ */
78
+ shouldAllowNested: boolean;
79
+ /**
80
+ * A custom slugification function
81
+ *
82
+ * Would be ignored if the `id` attr of the token is set.
83
+ */
84
+ slugify?: (str: string) => string;
85
+ /**
86
+ * A function for formatting headings
87
+ */
88
+ format?: (str: string) => string | undefined;
89
+ }
90
+ /**
91
+ * Resolve headers from markdown-it tokens
92
+ */
93
+ declare const resolveHeadersFromTokens: (tokens: Token[], { level, shouldAllowHtml, shouldAllowNested, shouldEscapeText, slugify, format, }?: Partial<ResolveHeadersOptions>) => MarkdownItHeader[];
94
+
95
+ /**
96
+ * Default slugification function
97
+ */
98
+ declare const slugify: (str: string) => string;
99
+
100
+ export { type MarkdownItEnv, type MarkdownItHeader, type ResolveHeadersOptions, type ResolveTitleOptions, htmlEscape, htmlUnescape, resolveHeadersFromTokens, resolveTitleFromToken, slugify };
@@ -0,0 +1,100 @@
1
+ import Token from 'markdown-it/lib/token.mjs';
2
+
3
+ /**
4
+ * Escape html chars
5
+ */
6
+ declare const htmlEscape: (str: string) => string;
7
+
8
+ /**
9
+ * Unescape html chars
10
+ */
11
+ declare const htmlUnescape: (str: string) => string;
12
+
13
+ interface MarkdownItEnv {
14
+ plugins?: Record<string, unknown>;
15
+ }
16
+ interface MarkdownItHeader {
17
+ /**
18
+ * The slug of the header
19
+ *
20
+ * Typically the `id` attr of the header anchor
21
+ */
22
+ id: string;
23
+ /**
24
+ * The level of the header
25
+ *
26
+ * `1` to `6` for `<h1>` to `<h6>`
27
+ */
28
+ level: number;
29
+ /**
30
+ * The title of the header
31
+ */
32
+ title: string;
33
+ /**
34
+ * Link of the header
35
+ *
36
+ * Typically using `#${slug}` as the anchor hash
37
+ */
38
+ link: string;
39
+ /**
40
+ * The children of the header
41
+ */
42
+ children: MarkdownItHeader[];
43
+ }
44
+
45
+ interface ResolveTitleOptions {
46
+ /**
47
+ * Should allow inline HTML tags or not.
48
+ *
49
+ * If the result is going to be used as Vue template, it should allow inline
50
+ * HTML tags so that Vue custom components would be kept.
51
+ */
52
+ shouldAllowHtml: boolean;
53
+ /**
54
+ * Should escape the text content or not.
55
+ *
56
+ * If the result is going to be used in HTML directly, it should be escaped
57
+ * so that the text content won't be wrongly treated as HTML tags.
58
+ */
59
+ shouldEscapeText: boolean;
60
+ }
61
+ /**
62
+ * Resolve header title from markdown-it token
63
+ *
64
+ * Typically using the next token of `heading_open` token
65
+ */
66
+ declare const resolveTitleFromToken: (token: Token, { shouldAllowHtml, shouldEscapeText }: ResolveTitleOptions) => string;
67
+
68
+ interface ResolveHeadersOptions extends ResolveTitleOptions {
69
+ /**
70
+ * Heading level that going to be resolved
71
+ */
72
+ level: number[];
73
+ /**
74
+ * Should allow headers inside nested blocks or not
75
+ *
76
+ * If set to `true`, headers inside blockquote, list, etc. would also be resolved.
77
+ */
78
+ shouldAllowNested: boolean;
79
+ /**
80
+ * A custom slugification function
81
+ *
82
+ * Would be ignored if the `id` attr of the token is set.
83
+ */
84
+ slugify?: (str: string) => string;
85
+ /**
86
+ * A function for formatting headings
87
+ */
88
+ format?: (str: string) => string | undefined;
89
+ }
90
+ /**
91
+ * Resolve headers from markdown-it tokens
92
+ */
93
+ declare const resolveHeadersFromTokens: (tokens: Token[], { level, shouldAllowHtml, shouldAllowNested, shouldEscapeText, slugify, format, }?: Partial<ResolveHeadersOptions>) => MarkdownItHeader[];
94
+
95
+ /**
96
+ * Default slugification function
97
+ */
98
+ declare const slugify: (str: string) => string;
99
+
100
+ export { type MarkdownItEnv, type MarkdownItHeader, type ResolveHeadersOptions, type ResolveTitleOptions, htmlEscape, htmlUnescape, resolveHeadersFromTokens, resolveTitleFromToken, slugify };
package/dist/index.mjs ADDED
@@ -0,0 +1,96 @@
1
+ const htmlEscapeMap = {
2
+ "&": "&amp;",
3
+ "<": "&lt;",
4
+ ">": "&gt;",
5
+ "'": "&#39;",
6
+ '"': "&quot;"
7
+ };
8
+ const htmlEscapeRegexp = /[&<>'"]/g;
9
+ const htmlEscape = (str) => str.replace(htmlEscapeRegexp, (char) => htmlEscapeMap[char]);
10
+
11
+ const htmlUnescapeMap = {
12
+ "&amp;": "&",
13
+ "&#38;": "&",
14
+ "&lt;": "<",
15
+ "&#60;": "<",
16
+ "&gt;": ">",
17
+ "&#62;": ">",
18
+ "&apos;": "'",
19
+ "&#39;": "'",
20
+ "&quot;": '"',
21
+ "&#34;": '"'
22
+ };
23
+ const htmlUnescapeRegexp = /&(amp|#38|lt|#60|gt|#62|apos|#39|quot|#34);/g;
24
+ const htmlUnescape = (str) => str.replace(htmlUnescapeRegexp, (char) => htmlUnescapeMap[char]);
25
+
26
+ const resolveTitleFromToken = (token, { shouldAllowHtml, shouldEscapeText }) => {
27
+ const children = token.children ?? [];
28
+ const titleTokenTypes = ["text", "emoji", "code_inline"];
29
+ if (shouldAllowHtml) {
30
+ titleTokenTypes.push("html_inline");
31
+ }
32
+ const titleTokens = children.filter(
33
+ (item) => titleTokenTypes.includes(item.type) && // filter permalink symbol that generated by markdown-it-anchor
34
+ !item.meta?.isPermalinkSymbol
35
+ );
36
+ return titleTokens.reduce((result, item) => {
37
+ if (shouldEscapeText) {
38
+ if (item.type === "code_inline" || item.type === "text") {
39
+ return `${result}${htmlEscape(item.content)}`;
40
+ }
41
+ }
42
+ return `${result}${item.content}`;
43
+ }, "").trim();
44
+ };
45
+
46
+ const rControl = /[\u0000-\u001f]/g;
47
+ const rSpecial = /[\s~`!@#$%^&*()\-_+=[\]{}|\\;:"'“”‘’<>,.?/]+/g;
48
+ const rCombining = /[\u0300-\u036F]/g;
49
+ const andRE = /&/g;
50
+ const slugify = (str) => str.normalize("NFKD").toLowerCase().replace(andRE, "-and-").replace(rCombining, "").replace(rControl, "-").replace(rSpecial, "-").replace(/[^a-z0-9-]+/g, "").replace(/-{2,}/g, "-").replace(/^-+|-+$/g, "").replace(/^(\d)/, "_$1");
51
+
52
+ const resolveHeadersFromTokens = (tokens, {
53
+ level = [1, 2, 3],
54
+ shouldAllowHtml = false,
55
+ shouldAllowNested = false,
56
+ shouldEscapeText = false,
57
+ slugify: slugify$1 = slugify,
58
+ format = (str) => str
59
+ } = {}) => {
60
+ const headers = [];
61
+ const stack = [];
62
+ const pushHeader = (header) => {
63
+ while (stack.length > 0 && header.level <= stack[0].level) {
64
+ stack.shift();
65
+ }
66
+ if (stack.length === 0) {
67
+ headers.push(header);
68
+ } else {
69
+ stack[0].children.push(header);
70
+ }
71
+ stack.unshift(header);
72
+ };
73
+ tokens.forEach((token, i) => {
74
+ if (token.type !== "heading_open") return;
75
+ if (token.level !== 0 && !shouldAllowNested) return;
76
+ const headerLevel = Number.parseInt(token.tag.slice(1), 10);
77
+ if (!level.includes(headerLevel)) return;
78
+ const nextToken = tokens[i + 1];
79
+ if (!nextToken) return;
80
+ const title = resolveTitleFromToken(nextToken, {
81
+ shouldAllowHtml,
82
+ shouldEscapeText
83
+ });
84
+ const slug = token.attrGet("id") ?? slugify$1(title);
85
+ pushHeader({
86
+ level: headerLevel,
87
+ title: format(title) ?? title,
88
+ id: slug,
89
+ link: `#${slug}`,
90
+ children: []
91
+ });
92
+ });
93
+ return headers;
94
+ };
95
+
96
+ export { htmlEscape, htmlUnescape, resolveHeadersFromTokens, resolveTitleFromToken, slugify };
package/package.json ADDED
@@ -0,0 +1,47 @@
1
+ {
2
+ "name": "@md-plugins/shared",
3
+ "version": "0.1.0-alpha.1",
4
+ "description": "Shared functions and utilities for md-plugins.",
5
+ "keywords": [
6
+ "markdown-it",
7
+ "quasarframework",
8
+ "vue",
9
+ "utils"
10
+ ],
11
+ "homepage": "https://github.com/md-plugins",
12
+ "bugs": {
13
+ "url": "https://github.com/md-plugins/md-plugins/issues"
14
+ },
15
+ "repository": {
16
+ "type": "git",
17
+ "url": "git+https://github.com/md-plugins/md-plugins.git"
18
+ },
19
+ "license": "MIT",
20
+ "author": "hawkeye64 <galbraith64@gmail.com>",
21
+ "type": "module",
22
+ "exports": {
23
+ ".": {
24
+ "import": {
25
+ "types": "./dist/index.d.mts",
26
+ "default": "./dist/index.mjs"
27
+ }
28
+ }
29
+ },
30
+ "module": "./dist/index.mjs",
31
+ "types": "./dist/index.d.ts",
32
+ "files": [
33
+ "./dist"
34
+ ],
35
+ "dependencies": {
36
+ "@types/markdown-it": "^14.1.2",
37
+ "markdown-it": "^14.1.0"
38
+ },
39
+ "publishConfig": {
40
+ "access": "public"
41
+ },
42
+ "scripts": {
43
+ "build": "unbuild",
44
+ "clean": "rm -rf dist",
45
+ "test": "vitest"
46
+ }
47
+ }