@markedjs/testutils 9.0.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/.eslintrc.cjs ADDED
@@ -0,0 +1,11 @@
1
+ module.exports = {
2
+ env: {
3
+ node: true,
4
+ es2021: true,
5
+ },
6
+ extends: "eslint:recommended",
7
+ parserOptions: {
8
+ ecmaVersion: "latest",
9
+ sourceType: "module",
10
+ },
11
+ };
@@ -0,0 +1,11 @@
1
+ version: 2
2
+ updates:
3
+ - package-ecosystem: "github-actions"
4
+ directory: "/"
5
+ schedule:
6
+ interval: "weekly"
7
+ - package-ecosystem: "npm"
8
+ versioning-strategy: "increase"
9
+ directory: "/"
10
+ schedule:
11
+ interval: "weekly"
@@ -0,0 +1,42 @@
1
+ name: "Automerge"
2
+ on:
3
+ workflow_run:
4
+ workflows:
5
+ - CI
6
+ types:
7
+ - completed
8
+
9
+ jobs:
10
+ Automerge:
11
+ runs-on: ubuntu-latest
12
+ if: |
13
+ github.event.workflow_run.event == 'pull_request' &&
14
+ github.event.workflow_run.conclusion == 'success'
15
+ steps:
16
+ - name: "Merge PR"
17
+ uses: actions/github-script@v6
18
+ with:
19
+ github-token: ${{ secrets.GITHUB_TOKEN }}
20
+ script: |
21
+ const pr = await github.rest.pulls.get({
22
+ owner: context.repo.owner,
23
+ repo: context.repo.repo,
24
+ pull_number: context.payload.workflow_run.pull_requests[0].number,
25
+ });
26
+ if (!pr.data.title.includes('marked')) {
27
+ console.log('Not Merged 🚫');
28
+ console.log(`Must update marked-repo as well`);
29
+ } else if (!pr.data.title.startsWith('chore(deps-dev):')) {
30
+ console.log('Not Merged 🚫');
31
+ console.log(`Title '${pr.data.title}' does not start with 'chore(deps-dev):'`);
32
+ } else if (pr.data.user.login !== 'dependabot[bot]') {
33
+ console.log('Not Merged 🚫');
34
+ console.log(`User '${pr.data.user.login}' does not equal 'dependabot[bot]'`);
35
+ } else {
36
+ await github.rest.pulls.merge({
37
+ owner: context.repo.owner,
38
+ repo: context.repo.repo,
39
+ pull_number: context.payload.workflow_run.pull_requests[0].number,
40
+ });
41
+ console.log('Merged 🎉');
42
+ }
@@ -0,0 +1,78 @@
1
+ name: "Tests"
2
+ on:
3
+ pull_request:
4
+ push:
5
+ branches:
6
+ - main
7
+
8
+ permissions:
9
+ contents: read
10
+
11
+ jobs:
12
+ Test:
13
+ strategy:
14
+ matrix:
15
+ node_version: ["lts/*", "*"]
16
+ runs-on: ubuntu-latest
17
+ steps:
18
+ - name: Checkout Code
19
+ uses: actions/checkout@v4
20
+ - name: Install Node
21
+ uses: actions/setup-node@v3
22
+ with:
23
+ node-version: ${{ matrix.node_version }}
24
+ check-latest: true
25
+ - name: Install Dependencies
26
+ run: npm ci
27
+ - name: Test 👩🏽‍💻
28
+ run: npm run test
29
+
30
+ Lint:
31
+ runs-on: ubuntu-latest
32
+ steps:
33
+ - name: Checkout Code
34
+ uses: actions/checkout@v4
35
+ - name: Install Node
36
+ uses: actions/setup-node@v3
37
+ with:
38
+ node-version: "lts/*"
39
+ - name: Install Dependencies
40
+ run: npm ci
41
+ - name: Lint ✨
42
+ run: npm run test:lint
43
+
44
+ Format:
45
+ runs-on: ubuntu-latest
46
+ steps:
47
+ - name: Checkout Code
48
+ uses: actions/checkout@v4
49
+ - name: Install Node
50
+ uses: actions/setup-node@v3
51
+ with:
52
+ node-version: "lts/*"
53
+ - name: Install Dependencies
54
+ run: npm ci
55
+ - name: Format 💖
56
+ run: npm run test:format
57
+
58
+ Release:
59
+ # This will only work if the version in package.json is updated
60
+ needs: [Test, Lint, Format]
61
+ if: |
62
+ github.ref == 'refs/heads/main' &&
63
+ github.event.repository.fork == false
64
+ runs-on: ubuntu-latest
65
+ steps:
66
+ - name: Checkout Code
67
+ uses: actions/checkout@v4
68
+ - name: Install Node
69
+ uses: actions/setup-node@v3
70
+ with:
71
+ node-version: "lts/*"
72
+ registry-url: https://registry.npmjs.org/
73
+ - name: Install Dependencies
74
+ run: npm ci
75
+ - name: Publish 📝
76
+ run: npm publish
77
+ env:
78
+ NODE_AUTH_TOKEN: ${{secrets.NPM_TOKEN}}
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2023 Marked
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,3 @@
1
+ # @markedjs/testutils
2
+
3
+ Test utilities for marked and marked extensions
package/package.json ADDED
@@ -0,0 +1,34 @@
1
+ {
2
+ "name": "@markedjs/testutils",
3
+ "version": "9.0.3",
4
+ "description": "Test utilities for marked and marked extensions",
5
+ "main": "src/index.js",
6
+ "type": "module",
7
+ "scripts": {
8
+ "test": "node --test",
9
+ "test:lint": "eslint .",
10
+ "test:format": "prettier . --check",
11
+ "lint": "eslint . --fix",
12
+ "format": "prettier . --write"
13
+ },
14
+ "repository": {
15
+ "type": "git",
16
+ "url": "git+https://github.com/markedjs/testutils.git"
17
+ },
18
+ "author": "",
19
+ "license": "MIT",
20
+ "bugs": {
21
+ "url": "https://github.com/markedjs/testutils/issues"
22
+ },
23
+ "homepage": "https://github.com/markedjs/testutils#readme",
24
+ "dependencies": {
25
+ "@markedjs/html-differ": "^4.0.2",
26
+ "front-matter": "^4.0.2",
27
+ "marked": "^9.0.3",
28
+ "marked-repo": "https://github.com/markedjs/marked/tarball/v9.0.3"
29
+ },
30
+ "devDependencies": {
31
+ "eslint": "^8.50.0",
32
+ "prettier": "^3.0.3"
33
+ }
34
+ }
@@ -0,0 +1,33 @@
1
+ import { loadTests } from "./load-tests.js";
2
+ import { resolvePath } from "./helpers.js";
3
+
4
+ export async function getTests(dirs) {
5
+ if (typeof dirs === "string") {
6
+ return await loadTests(dirs);
7
+ }
8
+
9
+ if (Array.isArray(dirs)) {
10
+ return await Promise.all(dirs.map((dir) => loadTests(dir)));
11
+ }
12
+
13
+ const keys = Object.keys(dirs);
14
+ const tests = await Promise.all(keys.map((key) => loadTests(dirs[key])));
15
+ const testsObj = {};
16
+ for (let i = 0; i < keys.length; i++) {
17
+ testsObj[keys[i]] = tests[i];
18
+ }
19
+
20
+ return testsObj;
21
+ }
22
+
23
+ export async function getAllMarkedSpecTests() {
24
+ return await getTests({
25
+ CommonMark: resolvePath(
26
+ "../node_modules/marked-repo/test/specs/commonmark",
27
+ ),
28
+ GFM: resolvePath("../node_modules/marked-repo/test/specs/gfm"),
29
+ New: resolvePath("../node_modules/marked-repo/test/specs/new"),
30
+ Original: resolvePath("../node_modules/marked-repo/test/specs/original"),
31
+ RedDOS: resolvePath("../node_modules/marked-repo/test/specs/redos"),
32
+ });
33
+ }
package/src/helpers.js ADDED
@@ -0,0 +1,8 @@
1
+ import { resolve, dirname } from "node:path";
2
+ import { fileURLToPath } from "node:url";
3
+
4
+ const __dirname = dirname(fileURLToPath(import.meta.url));
5
+
6
+ export function resolvePath(p) {
7
+ return resolve(__dirname, p);
8
+ }
@@ -0,0 +1,48 @@
1
+ import { HtmlDiffer } from "@markedjs/html-differ";
2
+
3
+ const htmlDiffer = new HtmlDiffer({
4
+ ignoreSelfClosingSlash: true,
5
+ ignoreComments: false,
6
+ });
7
+
8
+ export const htmlIsEqual = htmlDiffer.isEqual.bind(htmlDiffer);
9
+ export async function firstDiff(actual, expected, padding) {
10
+ padding = padding || 30;
11
+ const diffHtml = await htmlDiffer.diffHtml(actual, expected);
12
+ const result = diffHtml.reduce(
13
+ (obj, diff) => {
14
+ if (diff.added) {
15
+ if (obj.firstIndex === null) {
16
+ obj.firstIndex = obj.expected.length;
17
+ }
18
+ obj.expected += diff.value;
19
+ } else if (diff.removed) {
20
+ if (obj.firstIndex === null) {
21
+ obj.firstIndex = obj.actual.length;
22
+ }
23
+ obj.actual += diff.value;
24
+ } else {
25
+ obj.actual += diff.value;
26
+ obj.expected += diff.value;
27
+ }
28
+
29
+ return obj;
30
+ },
31
+ {
32
+ firstIndex: null,
33
+ actual: "",
34
+ expected: "",
35
+ },
36
+ );
37
+
38
+ return {
39
+ actual: result.actual.substring(
40
+ result.firstIndex - padding,
41
+ result.firstIndex + padding,
42
+ ),
43
+ expected: result.expected.substring(
44
+ result.firstIndex - padding,
45
+ result.firstIndex + padding,
46
+ ),
47
+ };
48
+ }
package/src/index.js ADDED
@@ -0,0 +1,4 @@
1
+ export * from "./get-tests.js";
2
+ export * from "./html-differ.js";
3
+ export * from "./output-table.js";
4
+ export * from "./run-tests.js";
@@ -0,0 +1,81 @@
1
+ import fs from "node:fs";
2
+ import path from "node:path";
3
+ import fm from "front-matter";
4
+ import { createRequire } from "node:module";
5
+
6
+ const require = createRequire(import.meta.url);
7
+
8
+ export async function loadTests(fileOrDir) {
9
+ const isFile = fs.statSync(fileOrDir).isFile();
10
+ const files = isFile ? [path.basename(fileOrDir)] : fs.readdirSync(fileOrDir);
11
+ const dir = isFile ? path.dirname(fileOrDir) : fileOrDir;
12
+
13
+ const obj = {};
14
+
15
+ for (const file of files) {
16
+ const ext = path.extname(file);
17
+ const name = path.basename(file, ext);
18
+ const absFile = path.join(dir, file);
19
+ let specs = [];
20
+
21
+ switch (ext) {
22
+ case ".md": {
23
+ const content = fm(fs.readFileSync(absFile, "utf8"));
24
+ const skip = content.attributes.skip;
25
+ delete content.attributes.skip;
26
+ const only = content.attributes.only;
27
+ delete content.attributes.only;
28
+ specs.push({
29
+ section: name,
30
+ markdown: content.body,
31
+ html: fs.readFileSync(absFile.replace(/[^.]+$/, "html"), "utf8"),
32
+ options: content.attributes,
33
+ only,
34
+ skip,
35
+ });
36
+ break;
37
+ }
38
+ case ".js":
39
+ case ".mjs":
40
+ case ".cjs":
41
+ case ".json": {
42
+ let json;
43
+ try {
44
+ // try require first
45
+ json = await require(absFile);
46
+ } catch (err) {
47
+ if (err.code !== "ERR_REQUIRE_ESM") {
48
+ throw err;
49
+ }
50
+ // must import esm
51
+ json = await import(absFile);
52
+ }
53
+ specs = specs.concat(json);
54
+ break;
55
+ }
56
+ default:
57
+ // do nothing
58
+ }
59
+
60
+ for (let i = 0; i < specs.length; i++) {
61
+ const spec = specs[i];
62
+ if (!spec.section) {
63
+ spec.section = `${name}[${i}]`;
64
+ }
65
+
66
+ if (!obj[spec.section]) {
67
+ obj[spec.section] = {
68
+ total: 0,
69
+ pass: 0,
70
+ specs: [],
71
+ };
72
+ }
73
+
74
+ obj[spec.section].total++;
75
+ obj[spec.section].pass += spec.shouldFail ? 0 : 1;
76
+ obj[spec.section].specs.push(spec);
77
+ }
78
+ }
79
+
80
+ return obj;
81
+ }
@@ -0,0 +1,34 @@
1
+ export function outputCompletionTable(title, tests) {
2
+ let longestName = 0;
3
+ let maxTests = 0;
4
+
5
+ for (const section in tests) {
6
+ longestName = Math.max(section.length, longestName);
7
+ maxTests = Math.max(tests[section].total, maxTests);
8
+ }
9
+
10
+ const maxTestsLen = ("" + maxTests).length;
11
+ const spaces = maxTestsLen * 2 + longestName + 11;
12
+
13
+ console.log("-".padEnd(spaces + 4, "-"));
14
+ console.log(
15
+ `| ${title
16
+ .padStart(Math.ceil((spaces + title.length) / 2))
17
+ .padEnd(spaces)} |`,
18
+ );
19
+ console.log(`| ${" ".padEnd(spaces)} |`);
20
+ for (const section in tests) {
21
+ console.log(
22
+ `| ${section.padEnd(longestName)} ${("" + tests[section].pass).padStart(
23
+ maxTestsLen,
24
+ )} of ${("" + tests[section].total).padStart(maxTestsLen)} ${(
25
+ (100 * tests[section].pass) /
26
+ tests[section].total
27
+ )
28
+ .toFixed()
29
+ .padStart(4)}% |`,
30
+ );
31
+ }
32
+ console.log("-".padEnd(spaces + 4, "-"));
33
+ console.log();
34
+ }
@@ -0,0 +1,123 @@
1
+ import { htmlIsEqual, firstDiff } from "./html-differ.js";
2
+ import { getTests, getAllMarkedSpecTests } from "./get-tests.js";
3
+ import nodeTest from "node:test";
4
+ import assert from "node:assert";
5
+ import { Marked } from "marked";
6
+ import { outputCompletionTable } from "./output-table.js";
7
+
8
+ export async function runTests({
9
+ tests = {},
10
+ defaultMarkedOptions = {},
11
+ parse = parseMarked,
12
+ addExtension = () => {},
13
+ isEqual = htmlIsEqual,
14
+ diff = firstDiff,
15
+ } = {}) {
16
+ if (typeof tests === "string") {
17
+ tests = getTests(tests);
18
+ }
19
+
20
+ for (const section of Object.keys(tests)) {
21
+ await nodeTest(section, async (t) => {
22
+ for (const test of tests[section].specs) {
23
+ const options = {
24
+ ...defaultMarkedOptions,
25
+ ...(test.options || {}),
26
+ };
27
+ const example = test.example ? " example " + test.example : "";
28
+ const passFail = test.shouldFail ? "fail" : "pass";
29
+
30
+ if (typeof options.silent === "undefined") {
31
+ options.silent = true;
32
+ }
33
+
34
+ await t.test(
35
+ `${section} should ${passFail}${example}`,
36
+ {
37
+ only: test.only,
38
+ skip: test.skip,
39
+ },
40
+ async () => {
41
+ const before = process.hrtime();
42
+ let parsed = parse(test.markdown, options, addExtension);
43
+ if (options.async) {
44
+ parsed = await parsed;
45
+ }
46
+ const elapsed = process.hrtime(before);
47
+ const pass = await isEqual(parsed, test.html);
48
+ if (test.shouldFail) {
49
+ assert.ok(
50
+ !pass,
51
+ `${test.markdown}\n------\n\nExpected: Should Fail`,
52
+ );
53
+ } else if (options.renderExact) {
54
+ assert.strictEqual(test.html, parsed);
55
+ } else {
56
+ const testDiff = await diff(parsed, test.html);
57
+ assert(
58
+ pass,
59
+ `Expected: ${testDiff.expected}\n Actual: ${testDiff.actual}`,
60
+ );
61
+ }
62
+
63
+ if (!options.async && elapsed[0] > 0) {
64
+ const s = (elapsed[0] + elapsed[1] * 1e-9).toFixed(3);
65
+ assert.fail(`took too long: ${s}s`);
66
+ }
67
+ },
68
+ );
69
+ }
70
+ });
71
+ }
72
+ }
73
+
74
+ export async function runAllMarkedSpecTests({
75
+ addExtension = () => {},
76
+ outputCompletionTables = true,
77
+ } = {}) {
78
+ const specTests = await getAllMarkedSpecTests();
79
+
80
+ await Promise.all(
81
+ Object.keys(specTests).map((title) => {
82
+ const tests = specTests[title];
83
+ switch (title) {
84
+ case "CommonMark":
85
+ if (outputCompletionTables) {
86
+ outputCompletionTable(title, tests);
87
+ }
88
+ return runTests({
89
+ tests,
90
+ defaultMarkedOptions: { gfm: false, pedantic: false },
91
+ addExtension,
92
+ });
93
+ case "GFM":
94
+ if (outputCompletionTables) {
95
+ outputCompletionTable(title, tests);
96
+ }
97
+ return runTests({
98
+ tests,
99
+ defaultMarkedOptions: { gfm: true, pedantic: false },
100
+ addExtension,
101
+ });
102
+ case "New":
103
+ return runTests({ tests, addExtension });
104
+ case "Original":
105
+ return runTests({
106
+ tests,
107
+ defaultMarkedOptions: { gfm: false, pedantic: true },
108
+ addExtension,
109
+ });
110
+ case "RedDOS":
111
+ return runTests({ tests, addExtension });
112
+ default:
113
+ throw new Error("invalid title");
114
+ }
115
+ }),
116
+ );
117
+ }
118
+
119
+ function parseMarked(markedown, options, addExtension) {
120
+ const marked = new Marked(options);
121
+ addExtension(marked);
122
+ return marked.parse(markedown);
123
+ }
@@ -0,0 +1,30 @@
1
+ import { getTests } from "../src/index.js";
2
+ import { resolvePath } from "../src/helpers.js";
3
+ import test from "node:test";
4
+ import assert from "node:assert";
5
+
6
+ test("get-tests", async (t) => {
7
+ await t.test("getTests(string)", async () => {
8
+ const tests = await getTests(
9
+ resolvePath("../node_modules/marked-repo/test/specs/commonmark"),
10
+ );
11
+
12
+ assert.ok(tests.Tabs);
13
+ });
14
+
15
+ await t.test("getTests(array)", async () => {
16
+ const tests = await getTests([
17
+ resolvePath("../node_modules/marked-repo/test/specs/commonmark"),
18
+ ]);
19
+
20
+ assert.ok(tests[0].Tabs);
21
+ });
22
+
23
+ await t.test("getTests(obj)", async () => {
24
+ const tests = await getTests({
25
+ test: resolvePath("../node_modules/marked-repo/test/specs/commonmark"),
26
+ });
27
+
28
+ assert.ok(tests.test.Tabs);
29
+ });
30
+ });
@@ -0,0 +1,31 @@
1
+ import { htmlIsEqual, firstDiff } from "../src/index.js";
2
+ import test from "node:test";
3
+ import assert from "node:assert";
4
+
5
+ test("html-differ", async (t) => {
6
+ await t.test("htmlIsEqual is equal", async () => {
7
+ const same = await htmlIsEqual("<p> test </p>", "<p> test </p>");
8
+
9
+ assert.ok(same);
10
+ });
11
+
12
+ await t.test("htmlIsEqual is not equal", async () => {
13
+ const same = await htmlIsEqual("<p>test1</p>", "<p>test2</p>");
14
+
15
+ assert.ok(!same);
16
+ });
17
+
18
+ await t.test("firstDiff", async () => {
19
+ const diff = await firstDiff("<p>test1</p>", "<p>test2</p>");
20
+
21
+ assert.strictEqual(diff.actual, "<p>test1</p>");
22
+ assert.strictEqual(diff.expected, "<p>test2</p>");
23
+ });
24
+
25
+ await t.test("firstDiff padding", async () => {
26
+ const diff = await firstDiff("<p>test1</p>", "<p>test2</p>", 5);
27
+
28
+ assert.strictEqual(diff.actual, "<p>test1");
29
+ assert.strictEqual(diff.expected, "<p>test2");
30
+ });
31
+ });
@@ -0,0 +1,24 @@
1
+ import { outputCompletionTable } from "../src/index.js";
2
+ import test from "node:test";
3
+ import assert from "node:assert";
4
+
5
+ test("output-table", (t) => {
6
+ t.test("outputCompletionTable", () => {
7
+ let output = "";
8
+ t.mock.method(console, "log", (...args) => {
9
+ output += args.join(" ") + "\n";
10
+ });
11
+ const tests = {
12
+ Tests: {
13
+ total: 1,
14
+ pass: 1,
15
+ },
16
+ };
17
+ outputCompletionTable("Title", tests);
18
+
19
+ assert.strictEqual(
20
+ output,
21
+ "----------------------\n| Title |\n| |\n| Tests 1 of 1 100% |\n----------------------\n\n",
22
+ );
23
+ });
24
+ });
@@ -0,0 +1,8 @@
1
+ import { runAllMarkedSpecTests } from "../src/index.js";
2
+ import test from "node:test";
3
+
4
+ test("run-tests", async (t) => {
5
+ await t.test("runAllMarkedSpecTests", async () => {
6
+ await runAllMarkedSpecTests();
7
+ });
8
+ });
File without changes