@idomatic/parser-html 1.0.42 → 1.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.
package/consts/index.js CHANGED
@@ -1 +1 @@
1
- export const templateRegex = /<template(?:\s[^>]*)?>([\s\S]*?)<\/template>/i;
1
+ export const TEMPLATE_REGEX = /<template(?:\s[^>]*)?>([\s\S]*?)<\/template>/i;
package/idGen.js ADDED
@@ -0,0 +1,58 @@
1
+ import { randomUUID } from "crypto";
2
+
3
+ /**
4
+ * Id generation with a configurable strategy, for HTML/Vue templates.
5
+ *
6
+ * - "semantic" (default): derive a human-readable slug from the tag and its
7
+ * descriptive attributes, then guarantee uniqueness by suffixing `-2`, `-3`,
8
+ * ... only on collision.
9
+ * - "random": use `${prefix}${randomUUID()}`.
10
+ *
11
+ * Either way the factory is seeded with ids already present in the file, so
12
+ * re-runs are idempotent: a new element never duplicates an existing id.
13
+ */
14
+
15
+ const MAX_SLUG_LENGTH = 40;
16
+
17
+ export function slugify(str, maxLen = MAX_SLUG_LENGTH) {
18
+ if (!str) return "";
19
+ return String(str)
20
+ .trim()
21
+ .toLowerCase()
22
+ .replace(/[^a-z0-9]+/g, "-")
23
+ .replace(/-{2,}/g, "-")
24
+ .replace(/^-+|-+$/g, "")
25
+ .slice(0, maxLen)
26
+ .replace(/-+$/g, "");
27
+ }
28
+
29
+ /**
30
+ * @param {object} config - iDomatic config (uses `prefix` and `idStrategy`).
31
+ * @param {Iterable<string>} existing - ids already present in the file.
32
+ * @returns {(parts: string[]) => string} - returns a unique id per call.
33
+ */
34
+ export function createIdFactory(config, existing = []) {
35
+ const prefix = config.prefix || "";
36
+ const random = config.idStrategy === "random";
37
+ const taken = new Set(existing);
38
+
39
+ return function makeId(parts) {
40
+ if (random) {
41
+ let candidate = `${prefix}${randomUUID()}`;
42
+ while (taken.has(candidate)) candidate = `${prefix}${randomUUID()}`;
43
+ taken.add(candidate);
44
+ return candidate;
45
+ }
46
+
47
+ const slug =
48
+ slugify(parts.map((p) => slugify(p)).filter(Boolean).join("-")) || "el";
49
+
50
+ let candidate = `${prefix}${slug}`;
51
+ let n = 2;
52
+ while (taken.has(candidate)) {
53
+ candidate = `${prefix}${slug}-${n++}`;
54
+ }
55
+ taken.add(candidate);
56
+ return candidate;
57
+ };
58
+ }
package/index.js CHANGED
@@ -1,6 +1,6 @@
1
1
  import fs from "fs";
2
2
  import path from "path";
3
- import { templateRegex } from "./consts/index.js";
3
+ import { TEMPLATE_REGEX as templateRegex } from "./consts/index.js";
4
4
  import { processHtmlContent, processVueTemplate } from "./utils/index.js";
5
5
 
