@monoes/monodesign 1.2.20 → 1.2.22

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.
Files changed (85) hide show
  1. package/README.md +2 -2
  2. package/cli/engine/design-system-checks.mjs +381 -0
  3. package/cli/engine/design-system-parse.mjs +433 -0
  4. package/cli/engine/design-system.mjs +20 -736
  5. package/cli/engine/engines/regex/detect-text-matchers.mjs +371 -0
  6. package/cli/engine/engines/regex/detect-text-run.mjs +186 -0
  7. package/cli/engine/engines/regex/detect-text.mjs +11 -523
  8. package/cli/engine/engines/static-html/css-cascade-color.mjs +219 -0
  9. package/cli/engine/engines/static-html/css-cascade-static-data.mjs +138 -0
  10. package/cli/engine/engines/static-html/css-cascade-static-dom.mjs +132 -0
  11. package/cli/engine/engines/static-html/css-cascade-static-parse.mjs +393 -0
  12. package/cli/engine/engines/static-html/css-cascade.mjs +24 -837
  13. package/cli/lib/monodesign-config-consent.mjs +93 -0
  14. package/cli/lib/monodesign-config-core.mjs +37 -0
  15. package/cli/lib/monodesign-config-detection.mjs +133 -0
  16. package/cli/lib/monodesign-config-filter.mjs +198 -0
  17. package/cli/lib/monodesign-config-ignore-value.mjs +212 -0
  18. package/cli/lib/monodesign-config.mjs +21 -623
  19. package/package.json +2 -2
  20. package/skill/scripts/context-fields.mjs +65 -0
  21. package/skill/scripts/context-resolve.mjs +425 -0
  22. package/skill/scripts/context-update.mjs +151 -0
  23. package/skill/scripts/context-utils.mjs +68 -0
  24. package/skill/scripts/context-workspace.mjs +245 -0
  25. package/skill/scripts/context.mjs +17 -891
  26. package/skill/scripts/hook-admin-config.mjs +152 -0
  27. package/skill/scripts/hook-admin-ignore.mjs +131 -0
  28. package/skill/scripts/hook-admin-manifest.mjs +292 -0
  29. package/skill/scripts/hook-admin.mjs +8 -541
  30. package/skill/scripts/hook-lib-cache.mjs +145 -0
  31. package/skill/scripts/hook-lib-config.mjs +292 -0
  32. package/skill/scripts/hook-lib-detector.mjs +72 -0
  33. package/skill/scripts/hook-lib-events.mjs +182 -0
  34. package/skill/scripts/hook-lib-findings.mjs +201 -0
  35. package/skill/scripts/hook-lib-ignore.mjs +205 -0
  36. package/skill/scripts/hook-lib-render.mjs +273 -0
  37. package/skill/scripts/hook-lib-run.mjs +281 -0
  38. package/skill/scripts/hook-lib-scan-targets.mjs +128 -0
  39. package/skill/scripts/hook-lib.mjs +71 -1747
  40. package/skill/scripts/lib/design-parser-colors.mjs +182 -0
  41. package/skill/scripts/lib/design-parser-extract.mjs +333 -0
  42. package/skill/scripts/lib/design-parser-sections.mjs +214 -0
  43. package/skill/scripts/lib/design-parser-yaml.mjs +135 -0
  44. package/skill/scripts/lib/design-parser.mjs +10 -783
  45. package/skill/scripts/live/manual-apply-chunk.mjs +151 -0
  46. package/skill/scripts/live/manual-apply-compact.mjs +122 -0
  47. package/skill/scripts/live/manual-apply-evidence.mjs +115 -0
  48. package/skill/scripts/live/manual-apply-log.mjs +179 -0
  49. package/skill/scripts/live/manual-apply-transaction.mjs +122 -0
  50. package/skill/scripts/live/manual-apply.mjs +65 -640
  51. package/skill/scripts/live/svelte-component-accept.mjs +248 -0
  52. package/skill/scripts/live/svelte-component-css.mjs +230 -0
  53. package/skill/scripts/live/svelte-component-markup.mjs +104 -0
  54. package/skill/scripts/live/svelte-component-scaffold.mjs +118 -0
  55. package/skill/scripts/live/svelte-component-session.mjs +158 -0
  56. package/skill/scripts/live/svelte-component.mjs +32 -792
  57. package/skill/scripts/live-accept-mutate.mjs +152 -0
  58. package/skill/scripts/live-accept-parse.mjs +370 -0
  59. package/skill/scripts/live-accept-scrub.mjs +59 -0
  60. package/skill/scripts/live-accept-search.mjs +58 -0
  61. package/skill/scripts/live-accept.mjs +15 -631
  62. package/skill/scripts/live-commit-manual-edits-paths.mjs +27 -0
  63. package/skill/scripts/live-commit-manual-edits-repair.mjs +166 -0
  64. package/skill/scripts/live-commit-manual-edits-rollback.mjs +231 -0
  65. package/skill/scripts/live-commit-manual-edits-utils.mjs +167 -0
  66. package/skill/scripts/live-commit-manual-edits-verify.mjs +356 -0
  67. package/skill/scripts/live-commit-manual-edits.mjs +24 -881
  68. package/skill/scripts/live-copy-edit-agent.mjs +16 -551
  69. package/skill/scripts/live-copy-edit-compact.mjs +137 -0
  70. package/skill/scripts/live-copy-edit-post-apply.mjs +175 -0
  71. package/skill/scripts/live-copy-edit-runners.mjs +297 -0
  72. package/skill/scripts/live-inject-csp.mjs +132 -0
  73. package/skill/scripts/live-inject-files.mjs +229 -0
  74. package/skill/scripts/live-inject-tag.mjs +114 -0
  75. package/skill/scripts/live-inject.mjs +13 -440
  76. package/skill/scripts/live-server-poll.mjs +232 -0
  77. package/skill/scripts/live-server-routes.mjs +449 -0
  78. package/skill/scripts/live-server-state.mjs +361 -0
  79. package/skill/scripts/live-server.mjs +10 -946
  80. package/skill/scripts/live-wrap-css.mjs +132 -0
  81. package/skill/scripts/live-wrap-manual-edit.mjs +153 -0
  82. package/skill/scripts/live-wrap-search.mjs +247 -0
  83. package/skill/scripts/live-wrap.mjs +21 -484
  84. package/skill/scripts/palette-seeds.mjs +401 -0
  85. package/skill/scripts/palette.mjs +1 -395
