@monoes/monodesign 1.2.18 → 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 (104) hide show
  1. package/README.md +3 -3
  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/detect-antipatterns-browser.js +12 -1
  6. package/cli/engine/engines/regex/detect-text-matchers.mjs +371 -0
  7. package/cli/engine/engines/regex/detect-text-run.mjs +186 -0
  8. package/cli/engine/engines/regex/detect-text.mjs +11 -523
  9. package/cli/engine/engines/static-html/css-cascade-color.mjs +219 -0
  10. package/cli/engine/engines/static-html/css-cascade-static-data.mjs +138 -0
  11. package/cli/engine/engines/static-html/css-cascade-static-dom.mjs +132 -0
  12. package/cli/engine/engines/static-html/css-cascade-static-parse.mjs +393 -0
  13. package/cli/engine/engines/static-html/css-cascade.mjs +24 -837
  14. package/cli/engine/registry/antipatterns-provider.mjs +60 -0
  15. package/cli/engine/registry/antipatterns-quality.mjs +218 -0
  16. package/cli/engine/registry/antipatterns-slop.mjs +226 -0
  17. package/cli/engine/registry/antipatterns.mjs +7 -494
  18. package/cli/engine/rules/checks-background.mjs +155 -0
  19. package/cli/engine/rules/checks-css-values.mjs +137 -0
  20. package/cli/engine/rules/checks-dom-effects.mjs +243 -0
  21. package/cli/engine/rules/checks-dom.mjs +148 -0
  22. package/cli/engine/rules/checks-element.mjs +286 -0
  23. package/cli/engine/rules/checks-html.mjs +204 -0
  24. package/cli/engine/rules/checks-overflow.mjs +263 -0
  25. package/cli/engine/rules/checks-page.mjs +465 -0
  26. package/cli/engine/rules/checks-pure.mjs +453 -0
  27. package/cli/engine/rules/checks-quality.mjs +447 -0
  28. package/cli/engine/rules/checks-stylesheet.mjs +324 -0
  29. package/cli/engine/rules/checks.mjs +98 -2939
  30. package/cli/lib/monodesign-config-consent.mjs +93 -0
  31. package/cli/lib/monodesign-config-core.mjs +37 -0
  32. package/cli/lib/monodesign-config-detection.mjs +133 -0
  33. package/cli/lib/monodesign-config-filter.mjs +198 -0
  34. package/cli/lib/monodesign-config-ignore-value.mjs +212 -0
  35. package/cli/lib/monodesign-config.mjs +21 -623
  36. package/package.json +2 -2
  37. package/skill/scripts/context-fields.mjs +65 -0
  38. package/skill/scripts/context-resolve.mjs +425 -0
  39. package/skill/scripts/context-update.mjs +151 -0
  40. package/skill/scripts/context-utils.mjs +68 -0
  41. package/skill/scripts/context-workspace.mjs +245 -0
  42. package/skill/scripts/context.mjs +17 -891
  43. package/skill/scripts/hook-admin-config.mjs +152 -0
  44. package/skill/scripts/hook-admin-ignore.mjs +131 -0
  45. package/skill/scripts/hook-admin-manifest.mjs +292 -0
  46. package/skill/scripts/hook-admin.mjs +8 -541
  47. package/skill/scripts/hook-before-edit-shell.mjs +184 -0
  48. package/skill/scripts/hook-before-edit.mjs +9 -165
  49. package/skill/scripts/hook-lib-cache.mjs +145 -0
  50. package/skill/scripts/hook-lib-config.mjs +292 -0
  51. package/skill/scripts/hook-lib-detector.mjs +72 -0
  52. package/skill/scripts/hook-lib-events.mjs +182 -0
  53. package/skill/scripts/hook-lib-findings.mjs +201 -0
  54. package/skill/scripts/hook-lib-ignore.mjs +205 -0
  55. package/skill/scripts/hook-lib-render.mjs +273 -0
  56. package/skill/scripts/hook-lib-run.mjs +281 -0
  57. package/skill/scripts/hook-lib-scan-targets.mjs +128 -0
  58. package/skill/scripts/hook-lib.mjs +71 -1747
  59. package/skill/scripts/lib/design-parser-colors.mjs +182 -0
  60. package/skill/scripts/lib/design-parser-extract.mjs +333 -0
  61. package/skill/scripts/lib/design-parser-sections.mjs +214 -0
  62. package/skill/scripts/lib/design-parser-yaml.mjs +135 -0
  63. package/skill/scripts/lib/design-parser.mjs +10 -783
  64. package/skill/scripts/live/manual-apply-chunk.mjs +151 -0
  65. package/skill/scripts/live/manual-apply-compact.mjs +122 -0
  66. package/skill/scripts/live/manual-apply-evidence.mjs +115 -0
  67. package/skill/scripts/live/manual-apply-log.mjs +179 -0
  68. package/skill/scripts/live/manual-apply-transaction.mjs +122 -0
  69. package/skill/scripts/live/manual-apply.mjs +65 -640
  70. package/skill/scripts/live/svelte-component-accept.mjs +248 -0
  71. package/skill/scripts/live/svelte-component-css.mjs +230 -0
  72. package/skill/scripts/live/svelte-component-markup.mjs +104 -0
  73. package/skill/scripts/live/svelte-component-scaffold.mjs +118 -0
  74. package/skill/scripts/live/svelte-component-session.mjs +158 -0
  75. package/skill/scripts/live/svelte-component.mjs +32 -792
  76. package/skill/scripts/live-accept-mutate.mjs +152 -0
  77. package/skill/scripts/live-accept-parse.mjs +370 -0
  78. package/skill/scripts/live-accept-scrub.mjs +59 -0
  79. package/skill/scripts/live-accept-search.mjs +58 -0
  80. package/skill/scripts/live-accept.mjs +15 -631
  81. package/skill/scripts/live-commit-manual-edits-paths.mjs +27 -0
  82. package/skill/scripts/live-commit-manual-edits-repair.mjs +166 -0
  83. package/skill/scripts/live-commit-manual-edits-rollback.mjs +231 -0
  84. package/skill/scripts/live-commit-manual-edits-utils.mjs +167 -0
  85. package/skill/scripts/live-commit-manual-edits-verify.mjs +356 -0
  86. package/skill/scripts/live-commit-manual-edits.mjs +24 -881
  87. package/skill/scripts/live-copy-edit-agent.mjs +16 -551
  88. package/skill/scripts/live-copy-edit-compact.mjs +137 -0
  89. package/skill/scripts/live-copy-edit-post-apply.mjs +175 -0
  90. package/skill/scripts/live-copy-edit-runners.mjs +297 -0
  91. package/skill/scripts/live-inject-csp.mjs +132 -0
  92. package/skill/scripts/live-inject-files.mjs +229 -0
  93. package/skill/scripts/live-inject-tag.mjs +114 -0
  94. package/skill/scripts/live-inject.mjs +13 -440
  95. package/skill/scripts/live-server-poll.mjs +232 -0
  96. package/skill/scripts/live-server-routes.mjs +449 -0
  97. package/skill/scripts/live-server-state.mjs +361 -0
  98. package/skill/scripts/live-server.mjs +10 -946
  99. package/skill/scripts/live-wrap-css.mjs +132 -0
  100. package/skill/scripts/live-wrap-manual-edit.mjs +153 -0
  101. package/skill/scripts/live-wrap-search.mjs +247 -0
  102. package/skill/scripts/live-wrap.mjs +21 -484
  103. package/skill/scripts/palette-seeds.mjs +401 -0
  104. package/skill/scripts/palette.mjs +1 -395