6
6
  /**
@@ -18,7 +18,6 @@ export default async function parseHTML(filePath, config, dry = false) {
18
18
  let updatedContent = originalContent;
19
19
 
20
20
  if (ext === ".vue") {
21
- // Process Vue <template> tag contents using MagicString-based approach
22
21
  const match = originalContent.match(templateRegex);
23
22
  if (match) {
24
23
  const newTemplate = processVueTemplate(match[1], config);
package/package.json CHANGED
@@ -1,9 +1,16 @@
1
1
  {
2
2
  "name": "@idomatic/parser-html",
3
- "version": "1.0.42",
3
+ "version": "1.1.0",
4
4
  "description": "HTML/Vue/Angular parser for idomatic CLI",
5
5
  "type": "module",
6
6
  "main": "index.js",
7
+ "files": [
8
+ "index.js",
9
+ "idGen.js",
10
+ "utils",
11
+ "consts",
12
+ "helpers"
13
+ ],
7
14
  "exports": {
8
15
  "default": "./index.js"
9
16
  },
@@ -12,12 +19,22 @@
12
19
  "parser",
13
20
  "html",
14
21
  "vue",
15
- "angular"
22
+ "angular",
23
+ "data-testid",
24
+ "test-automation",
25
+ "playwright",
26
+ "cypress",
27
+ "testing-library"
16
28
  ],
17
29
  "author": "Amar Smajlovic",
18
30
  "license": "MIT",
31
+ "scripts": {
32
+ "test": "vitest run"
33
+ },
19
34
  "dependencies": {
20
- "cheerio": "^1.0.0-rc.12",
21
35
  "magic-string": "^0.30.17"
36
+ },
37
+ "devDependencies": {
38
+ "vitest": "^2.1.8"
22
39
  }
23
40
  }
package/utils/index.js CHANGED
@@ -1,77 +1,98 @@
1
1
  import MagicString from "magic-string";
2
- import { randomUUID } from "crypto";
2
+ import { createIdFactory } from "../idGen.js";
3
3
 
4
- /**
5
- * Processes a Vue template content by inserting unique IDs while preserving formatting.
6
- *
7
- * @param {string} templateContent - The content inside the Vue <template> tag.
8
- * @param {object} config - The configuration object.
9
- * @param {string} config.attributeName - The attribute name to add (e.g. "id" or "data-id").
10
- * @param {string} config.prefix - The prefix for generated IDs.
11
- * @param {string[]} [config.excludeTags] - An array of tag names to exclude (optional).
12
- * @returns {string} - The updated template content.
13
- */
14
- export function processVueTemplate(templateContent, config) {
15
- const { attributeName, prefix, excludeTags = [] } = config;
16
- const ms = new MagicString(templateContent);
17
-
18
- // A generic regex to match opening tags:
19
- // - It captures the tag name and its attributes.
20
- // - This regex is simplified, so you might need additional adjustments for complex cases.
21
- const tagRegex = /<([a-zA-Z][^\s/>]*)([^>]*?)(\/?)>/g;
4
+ // Attributes that describe an element well, in priority order.
5
+ const DESCRIPTIVE_ATTRS = [
6
+ "aria-label",
7
+ "name",
8
+ "placeholder",
9
+ "alt",
10
+ "title",
11
+ "label",
12
+ "role",
13
+ "type",
14
+ ];
22
15
 
23
- let match;
24
- while ((match = tagRegex.exec(templateContent)) !== null) {
25
- const fullMatch = match[0]; // entire opening tag text
26
- const tagName = match[1]; // tag name, e.g., v-btn, i, etc.
27
- const attributesStr = match[2]; // all attributes as a string
28
- const selfClosing = match[3] || ""; // self-closing slash if present
16
+ const TAG_REGEX = /<([a-zA-Z][^\s/>]*)([^>]*?)(\/?)>/g;
29
17
 
30
- // If the tag is in the exclude list, skip processing.
31
- if (excludeTags.includes(tagName)) continue;
18
+ function escapeRegExp(str) {
19
+ return str.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
20
+ }
32
21
 
33
- // Check if this tag already has the attribute
34
- const idRegex = new RegExp(`\\s${attributeName}\\s*=`);
35
- if (idRegex.test(attributesStr)) continue;
22
+ function getAttrValue(attributesStr, attrName) {
23
+ const re = new RegExp(
24
+ `${escapeRegExp(attrName)}\\s*=\\s*(?:"([^"]*)"|'([^']*)')`,
25
+ "i"
26
+ );
27
+ const match = attributesStr.match(re);
28
+ if (!match) return "";
29
+ return match[1] ?? match[2] ?? "";
30
+ }
36
31
 
37
- // Insert the attribute just before the closing of the tag.
38
- // We subtract the length of any trailing self-closing slash and the ">" character.
39
- const insertPosition =
40
- match.index + fullMatch.length - (selfClosing.length + 1);
41
- ms.appendLeft(
42
- insertPosition,
43
- ` ${attributeName}="${prefix}${randomUUID()}"`
44
- );
32
+ function describe(attributesStr) {
33
+ for (const name of DESCRIPTIVE_ATTRS) {
34
+ const value = getAttrValue(attributesStr, name);
35
+ if (value) return value;
45
36
  }
37
+ return "";
38
+ }
46
39
 
47
- return ms.toString();
40
+ function collectExistingIds(content, attributeName) {
41
+ const ids = [];
42
+ const re = new RegExp(
43
+ `\\s${escapeRegExp(attributeName)}\\s*=\\s*(?:"([^"]*)"|'([^']*)')`,
44
+ "gi"
45
+ );
46
+ let match;
47
+ while ((match = re.exec(content)) !== null) {
48
+ const value = match[1] ?? match[2];
49
+ if (value) ids.push(value);
50
+ }
51
+ return ids;
48
52
  }
49
53
 
50
- export function processHtmlContent(htmlContent, config) {
51
- const { attributeName, prefix, excludeTags = [] } = config;
52
- const ms = new MagicString(htmlContent);
54
+ /**
55
+ * Inserts semantic, unique ids into every eligible tag of an HTML-like string
56
+ * while preserving the original formatting.
57
+ *
58
+ * @param {string} content - HTML or Vue template markup.
59
+ * @param {object} config - The configuration object.
60
+ * @param {string} config.attributeName - The attribute name to add.
61
+ * @param {string} [config.prefix] - The prefix for generated ids.
62
+ * @param {string[]} [config.excludeTags] - Tag names to skip.
63
+ * @returns {string} - The updated markup.
64
+ */
65
+ function processTemplate(content, config) {
66
+ const { attributeName, excludeTags = [] } = config;
67
+ const ms = new MagicString(content);
68
+ const makeId = createIdFactory(config, collectExistingIds(content, attributeName));
69
+
70
+ const idRegex = new RegExp(`\\s${escapeRegExp(attributeName)}\\s*=`);
53
71
 
54
- // This regex is similar to the Vue one.
55
- const tagRegex = /<([a-zA-Z][^\s/>]*)([^>]*?)(\/?)>/g;
56
72
  let match;
57
- while ((match = tagRegex.exec(htmlContent)) !== null) {
73
+ while ((match = TAG_REGEX.exec(content)) !== null) {
58
74
  const fullMatch = match[0];
59
75
  const tagName = match[1];
60
76
  const attributesStr = match[2];
61
77
  const selfClosing = match[3] || "";
62
78
 
63
79
  if (excludeTags.includes(tagName)) continue;
64
-
65
- const idRegex = new RegExp(`\\s${attributeName}\\s*=`);
66
80
  if (idRegex.test(attributesStr)) continue;
67
81
 
82
+ const idValue = makeId([tagName, describe(attributesStr)]);
68
83
  const insertPosition =
69
84
  match.index + fullMatch.length - (selfClosing.length + 1);
70
- ms.appendLeft(
71
- insertPosition,
72
- ` ${attributeName}="${prefix}${randomUUID()}"`
73
- );
85
+ ms.appendLeft(insertPosition, ` ${attributeName}="${idValue}"`);
74
86
  }
75
87
 
88
+ TAG_REGEX.lastIndex = 0;
76
89
  return ms.toString();
77
90
  }
91
+
92
+ export function processVueTemplate(templateContent, config) {
93
+ return processTemplate(templateContent, config);
94
+ }
95
+
96
+ export function processHtmlContent(htmlContent, config) {
97
+ return processTemplate(htmlContent, config);
98
+ }