@@ -0,0 +1,132 @@
1
+ // live-wrap search-query construction + per-file CSS/comment authoring
2
+ // helpers. Split out of live-wrap.mjs (file-size sweep — pure move, no
3
+ // behaviour change).
4
+
5
+ import path from 'node:path';
6
+
7
+ /**
8
+ * Build search query strings in priority order (most specific first).
9
+ * ID is most reliable, then specific class combos, then single classes, then raw query.
10
+ */
11
+ function buildSearchQueries(elementId, classes, tag, query) {
12
+ const queries = [];
13
+
14
+ // 1. ID is the most specific
15
+ if (elementId) {
16
+ queries.push(`id="${elementId}"`);
17
+ }
18
+
19
+ // 2. Full class attribute match (for elements with distinctive multi-class combos).
20
+ // Emit both class="..." (HTML) and className="..." (React/JSX) so whichever
21
+ // convention the file uses will match.
22
+ if (classes) {
23
+ const classList = splitClassList(classes);
24
+ if (classList.length > 1) {
25
+ const joined = classList.join(' ');
26
+ const sorted = [...classList].sort((a, b) => b.length - a.length);
27
+ queries.push(`class="${joined}"`);
28
+ queries.push(`className="${joined}"`);
29
+ for (const className of sorted) {
30
+ queries.push(className);
31
+ }
32
+ } else if (classList.length === 1) {
33
+ queries.push(classList[0]);
34
+ }
35
+ }
36
+
37
+ // 3. Tag + class combo (e.g., <section class="hero">).
38
+ // Same dual-emit for JSX compatibility.
39
+ if (tag && classes) {
40
+ const firstClass = splitClassList(classes)[0];
41
+ queries.push(`<${tag} class="${firstClass}`);
42
+ queries.push(`<${tag} className="${firstClass}`);
43
+ }
44
+
45
+ // 4. Raw fallback query
46
+ if (query) {
47
+ queries.push(query);
48
+ }
49
+
50
+ return queries;
51
+ }
52
+
53
+ function splitClassList(classes) {
54
+ return String(classes).split(/[,\s]+/).map(c => c.trim()).filter(Boolean);
55
+ }
56
+
57
+ function detectCommentSyntax(filePath) {
58
+ const ext = path.extname(filePath).toLowerCase();
59
+ if (ext === '.jsx' || ext === '.tsx') {
60
+ return { open: '{/*', close: '*/}' };
61
+ }
62
+ // HTML, Vue, Svelte, Astro all use HTML comments
63
+ return { open: '<!--', close: '-->' };
64
+ }
65
+
66
+ function detectStyleMode(filePath) {
67
+ const ext = path.extname(filePath).toLowerCase();
68
+ if (ext === '.astro') {
69
+ return {
70
+ mode: 'astro-global-prefixed',
71
+ styleTag: '<style is:inline data-monodesign-css="SESSION_ID">',
72
+ };
73
+ }
74
+ return {
75
+ mode: 'scoped',
76
+ styleTag: '<style data-monodesign-css="SESSION_ID">',
77
+ };
78
+ }
79
+
80
+ function buildCssSelectorPrefixExamples(styleMode, count) {
81
+ if (styleMode !== 'astro-global-prefixed') return [];
82
+ return Array.from({ length: count }, (_, i) => `[data-monodesign-variant="${i + 1}"]`);
83
+ }
84
+
85
+ function buildCssAuthoring(styleMode, count) {
86
+ const variantNumbers = Array.from({ length: count }, (_, i) => i + 1);
87
+ if (styleMode.mode === 'astro-global-prefixed') {
88
+ return {
89
+ mode: styleMode.mode,
90
+ styleTag: styleMode.styleTag,
91
+ strategy: 'global-prefixed',
92
+ rulePattern: '[data-monodesign-variant="N"] > .variant-class { ... }',
93
+ selectorExamples: variantNumbers.map((n) => `[data-monodesign-variant="${n}"] > .variant-class`),
94
+ requirements: [
95
+ 'Use the styleTag exactly; the is:inline attribute is required for this file.',
96
+ 'Put raw CSS directly between the styleTag opening and a plain </style> close.',
97
+ 'Prefix every preview selector with the matching [data-monodesign-variant="N"] selector.',
98
+ 'Keep selectors anchored to the generated variant wrapper; do not rely on component CSS scoping for preview rules.',
99
+ ],
100
+ forbidden: [
101
+ 'Do not use @scope for this styleMode.',
102
+ 'Do not wrap style content in a JSX/TSX template literal ({` ... `}); that syntax is for .tsx/.jsx only.',
103
+ 'Do not put { immediately after the style opening tag; Astro parses { as expression syntax.',
104
+ ],
105
+ };
106
+ }
107
+ return {
108
+ mode: styleMode.mode,
109
+ styleTag: styleMode.styleTag,
110
+ strategy: 'scope-rule',
111
+ rulePattern: '@scope ([data-monodesign-variant="N"]) { :scope > .variant-class { ... } }',
112
+ selectorExamples: variantNumbers.map((n) => `@scope ([data-monodesign-variant="${n}"]) { :scope > .variant-class { ... } }`),
113
+ requirements: [
114
+ 'Use @scope blocks keyed to each [data-monodesign-variant="N"] wrapper.',
115
+ 'Inside each @scope block, make :scope rules step into the replacement element with a descendant combinator.',
116
+ 'Use the styleTag exactly; do not add framework-specific style attributes unless this object says to.',
117
+ ],
118
+ forbidden: [
119
+ 'Do not use global [data-monodesign-variant="N"] selector prefixes for this styleMode.',
120
+ 'Do not add is:inline to the style tag for this styleMode.',
121
+ ],
122
+ };
123
+ }
124
+
125
+ export {
126
+ buildSearchQueries,
127
+ splitClassList,
128
+ detectCommentSyntax,
129
+ detectStyleMode,
130
+ buildCssSelectorPrefixExamples,
131
+ buildCssAuthoring,
132
+ };
@@ -0,0 +1,153 @@
1
+ // live-wrap CLI arg parsing + buffered manual-edit reconciliation helpers.
2
+ // Split out of live-wrap.mjs (file-size sweep — pure move, no behaviour
3
+ // change).
4
+
5
+ import path from 'node:path';
6
+
7
+ function argVal(args, flag) {
8
+ const prefix = `${flag}=`;
9
+ for (const arg of args) {
10
+ if (arg.startsWith(prefix)) return arg.slice(prefix.length);
11
+ }
12
+ const idx = args.indexOf(flag);
13
+ return idx !== -1 && idx + 1 < args.length ? args[idx + 1] : null;
14
+ }
15
+
16
+ function pendingEntriesThatMayAffectWrap(entries, targetFile, originalLines, selectionStartLine, cwd) {
17
+ const targetAbs = path.resolve(cwd, targetFile);
18
+ return (entries || []).filter((entry) => {
19
+ return (entry.ops || []).some((op) => {
20
+ return manualEditMayAffectWrap(op, targetAbs, originalLines, selectionStartLine, cwd);
21
+ });
22
+ });
23
+ }
24
+
25
+ function manualEditMayAffectWrap(op, targetFile, originalLines, selectionStartLine, cwd) {
26
+ const targetAbs = path.resolve(cwd, targetFile);
27
+ if (manualEditHintFallsInsideSelection(op, targetAbs, originalLines, selectionStartLine, cwd)) return true;
28
+ if (manualEditLocatorMatchesSelection(op, originalLines)) return true;
29
+ if (typeof op?.originalText === 'string' && op.originalText.length > 0) {
30
+ return originalLines.join('\n').includes(op.originalText);
31
+ }
32
+ return false;
33
+ }
34
+
35
+ function manualEditHintFallsInsideSelection(op, targetAbs, originalLines, selectionStartLine, cwd) {
36
+ const hintFile = op?.sourceHint?.file;
37
+ const hintedLine = Number(op?.sourceHint?.line);
38
+ if (!hintFile || !Number.isFinite(hintedLine)) return false;
39
+ const hintAbs = path.isAbsolute(hintFile) ? hintFile : path.resolve(cwd, hintFile);
40
+ if (path.resolve(hintAbs) !== targetAbs) return false;
41
+ const hintedIndex = hintedLine - 1 - selectionStartLine;
42
+ return hintedIndex >= 0
43
+ && hintedIndex < originalLines.length
44
+ && typeof op?.originalText === 'string'
45
+ && originalLines[hintedIndex].includes(op.originalText);
46
+ }
47
+
48
+ function manualEditLocatorMatchesSelection(op, originalLines) {
49
+ if (!op || typeof op.originalText !== 'string' || op.originalText.length === 0) return false;
50
+ return originalLines.some((line) => (
51
+ line.includes(op.originalText) && lineMatchesManualEditLocator(line, op)
52
+ ));
53
+ }
54
+
55
+ function applyBufferedManualEditToLines(originalLines, selectionStartLine, op) {
56
+ if (
57
+ !op
58
+ || typeof op.originalText !== 'string'
59
+ || op.originalText.length === 0
60
+ || typeof op.newText !== 'string'
61
+ ) {
62
+ return { lines: originalLines, changed: false };
63
+ }
64
+
65
+ const replaceLine = (lineIndex) => ({
66
+ lines: originalLines.map((line, index) => (
67
+ index === lineIndex ? replaceOnce(line, op.originalText, op.newText) : line
68
+ )),
69
+ changed: true,
70
+ });
71
+
72
+ const hintedLine = Number(op.sourceHint?.line);
73
+ if (Number.isFinite(hintedLine)) {
74
+ const hintedIndex = hintedLine - 1 - selectionStartLine;
75
+ if (hintedIndex >= 0 && hintedIndex < originalLines.length && originalLines[hintedIndex].includes(op.originalText)) {
76
+ return replaceLine(hintedIndex);
77
+ }
78
+ }
79
+
80
+ const locatorMatches = [];
81
+ for (let index = 0; index < originalLines.length; index += 1) {
82
+ const line = originalLines[index];
83
+ if (!line.includes(op.originalText)) continue;
84
+ if (!lineMatchesManualEditLocator(line, op)) continue;
85
+ locatorMatches.push(index);
86
+ }
87
+ if (locatorMatches.length === 1) return replaceLine(locatorMatches[0]);
88
+
89
+ const originalBlock = originalLines.join('\n');
90
+ if (countOccurrences(originalBlock, op.originalText) === 1) {
91
+ return {
92
+ lines: replaceOnce(originalBlock, op.originalText, op.newText).split('\n'),
93
+ changed: true,
94
+ };
95
+ }
96
+
97
+ return { lines: originalLines, changed: false };
98
+ }
99
+
100
+ function lineMatchesManualEditLocator(line, op) {
101
+ if (op.tag) {
102
+ const tagRe = new RegExp(`<\\s*${escapeRegExp(op.tag)}(?=[\\s>/]|$)`, 'i');
103
+ if (!tagRe.test(line)) return false;
104
+ }
105
+
106
+ if (op.elementId) {
107
+ const id = escapeRegExp(op.elementId);
108
+ const idRe = new RegExp(`\\bid\\s*=\\s*["']${id}["']`);
109
+ if (!idRe.test(line)) return false;
110
+ }
111
+
112
+ const classes = Array.isArray(op.classes) ? op.classes.filter(Boolean) : [];
113
+ for (const className of classes) {
114
+ if (!line.includes(className)) return false;
115
+ }
116
+
117
+ return true;
118
+ }
119
+
120
+ function replaceOnce(value, needle, replacement) {
121
+ const index = value.indexOf(needle);
122
+ if (index === -1) return value;
123
+ return value.slice(0, index) + replacement + value.slice(index + needle.length);
124
+ }
125
+
126
+ function countOccurrences(value, needle) {
127
+ if (!needle) return 0;
128
+ let count = 0;
129
+ let index = 0;
130
+ while (true) {
131
+ index = value.indexOf(needle, index);
132
+ if (index === -1) return count;
133
+ count += 1;
134
+ index += needle.length;
135
+ }
136
+ }
137
+
138
+ function escapeRegExp(value) {
139
+ return String(value).replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
140
+ }
141
+
142
+ export {
143
+ argVal,
144
+ pendingEntriesThatMayAffectWrap,
145
+ manualEditMayAffectWrap,
146
+ manualEditHintFallsInsideSelection,
147
+ manualEditLocatorMatchesSelection,
148
+ applyBufferedManualEditToLines,
149
+ lineMatchesManualEditLocator,
150
+ replaceOnce,
151
+ countOccurrences,
152
+ escapeRegExp,
153
+ };
@@ -0,0 +1,247 @@
1
+ // live-wrap element search: locating the target file and the element's
2
+ // start/end lines in its source. Split out of live-wrap.mjs (file-size
3
+ // sweep — pure move, no behaviour change).
4
+
5
+ import fs from 'node:fs';
6
+ import path from 'node:path';
7
+ import { isGeneratedFile } from './lib/is-generated.mjs';
8
+
9
+ const EXTENSIONS = ['.html', '.jsx', '.tsx', '.vue', '.svelte', '.astro'];
10
+
11
+ /**
12
+ * Search project files for the query string (class name, ID, etc.)
13
+ * Returns the first matching file path, or null.
14
+ */
15
+ function findFileWithQuery(query, cwd, genOpts = {}) {
16
+ const searchDirs = ['src', 'app', 'pages', 'components', 'public', 'views', 'templates', '.'];
17
+ const seen = new Set();
18
+
19
+ for (const dir of searchDirs) {
20
+ const absDir = path.join(cwd, dir);
21
+ if (!fs.existsSync(absDir)) continue;
22
+ const result = searchDir(absDir, query, seen, 0, genOpts);
23
+ if (result) return result;
24
+ }
25
+ return null;
26
+ }
27
+
28
+ function searchDir(dir, query, seen, depth, genOpts) {
29
+ if (depth > 5) return null; // don't go too deep
30
+ const realDir = fs.realpathSync(dir);
31
+ if (seen.has(realDir)) return null;
32
+ seen.add(realDir);
33
+
34
+ let entries;
35
+ try { entries = fs.readdirSync(dir, { withFileTypes: true }); }
36
+ catch { return null; }
37
+
38
+ // Check files first
39
+ for (const entry of entries) {
40
+ if (!entry.isFile()) continue;
41
+ const ext = path.extname(entry.name).toLowerCase();
42
+ if (!EXTENSIONS.includes(ext)) continue;
43
+
44
+ const filePath = path.join(dir, entry.name);
45
+ if (!genOpts.includeGenerated && isGeneratedFile(filePath, genOpts)) continue;
46
+ try {
47
+ const content = fs.readFileSync(filePath, 'utf-8');
48
+ if (content.includes(query)) return filePath;
49
+ } catch { /* skip unreadable files */ }
50
+ }
51
+
52
+ // Then recurse into directories. Always skip node_modules and .git (never
53
+ // project content). dist/build/out are left to the isGeneratedFile guard so
54
+ // the includeGenerated second-pass can still find the element there and
55
+ // report `generatedMatch`.
56
+ for (const entry of entries) {
57
+ if (!entry.isDirectory()) continue;
58
+ if (entry.name === 'node_modules' || entry.name === '.git') continue;
59
+ const result = searchDir(path.join(dir, entry.name), query, seen, depth + 1, genOpts);
60
+ if (result) return result;
61
+ }
62
+
63
+ return null;
64
+ }
65
+
66
+ /**
67
+ * Regex that matches a tag opener on a line. Allows the tag name to be
68
+ * followed by whitespace, `>`, `/`, or end-of-line so that multi-line JSX
69
+ * openers (e.g. `<section\n className="..."\n>`) are recognised.
70
+ */
71
+ const OPENER_RE = /<([A-Za-z][A-Za-z0-9]*)(?=[\s/>]|$)/;
72
+
73
+ /**
74
+ * Find the element's start and end line in the file.
75
+ *
76
+ * `query` is a class name, attribute fragment (`class="..."`, `className="..."`,
77
+ * `id="..."`), or a raw text snippet. Because a query can appear on a
78
+ * continuation line of a multi-line tag (e.g. the `className="..."` row of a
79
+ * `<section\n className="..."\n>` JSX tag), we walk backward from the match
80
+ * line to find the actual tag opener. When `tag` is provided, opener candidates
81
+ * must match that tag name.
82
+ */
83
+ /**
84
+ * Return the smallest leading-whitespace count across a set of lines,
85
+ * ignoring blank lines (whose indent isn't load-bearing). Used to compute
86
+ * the common base indent of a multi-line picked element so reindenting
87
+ * under the wrapper preserves the relative depth between lines.
88
+ */
89
+ function minLeadingSpaces(lines) {
90
+ let min = Infinity;
91
+ for (const l of lines) {
92
+ if (l.trim() === '') continue;
93
+ const m = l.match(/^(\s*)/);
94
+ if (m && m[1].length < min) min = m[1].length;
95
+ }
96
+ return min === Infinity ? 0 : min;
97
+ }
98
+
99
+ function findElement(lines, query, tag = null) {
100
+ // Iterate all matches — the first substring hit isn't always the right one.
101
+ for (let i = 0; i < lines.length; i++) {
102
+ if (!lines[i].includes(query)) continue;
103
+
104
+ const stripped = lines[i].trim();
105
+ if (stripped.startsWith('<!--') || stripped.startsWith('{/*') || stripped.startsWith('//')) continue;
106
+ // Skip lines already inside a variant wrapper
107
+ if (lines[i].includes('data-monodesign-variant')) continue;
108
+
109
+ const openerLine = findOpenerLine(lines, i, tag);
110
+ if (openerLine === -1) continue;
111
+
112
+ const endLine = findClosingLine(lines, openerLine);
113
+ return { startLine: openerLine, endLine };
114
+ }
115
+
116
+ return null;
117
+ }
118
+
119
+ /**
120
+ * Like findElement, but returns every match. Used for ambiguity detection
121
+ * when the agent passes --text: when the same className appears on multiple
122
+ * sibling elements (a list of cards, repeated section variants, etc.),
123
+ * first-match silently lands on the wrong branch. Returning all matches lets
124
+ * the caller narrow by textContent or fail with a structured ambiguity error.
125
+ */
126
+ function findAllElements(lines, query, tag = null) {
127
+ const out = [];
128
+ const seen = new Set();
129
+ for (let i = 0; i < lines.length; i++) {
130
+ if (!lines[i].includes(query)) continue;
131
+ const stripped = lines[i].trim();
132
+ if (stripped.startsWith('<!--') || stripped.startsWith('{/*') || stripped.startsWith('//')) continue;
133
+ if (lines[i].includes('data-monodesign-variant')) continue;
134
+ const openerLine = findOpenerLine(lines, i, tag);
135
+ if (openerLine === -1) continue;
136
+ if (seen.has(openerLine)) continue; // multiple matches inside the same element
137
+ seen.add(openerLine);
138
+ const endLine = findClosingLine(lines, openerLine);
139
+ out.push({ startLine: openerLine, endLine });
140
+ }
141
+ return out;
142
+ }
143
+
144
+ /**
145
+ * Narrow a candidate set to those whose source body matches a meaningful
146
+ * prefix of the picked element's textContent. The compare strips tags and
147
+ * JSX expressions, then checks two whitespace normalizations side-by-side:
148
+ *
149
+ * - single-space ("hero two second card body")
150
+ * - no-whitespace ("herotwosecondcardbody")
151
+ *
152
+ * Both are needed because `el.textContent` concatenates sibling text without
153
+ * inserting whitespace (e.g. `<h1>Hero Two</h1><p>Second…</p>` reads as
154
+ * `"Hero TwoSecond…"`), while the source has whitespace between tags. If
155
+ * EITHER normalization matches, the candidate keeps. A snippet shorter than
156
+ * 8 chars after stripping is too weak to disambiguate — the caller falls
157
+ * back to first-match.
158
+ */
159
+ function filterByText(candidates, lines, text) {
160
+ const trimmed = text.replace(/\s+/g, ' ').trim().toLowerCase().slice(0, 80);
161
+ // Too short to disambiguate. Return [] so the caller's `filtered.length
162
+ // === 0` branch fires (fall back to first-match) — the previous
163
+ // `candidates.slice()` return forced `filtered.length > 1` and surfaced
164
+ // a spurious `element_ambiguous` error on every short-text picker event
165
+ // with multiple candidates.
166
+ if (trimmed.length < 8) return [];
167
+ const targetSpaced = trimmed;
168
+ const targetCompact = trimmed.replace(/\s+/g, '');
169
+
170
+ return candidates.filter((c) => {
171
+ const body = lines.slice(c.startLine, c.endLine + 1).join(' ');
172
+ const inner = body
173
+ .replace(/<[^>]*>/g, ' ') // strip HTML/JSX tags
174
+ .replace(/\{[^}]*\}/g, ' ') // strip JSX expressions
175
+ .toLowerCase();
176
+ const sourceSpaced = inner.replace(/\s+/g, ' ').trim();
177
+ const sourceCompact = inner.replace(/\s+/g, '');
178
+ return sourceSpaced.includes(targetSpaced) || sourceCompact.includes(targetCompact);
179
+ });
180
+ }
181
+
182
+ /**
183
+ * Resolve a match line to the real tag opener. If the match line itself opens
184
+ * a tag, return it. Otherwise walk up to 10 lines backward looking for the
185
+ * first tag opener. If `tag` is specified, the opener must match that tag
186
+ * name; an opener with a different tag name aborts the backward walk for this
187
+ * match (we don't jump across element boundaries).
188
+ *
189
+ * Returns the line index of the opener, or -1 if none can be resolved.
190
+ */
191
+ function findOpenerLine(lines, matchLine, tag) {
192
+ const self = lines[matchLine].match(OPENER_RE);
193
+ if (self) {
194
+ if (!tag || self[1] === tag) return matchLine;
195
+ return -1;
196
+ }
197
+ const MAX_BACKWALK = 10;
198
+ for (let i = matchLine - 1; i >= Math.max(0, matchLine - MAX_BACKWALK); i--) {
199
+ const opener = lines[i].match(OPENER_RE);
200
+ if (!opener) continue;
201
+ if (!tag || opener[1] === tag) return i;
202
+ // Different tag name than requested — abort; we're inside a non-target opener.
203
+ return -1;
204
+ }
205
+ return -1;
206
+ }
207
+
208
+ /**
209
+ * Starting from a line with an opening tag, find the line with the matching
210
+ * closing tag by counting tag nesting depth.
211
+ */
212
+ function findClosingLine(lines, start) {
213
+ const openMatch = lines[start].match(OPENER_RE);
214
+ if (!openMatch) return start; // caller passed a non-opener; nothing to span
215
+
216
+ const tagName = openMatch[1];
217
+ let depth = 0;
218
+ const openRe = new RegExp(`<${tagName}(?=[\\s/>]|$)`, 'g');
219
+ const selfCloseRe = new RegExp(`<${tagName}[^>]*/>`, 'g');
220
+ const closeRe = new RegExp(`</${tagName}\\s*>`, 'g');
221
+
222
+ for (let i = start; i < lines.length; i++) {
223
+ const line = lines[i];
224
+ const opens = (line.match(openRe) || []).length;
225
+ const selfCloses = (line.match(selfCloseRe) || []).length;
226
+ const closes = (line.match(closeRe) || []).length;
227
+
228
+ depth += opens - selfCloses - closes;
229
+
230
+ if (depth <= 0) return i;
231
+ }
232
+
233
+ // If we can't find the close, return a reasonable guess
234
+ return Math.min(start + 50, lines.length - 1);
235
+ }
236
+
237
+ export {
238
+ findFileWithQuery,
239
+ searchDir,
240
+ OPENER_RE,
241
+ minLeadingSpaces,
242
+ findElement,
243
+ findAllElements,
244
+ filterByText,
245
+ findOpenerLine,
246
+ findClosingLine,
247
+ };