@@ -21,7 +21,27 @@ import {
21
21
  shouldUseSvelteComponentInjection,
22
22
  } from './live/svelte-component.mjs';
23
23
 
24
- const EXTENSIONS = ['.html', '.jsx', '.tsx', '.vue', '.svelte', '.astro'];
24
+ import {
25
+ argVal,
26
+ pendingEntriesThatMayAffectWrap,
27
+ manualEditMayAffectWrap,
28
+ applyBufferedManualEditToLines,
29
+ } from './live-wrap-manual-edit.mjs';
30
+ import {
31
+ buildSearchQueries,
32
+ detectCommentSyntax,
33
+ detectStyleMode,
34
+ buildCssSelectorPrefixExamples,
35
+ buildCssAuthoring,
36
+ } from './live-wrap-css.mjs';
37
+ import {
38
+ findFileWithQuery,
39
+ minLeadingSpaces,
40
+ findElement,
41
+ findAllElements,
42
+ filterByText,
43
+ findClosingLine,
44
+ } from './live-wrap-search.mjs';
25
45
 
26
46
  export async function wrapCli() {
27
47
  const args = process.argv.slice(2);
@@ -380,489 +400,6 @@ The agent should insert variant HTML at insertLine.`);
380
400
  }));
381
401
  }
382
402
 
383
- // ---------------------------------------------------------------------------
384
- // Helpers
385
- // ---------------------------------------------------------------------------
386
-
387
- function argVal(args, flag) {
388
- const prefix = `${flag}=`;
389
- for (const arg of args) {
390
- if (arg.startsWith(prefix)) return arg.slice(prefix.length);
391
- }
392
- const idx = args.indexOf(flag);
393
- return idx !== -1 && idx + 1 < args.length ? args[idx + 1] : null;
394
- }
395
-
396
- function pendingEntriesThatMayAffectWrap(entries, targetFile, originalLines, selectionStartLine, cwd) {
397
- const targetAbs = path.resolve(cwd, targetFile);
398
- return (entries || []).filter((entry) => {
399
- return (entry.ops || []).some((op) => {
400
- return manualEditMayAffectWrap(op, targetAbs, originalLines, selectionStartLine, cwd);
401
- });
402
- });
403
- }
404
-
405
- function manualEditMayAffectWrap(op, targetFile, originalLines, selectionStartLine, cwd) {
406
- const targetAbs = path.resolve(cwd, targetFile);
407
- if (manualEditHintFallsInsideSelection(op, targetAbs, originalLines, selectionStartLine, cwd)) return true;
408
- if (manualEditLocatorMatchesSelection(op, originalLines)) return true;
409
- if (typeof op?.originalText === 'string' && op.originalText.length > 0) {
410
- return originalLines.join('\n').includes(op.originalText);
411
- }
412
- return false;
413
- }
414
-
415
- function manualEditHintFallsInsideSelection(op, targetAbs, originalLines, selectionStartLine, cwd) {
416
- const hintFile = op?.sourceHint?.file;
417
- const hintedLine = Number(op?.sourceHint?.line);
418
- if (!hintFile || !Number.isFinite(hintedLine)) return false;
419
- const hintAbs = path.isAbsolute(hintFile) ? hintFile : path.resolve(cwd, hintFile);
420
- if (path.resolve(hintAbs) !== targetAbs) return false;
421
- const hintedIndex = hintedLine - 1 - selectionStartLine;
422
- return hintedIndex >= 0
423
- && hintedIndex < originalLines.length
424
- && typeof op?.originalText === 'string'
425
- && originalLines[hintedIndex].includes(op.originalText);
426
- }
427
-
428
- function manualEditLocatorMatchesSelection(op, originalLines) {
429
- if (!op || typeof op.originalText !== 'string' || op.originalText.length === 0) return false;
430
- return originalLines.some((line) => (
431
- line.includes(op.originalText) && lineMatchesManualEditLocator(line, op)
432
- ));
433
- }
434
-
435
- function applyBufferedManualEditToLines(originalLines, selectionStartLine, op) {
436
- if (
437
- !op
438
- || typeof op.originalText !== 'string'
439
- || op.originalText.length === 0
440
- || typeof op.newText !== 'string'
441
- ) {
442
- return { lines: originalLines, changed: false };
443
- }
444
-
445
- const replaceLine = (lineIndex) => ({
446
- lines: originalLines.map((line, index) => (
447
- index === lineIndex ? replaceOnce(line, op.originalText, op.newText) : line
448
- )),
449
- changed: true,
450
- });
451
-
452
- const hintedLine = Number(op.sourceHint?.line);
453
- if (Number.isFinite(hintedLine)) {
454
- const hintedIndex = hintedLine - 1 - selectionStartLine;
455
- if (hintedIndex >= 0 && hintedIndex < originalLines.length && originalLines[hintedIndex].includes(op.originalText)) {
456
- return replaceLine(hintedIndex);
457
- }
458
- }
459
-
460
- const locatorMatches = [];
461
- for (let index = 0; index < originalLines.length; index += 1) {
462
- const line = originalLines[index];
463
- if (!line.includes(op.originalText)) continue;
464
- if (!lineMatchesManualEditLocator(line, op)) continue;
465
- locatorMatches.push(index);
466
- }
467
- if (locatorMatches.length === 1) return replaceLine(locatorMatches[0]);
468
-
469
- const originalBlock = originalLines.join('\n');
470
- if (countOccurrences(originalBlock, op.originalText) === 1) {
471
- return {
472
- lines: replaceOnce(originalBlock, op.originalText, op.newText).split('\n'),
473
- changed: true,
474
- };
475
- }
476
-
477
- return { lines: originalLines, changed: false };
478
- }
479
-
480
- function lineMatchesManualEditLocator(line, op) {
481
- if (op.tag) {
482
- const tagRe = new RegExp(`<\\s*${escapeRegExp(op.tag)}(?=[\\s>/]|$)`, 'i');
483
- if (!tagRe.test(line)) return false;
484
- }
485
-
486
- if (op.elementId) {
487
- const id = escapeRegExp(op.elementId);
488
- const idRe = new RegExp(`\\bid\\s*=\\s*["']${id}["']`);
489
- if (!idRe.test(line)) return false;
490
- }
491
-
492
- const classes = Array.isArray(op.classes) ? op.classes.filter(Boolean) : [];
493
- for (const className of classes) {
494
- if (!line.includes(className)) return false;
495
- }
496
-
497
- return true;
498
- }
499
-
500
- function replaceOnce(value, needle, replacement) {
501
- const index = value.indexOf(needle);
502
- if (index === -1) return value;
503
- return value.slice(0, index) + replacement + value.slice(index + needle.length);
504
- }
505
-
506
- function countOccurrences(value, needle) {
507
- if (!needle) return 0;
508
- let count = 0;
509
- let index = 0;
510
- while (true) {
511
- index = value.indexOf(needle, index);
512
- if (index === -1) return count;
513
- count += 1;
514
- index += needle.length;
515
- }
516
- }
517
-
518
- function escapeRegExp(value) {
519
- return String(value).replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
520
- }
521
-
522
- /**
523
- * Build search query strings in priority order (most specific first).
524
- * ID is most reliable, then specific class combos, then single classes, then raw query.
525
- */
526
- function buildSearchQueries(elementId, classes, tag, query) {
527
- const queries = [];
528
-
529
- // 1. ID is the most specific
530
- if (elementId) {
531
- queries.push(`id="${elementId}"`);
532
- }
533
-
534
- // 2. Full class attribute match (for elements with distinctive multi-class combos).
535
- // Emit both class="..." (HTML) and className="..." (React/JSX) so whichever
536
- // convention the file uses will match.
537
- if (classes) {
538
- const classList = splitClassList(classes);
539
- if (classList.length > 1) {
540
- const joined = classList.join(' ');
541
- const sorted = [...classList].sort((a, b) => b.length - a.length);
542
- queries.push(`class="${joined}"`);
543
- queries.push(`className="${joined}"`);
544
- for (const className of sorted) {
545
- queries.push(className);
546
- }
547
- } else if (classList.length === 1) {
548
- queries.push(classList[0]);
549
- }
550
- }
551
-
552
- // 3. Tag + class combo (e.g., <section class="hero">).
553
- // Same dual-emit for JSX compatibility.
554
- if (tag && classes) {
555
- const firstClass = splitClassList(classes)[0];
556
- queries.push(`<${tag} class="${firstClass}`);
557
- queries.push(`<${tag} className="${firstClass}`);
558
- }
559
-
560
- // 4. Raw fallback query
561
- if (query) {
562
- queries.push(query);
563
- }
564
-
565
- return queries;
566
- }
567
-
568
- function splitClassList(classes) {
569
- return String(classes).split(/[,\s]+/).map(c => c.trim()).filter(Boolean);
570
- }
571
-
572
- function detectCommentSyntax(filePath) {
573
- const ext = path.extname(filePath).toLowerCase();
574
- if (ext === '.jsx' || ext === '.tsx') {
575
- return { open: '{/*', close: '*/}' };
576
- }
577
- // HTML, Vue, Svelte, Astro all use HTML comments
578
- return { open: '<!--', close: '-->' };
579
- }
580
-
581
- function detectStyleMode(filePath) {
582
- const ext = path.extname(filePath).toLowerCase();
583
- if (ext === '.astro') {
584
- return {
585
- mode: 'astro-global-prefixed',
586
- styleTag: '<style is:inline data-monodesign-css="SESSION_ID">',
587
- };
588
- }
589
- return {
590
- mode: 'scoped',
591
- styleTag: '<style data-monodesign-css="SESSION_ID">',
592
- };
593
- }
594
-
595
- function buildCssSelectorPrefixExamples(styleMode, count) {
596
- if (styleMode !== 'astro-global-prefixed') return [];
597
- return Array.from({ length: count }, (_, i) => `[data-monodesign-variant="${i + 1}"]`);
598
- }
599
-
600
- function buildCssAuthoring(styleMode, count) {
601
- const variantNumbers = Array.from({ length: count }, (_, i) => i + 1);
602
- if (styleMode.mode === 'astro-global-prefixed') {
603
- return {
604
- mode: styleMode.mode,
605
- styleTag: styleMode.styleTag,
606
- strategy: 'global-prefixed',
607
- rulePattern: '[data-monodesign-variant="N"] > .variant-class { ... }',
608
- selectorExamples: variantNumbers.map((n) => `[data-monodesign-variant="${n}"] > .variant-class`),
609
- requirements: [
610
- 'Use the styleTag exactly; the is:inline attribute is required for this file.',
611
- 'Put raw CSS directly between the styleTag opening and a plain </style> close.',
612
- 'Prefix every preview selector with the matching [data-monodesign-variant="N"] selector.',
613
- 'Keep selectors anchored to the generated variant wrapper; do not rely on component CSS scoping for preview rules.',
614
- ],
615
- forbidden: [
616
- 'Do not use @scope for this styleMode.',
617
- 'Do not wrap style content in a JSX/TSX template literal ({` ... `}); that syntax is for .tsx/.jsx only.',
618
- 'Do not put { immediately after the style opening tag; Astro parses { as expression syntax.',
619
- ],
620
- };
621
- }
622
- return {
623
- mode: styleMode.mode,
624
- styleTag: styleMode.styleTag,
625
- strategy: 'scope-rule',
626
- rulePattern: '@scope ([data-monodesign-variant="N"]) { :scope > .variant-class { ... } }',
627
- selectorExamples: variantNumbers.map((n) => `@scope ([data-monodesign-variant="${n}"]) { :scope > .variant-class { ... } }`),
628
- requirements: [
629
- 'Use @scope blocks keyed to each [data-monodesign-variant="N"] wrapper.',
630
- 'Inside each @scope block, make :scope rules step into the replacement element with a descendant combinator.',
631
- 'Use the styleTag exactly; do not add framework-specific style attributes unless this object says to.',
632
- ],
633
- forbidden: [
634
- 'Do not use global [data-monodesign-variant="N"] selector prefixes for this styleMode.',
635
- 'Do not add is:inline to the style tag for this styleMode.',
636
- ],
637
- };
638
- }
639
-
640
- /**
641
- * Search project files for the query string (class name, ID, etc.)
642
- * Returns the first matching file path, or null.
643
- */
644
- function findFileWithQuery(query, cwd, genOpts = {}) {
645
- const searchDirs = ['src', 'app', 'pages', 'components', 'public', 'views', 'templates', '.'];
646
- const seen = new Set();
647
-
648
- for (const dir of searchDirs) {
649
- const absDir = path.join(cwd, dir);
650
- if (!fs.existsSync(absDir)) continue;
651
- const result = searchDir(absDir, query, seen, 0, genOpts);
652
- if (result) return result;
653
- }
654
- return null;
655
- }
656
-
657
- function searchDir(dir, query, seen, depth, genOpts) {
658
- if (depth > 5) return null; // don't go too deep
659
- const realDir = fs.realpathSync(dir);
660
- if (seen.has(realDir)) return null;
661
- seen.add(realDir);
662
-
663
- let entries;
664
- try { entries = fs.readdirSync(dir, { withFileTypes: true }); }
665
- catch { return null; }
666
-
667
- // Check files first
668
- for (const entry of entries) {
669
- if (!entry.isFile()) continue;
670
- const ext = path.extname(entry.name).toLowerCase();
671
- if (!EXTENSIONS.includes(ext)) continue;
672
-
673
- const filePath = path.join(dir, entry.name);
674
- if (!genOpts.includeGenerated && isGeneratedFile(filePath, genOpts)) continue;
675
- try {
676
- const content = fs.readFileSync(filePath, 'utf-8');
677
- if (content.includes(query)) return filePath;
678
- } catch { /* skip unreadable files */ }
679
- }
680
-
681
- // Then recurse into directories. Always skip node_modules and .git (never
682
- // project content). dist/build/out are left to the isGeneratedFile guard so
683
- // the includeGenerated second-pass can still find the element there and
684
- // report `generatedMatch`.
685
- for (const entry of entries) {
686
- if (!entry.isDirectory()) continue;
687
- if (entry.name === 'node_modules' || entry.name === '.git') continue;
688
- const result = searchDir(path.join(dir, entry.name), query, seen, depth + 1, genOpts);
689
- if (result) return result;
690
- }
691
-
692
- return null;
693
- }
694
-
695
- /**
696
- * Regex that matches a tag opener on a line. Allows the tag name to be
697
- * followed by whitespace, `>`, `/`, or end-of-line so that multi-line JSX
698
- * openers (e.g. `<section\n className="..."\n>`) are recognised.
699
- */
700
- const OPENER_RE = /<([A-Za-z][A-Za-z0-9]*)(?=[\s/>]|$)/;
701
-
702
- /**
703
- * Find the element's start and end line in the file.
704
- *
705
- * `query` is a class name, attribute fragment (`class="..."`, `className="..."`,
706
- * `id="..."`), or a raw text snippet. Because a query can appear on a
707
- * continuation line of a multi-line tag (e.g. the `className="..."` row of a
708
- * `<section\n className="..."\n>` JSX tag), we walk backward from the match
709
- * line to find the actual tag opener. When `tag` is provided, opener candidates
710
- * must match that tag name.
711
- */
712
- /**
713
- * Return the smallest leading-whitespace count across a set of lines,
714
- * ignoring blank lines (whose indent isn't load-bearing). Used to compute
715
- * the common base indent of a multi-line picked element so reindenting
716
- * under the wrapper preserves the relative depth between lines.
717
- */
718
- function minLeadingSpaces(lines) {
719
- let min = Infinity;
720
- for (const l of lines) {
721
- if (l.trim() === '') continue;
722
- const m = l.match(/^(\s*)/);
723
- if (m && m[1].length < min) min = m[1].length;
724
- }
725
- return min === Infinity ? 0 : min;
726
- }
727
-
728
- function findElement(lines, query, tag = null) {
729
- // Iterate all matches — the first substring hit isn't always the right one.
730
- for (let i = 0; i < lines.length; i++) {
731
- if (!lines[i].includes(query)) continue;
732
-
733
- const stripped = lines[i].trim();
734
- if (stripped.startsWith('<!--') || stripped.startsWith('{/*') || stripped.startsWith('//')) continue;
735
- // Skip lines already inside a variant wrapper
736
- if (lines[i].includes('data-monodesign-variant')) continue;
737
-
738
- const openerLine = findOpenerLine(lines, i, tag);
739
- if (openerLine === -1) continue;
740
-
741
- const endLine = findClosingLine(lines, openerLine);
742
- return { startLine: openerLine, endLine };
743
- }
744
-
745
- return null;
746
- }
747
-
748
- /**
749
- * Like findElement, but returns every match. Used for ambiguity detection
750
- * when the agent passes --text: when the same className appears on multiple
751
- * sibling elements (a list of cards, repeated section variants, etc.),
752
- * first-match silently lands on the wrong branch. Returning all matches lets
753
- * the caller narrow by textContent or fail with a structured ambiguity error.
754
- */
755
- function findAllElements(lines, query, tag = null) {
756
- const out = [];
757
- const seen = new Set();
758
- for (let i = 0; i < lines.length; i++) {
759
- if (!lines[i].includes(query)) continue;
760
- const stripped = lines[i].trim();
761
- if (stripped.startsWith('<!--') || stripped.startsWith('{/*') || stripped.startsWith('//')) continue;
762
- if (lines[i].includes('data-monodesign-variant')) continue;
763
- const openerLine = findOpenerLine(lines, i, tag);
764
- if (openerLine === -1) continue;
765
- if (seen.has(openerLine)) continue; // multiple matches inside the same element
766
- seen.add(openerLine);
767
- const endLine = findClosingLine(lines, openerLine);
768
- out.push({ startLine: openerLine, endLine });
769
- }
770
- return out;
771
- }
772
-
773
- /**
774
- * Narrow a candidate set to those whose source body matches a meaningful
775
- * prefix of the picked element's textContent. The compare strips tags and
776
- * JSX expressions, then checks two whitespace normalizations side-by-side:
777
- *
778
- * - single-space ("hero two second card body")
779
- * - no-whitespace ("herotwosecondcardbody")
780
- *
781
- * Both are needed because `el.textContent` concatenates sibling text without
782
- * inserting whitespace (e.g. `<h1>Hero Two</h1><p>Second…</p>` reads as
783
- * `"Hero TwoSecond…"`), while the source has whitespace between tags. If
784
- * EITHER normalization matches, the candidate keeps. A snippet shorter than
785
- * 8 chars after stripping is too weak to disambiguate — the caller falls
786
- * back to first-match.
787
- */
788
- function filterByText(candidates, lines, text) {
789
- const trimmed = text.replace(/\s+/g, ' ').trim().toLowerCase().slice(0, 80);
790
- // Too short to disambiguate. Return [] so the caller's `filtered.length
791
- // === 0` branch fires (fall back to first-match) — the previous
792
- // `candidates.slice()` return forced `filtered.length > 1` and surfaced
793
- // a spurious `element_ambiguous` error on every short-text picker event
794
- // with multiple candidates.
795
- if (trimmed.length < 8) return [];
796
- const targetSpaced = trimmed;
797
- const targetCompact = trimmed.replace(/\s+/g, '');
798
-
799
- return candidates.filter((c) => {
800
- const body = lines.slice(c.startLine, c.endLine + 1).join(' ');
801
- const inner = body
802
- .replace(/<[^>]*>/g, ' ') // strip HTML/JSX tags
803
- .replace(/\{[^}]*\}/g, ' ') // strip JSX expressions
804
- .toLowerCase();
805
- const sourceSpaced = inner.replace(/\s+/g, ' ').trim();
806
- const sourceCompact = inner.replace(/\s+/g, '');
807
- return sourceSpaced.includes(targetSpaced) || sourceCompact.includes(targetCompact);
808
- });
809
- }
810
-
811
- /**
812
- * Resolve a match line to the real tag opener. If the match line itself opens
813
- * a tag, return it. Otherwise walk up to 10 lines backward looking for the
814
- * first tag opener. If `tag` is specified, the opener must match that tag
815
- * name; an opener with a different tag name aborts the backward walk for this
816
- * match (we don't jump across element boundaries).
817
- *
818
- * Returns the line index of the opener, or -1 if none can be resolved.
819
- */
820
- function findOpenerLine(lines, matchLine, tag) {
821
- const self = lines[matchLine].match(OPENER_RE);
822
- if (self) {
823
- if (!tag || self[1] === tag) return matchLine;
824
- return -1;
825
- }
826
- const MAX_BACKWALK = 10;
827
- for (let i = matchLine - 1; i >= Math.max(0, matchLine - MAX_BACKWALK); i--) {
828
- const opener = lines[i].match(OPENER_RE);
829
- if (!opener) continue;
830
- if (!tag || opener[1] === tag) return i;
831
- // Different tag name than requested — abort; we're inside a non-target opener.
832
- return -1;
833
- }
834
- return -1;
835
- }
836
-
837
- /**
838
- * Starting from a line with an opening tag, find the line with the matching
839
- * closing tag by counting tag nesting depth.
840
- */
841
- function findClosingLine(lines, start) {
842
- const openMatch = lines[start].match(OPENER_RE);
843
- if (!openMatch) return start; // caller passed a non-opener; nothing to span
844
-
845
- const tagName = openMatch[1];
846
- let depth = 0;
847
- const openRe = new RegExp(`<${tagName}(?=[\\s/>]|$)`, 'g');
848
- const selfCloseRe = new RegExp(`<${tagName}[^>]*/>`, 'g');
849
- const closeRe = new RegExp(`</${tagName}\\s*>`, 'g');
850
-
851
- for (let i = start; i < lines.length; i++) {
852
- const line = lines[i];
853
- const opens = (line.match(openRe) || []).length;
854
- const selfCloses = (line.match(selfCloseRe) || []).length;
855
- const closes = (line.match(closeRe) || []).length;
856
-
857
- depth += opens - selfCloses - closes;
858
-
859
- if (depth <= 0) return i;
860
- }
861
-
862
- // If we can't find the close, return a reasonable guess
863
- return Math.min(start + 50, lines.length - 1);
864
- }
865
-
866
403
  // Auto-execute when run directly (node live-wrap.mjs ...)
867
404
  const _running = process.argv[1];
868
405
  if (_running?.endsWith('live-wrap.mjs') || _running?.endsWith('live-wrap.mjs/')) {