@monoes/monomindcli 2.16.1 → 2.16.2

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 (214) hide show
  1. package/.claude/helpers/handlers/edit-handler.cjs +14 -12
  2. package/.claude/helpers/handlers/route-handler.cjs +6 -0
  3. package/.claude/helpers/monograph-freshen.cjs +31 -113
  4. package/.claude/helpers/utils/monograph-resolve.cjs +497 -0
  5. package/.claude/helpers/utils/monograph.cjs +8 -51
  6. package/README.md +1 -1
  7. package/dist/src/commands/doctor-hook-monograph-checks.d.ts +8 -0
  8. package/dist/src/commands/doctor-hook-monograph-checks.d.ts.map +1 -0
  9. package/dist/src/commands/doctor-hook-monograph-checks.js +79 -0
  10. package/dist/src/commands/doctor-hook-monograph-checks.js.map +1 -0
  11. package/dist/src/commands/doctor.d.ts.map +1 -1
  12. package/dist/src/commands/doctor.js +4 -1
  13. package/dist/src/commands/doctor.js.map +1 -1
  14. package/dist/src/commands/monograph.d.ts.map +1 -1
  15. package/dist/src/commands/monograph.js +16 -1
  16. package/dist/src/commands/monograph.js.map +1 -1
  17. package/dist/src/orgrt/bash-timeout.d.ts +14 -0
  18. package/dist/src/orgrt/bash-timeout.d.ts.map +1 -0
  19. package/dist/src/orgrt/bash-timeout.js +18 -0
  20. package/dist/src/orgrt/bash-timeout.js.map +1 -0
  21. package/dist/src/orgrt/block-recheck.d.ts +30 -0
  22. package/dist/src/orgrt/block-recheck.d.ts.map +1 -0
  23. package/dist/src/orgrt/block-recheck.js +81 -0
  24. package/dist/src/orgrt/block-recheck.js.map +1 -0
  25. package/dist/src/orgrt/completion-gate.d.ts +4 -0
  26. package/dist/src/orgrt/completion-gate.d.ts.map +1 -1
  27. package/dist/src/orgrt/completion-gate.js +22 -2
  28. package/dist/src/orgrt/completion-gate.js.map +1 -1
  29. package/dist/src/orgrt/daemon.d.ts.map +1 -1
  30. package/dist/src/orgrt/daemon.js +6 -4
  31. package/dist/src/orgrt/daemon.js.map +1 -1
  32. package/dist/src/orgrt/decisions.d.ts +1 -1
  33. package/dist/src/orgrt/decisions.d.ts.map +1 -1
  34. package/dist/src/orgrt/decisions.js +14 -6
  35. package/dist/src/orgrt/decisions.js.map +1 -1
  36. package/dist/src/orgrt/mailbox.d.ts +14 -0
  37. package/dist/src/orgrt/mailbox.d.ts.map +1 -1
  38. package/dist/src/orgrt/mailbox.js +31 -1
  39. package/dist/src/orgrt/mailbox.js.map +1 -1
  40. package/dist/src/orgrt/sandbox-fault.d.ts +16 -6
  41. package/dist/src/orgrt/sandbox-fault.d.ts.map +1 -1
  42. package/dist/src/orgrt/sandbox-fault.js +78 -33
  43. package/dist/src/orgrt/sandbox-fault.js.map +1 -1
  44. package/dist/src/orgrt/session.d.ts +4 -3
  45. package/dist/src/orgrt/session.d.ts.map +1 -1
  46. package/dist/src/orgrt/session.js +24 -13
  47. package/dist/src/orgrt/session.js.map +1 -1
  48. package/dist/src/orgrt/task-dag.d.ts +8 -2
  49. package/dist/src/orgrt/task-dag.d.ts.map +1 -1
  50. package/dist/src/orgrt/task-dag.js +10 -4
  51. package/dist/src/orgrt/task-dag.js.map +1 -1
  52. package/dist/src/orgrt/types.d.ts +11 -0
  53. package/dist/src/orgrt/types.d.ts.map +1 -1
  54. package/dist/src/orgrt/types.js +18 -0
  55. package/dist/src/orgrt/types.js.map +1 -1
  56. package/dist/src/utils/resource-governor.d.ts.map +1 -1
  57. package/dist/src/utils/resource-governor.js +35 -2
  58. package/dist/src/utils/resource-governor.js.map +1 -1
  59. package/dist/tsconfig.tsbuildinfo +1 -1
  60. package/package.json +6 -6
  61. package/.claude/skills/monodesign/SKILL.md +0 -257
  62. package/.claude/skills/monodesign/adapt.md +0 -53
  63. package/.claude/skills/monodesign/agents/monodesign-asset-producer.md +0 -100
  64. package/.claude/skills/monodesign/agents/monodesign-manual-edit-applier.md +0 -103
  65. package/.claude/skills/monodesign/animate.md +0 -65
  66. package/.claude/skills/monodesign/audit.md +0 -89
  67. package/.claude/skills/monodesign/bolder.md +0 -50
  68. package/.claude/skills/monodesign/clarify.md +0 -64
  69. package/.claude/skills/monodesign/colorize.md +0 -68
  70. package/.claude/skills/monodesign/craft.md +0 -51
  71. package/.claude/skills/monodesign/critique.md +0 -66
  72. package/.claude/skills/monodesign/delight.md +0 -47
  73. package/.claude/skills/monodesign/distill.md +0 -56
  74. package/.claude/skills/monodesign/document.md +0 -83
  75. package/.claude/skills/monodesign/extract.md +0 -74
  76. package/.claude/skills/monodesign/harden.md +0 -65
  77. package/.claude/skills/monodesign/init.md +0 -30
  78. package/.claude/skills/monodesign/layout.md +0 -36
  79. package/.claude/skills/monodesign/live.md +0 -34
  80. package/.claude/skills/monodesign/onboard.md +0 -50
  81. package/.claude/skills/monodesign/optimize.md +0 -64
  82. package/.claude/skills/monodesign/overdrive.md +0 -56
  83. package/.claude/skills/monodesign/polish.md +0 -68
  84. package/.claude/skills/monodesign/quieter.md +0 -57
  85. package/.claude/skills/monodesign/reference/adapt.md +0 -312
  86. package/.claude/skills/monodesign/reference/adapt.native.md +0 -58
  87. package/.claude/skills/monodesign/reference/android.md +0 -40
  88. package/.claude/skills/monodesign/reference/animate.md +0 -203
  89. package/.claude/skills/monodesign/reference/antipatterns-catalog.md +0 -410
  90. package/.claude/skills/monodesign/reference/audit.md +0 -135
  91. package/.claude/skills/monodesign/reference/audit.native.md +0 -139
  92. package/.claude/skills/monodesign/reference/bolder.md +0 -120
  93. package/.claude/skills/monodesign/reference/brand-workflow.md +0 -180
  94. package/.claude/skills/monodesign/reference/brand.md +0 -108
  95. package/.claude/skills/monodesign/reference/clarify.md +0 -288
  96. package/.claude/skills/monodesign/reference/codex.md +0 -105
  97. package/.claude/skills/monodesign/reference/cognitive-load.md +0 -106
  98. package/.claude/skills/monodesign/reference/color-and-contrast.md +0 -105
  99. package/.claude/skills/monodesign/reference/colorize.md +0 -257
  100. package/.claude/skills/monodesign/reference/component-specs.md +0 -260
  101. package/.claude/skills/monodesign/reference/component-states.md +0 -274
  102. package/.claude/skills/monodesign/reference/component-system.md +0 -358
  103. package/.claude/skills/monodesign/reference/copy-formulas.md +0 -160
  104. package/.claude/skills/monodesign/reference/craft.md +0 -123
  105. package/.claude/skills/monodesign/reference/critique.md +0 -780
  106. package/.claude/skills/monodesign/reference/delight.md +0 -302
  107. package/.claude/skills/monodesign/reference/design-principles.md +0 -246
  108. package/.claude/skills/monodesign/reference/distill.md +0 -111
  109. package/.claude/skills/monodesign/reference/document.md +0 -429
  110. package/.claude/skills/monodesign/reference/extract.md +0 -69
  111. package/.claude/skills/monodesign/reference/harden.md +0 -347
  112. package/.claude/skills/monodesign/reference/heuristics-scoring.md +0 -234
  113. package/.claude/skills/monodesign/reference/hooks.md +0 -92
  114. package/.claude/skills/monodesign/reference/image-prompts.md +0 -130
  115. package/.claude/skills/monodesign/reference/init.md +0 -221
  116. package/.claude/skills/monodesign/reference/interaction-design.md +0 -189
  117. package/.claude/skills/monodesign/reference/ios.md +0 -45
  118. package/.claude/skills/monodesign/reference/layout.md +0 -185
  119. package/.claude/skills/monodesign/reference/live.md +0 -710
  120. package/.claude/skills/monodesign/reference/motion-design.md +0 -109
  121. package/.claude/skills/monodesign/reference/onboard.md +0 -234
  122. package/.claude/skills/monodesign/reference/optimize.md +0 -258
  123. package/.claude/skills/monodesign/reference/overdrive.md +0 -130
  124. package/.claude/skills/monodesign/reference/personas.md +0 -179
  125. package/.claude/skills/monodesign/reference/polish.md +0 -241
  126. package/.claude/skills/monodesign/reference/pre-delivery-checklist.md +0 -108
  127. package/.claude/skills/monodesign/reference/product.md +0 -60
  128. package/.claude/skills/monodesign/reference/quieter.md +0 -99
  129. package/.claude/skills/monodesign/reference/responsive-design.md +0 -114
  130. package/.claude/skills/monodesign/reference/shape.md +0 -165
  131. package/.claude/skills/monodesign/reference/spatial-design.md +0 -100
  132. package/.claude/skills/monodesign/reference/teach.md +0 -10
  133. package/.claude/skills/monodesign/reference/token-architecture.md +0 -222
  134. package/.claude/skills/monodesign/reference/typeset.md +0 -301
  135. package/.claude/skills/monodesign/reference/typography.md +0 -159
  136. package/.claude/skills/monodesign/reference/ux-research.md +0 -143
  137. package/.claude/skills/monodesign/reference/ux-rules.md +0 -211
  138. package/.claude/skills/monodesign/reference/ux-writing.md +0 -107
  139. package/.claude/skills/monodesign/scripts/command-metadata.json +0 -94
  140. package/.claude/skills/monodesign/scripts/context-signals.mjs +0 -260
  141. package/.claude/skills/monodesign/scripts/context.mjs +0 -1065
  142. package/.claude/skills/monodesign/scripts/critique-storage.mjs +0 -416
  143. package/.claude/skills/monodesign/scripts/detect-csp.mjs +0 -193
  144. package/.claude/skills/monodesign/scripts/detect.mjs +0 -33
  145. package/.claude/skills/monodesign/scripts/detector/browser/injected/index.mjs +0 -1960
  146. package/.claude/skills/monodesign/scripts/detector/cli/main.mjs +0 -321
  147. package/.claude/skills/monodesign/scripts/detector/design-system.mjs +0 -814
  148. package/.claude/skills/monodesign/scripts/detector/detect-antipatterns-browser.js +0 -5628
  149. package/.claude/skills/monodesign/scripts/detector/detect-antipatterns.mjs +0 -50
  150. package/.claude/skills/monodesign/scripts/detector/engines/browser/detect-url.mjs +0 -259
  151. package/.claude/skills/monodesign/scripts/detector/engines/browser/drivers.mjs +0 -339
  152. package/.claude/skills/monodesign/scripts/detector/engines/regex/detect-text.mjs +0 -636
  153. package/.claude/skills/monodesign/scripts/detector/engines/static-html/css-cascade.mjs +0 -1016
  154. package/.claude/skills/monodesign/scripts/detector/engines/static-html/detect-html.mjs +0 -253
  155. package/.claude/skills/monodesign/scripts/detector/engines/visual/screenshot-contrast.mjs +0 -198
  156. package/.claude/skills/monodesign/scripts/detector/findings.mjs +0 -12
  157. package/.claude/skills/monodesign/scripts/detector/fix/css-regions.mjs +0 -181
  158. package/.claude/skills/monodesign/scripts/detector/fix/fixers.mjs +0 -373
  159. package/.claude/skills/monodesign/scripts/detector/fix/index.mjs +0 -426
  160. package/.claude/skills/monodesign/scripts/detector/node/file-system.mjs +0 -198
  161. package/.claude/skills/monodesign/scripts/detector/profile/profiler.mjs +0 -166
  162. package/.claude/skills/monodesign/scripts/detector/registry/antipatterns.mjs +0 -563
  163. package/.claude/skills/monodesign/scripts/detector/rules/checks.mjs +0 -3024
  164. package/.claude/skills/monodesign/scripts/detector/shared/color.mjs +0 -124
  165. package/.claude/skills/monodesign/scripts/detector/shared/constants.mjs +0 -101
  166. package/.claude/skills/monodesign/scripts/detector/shared/fonts.mjs +0 -30
  167. package/.claude/skills/monodesign/scripts/detector/shared/inline-ignores.mjs +0 -148
  168. package/.claude/skills/monodesign/scripts/detector/shared/page.mjs +0 -7
  169. package/.claude/skills/monodesign/scripts/hook-admin.mjs +0 -694
  170. package/.claude/skills/monodesign/scripts/hook-before-edit.mjs +0 -516
  171. package/.claude/skills/monodesign/scripts/hook-lib.mjs +0 -1785
  172. package/.claude/skills/monodesign/scripts/hook.mjs +0 -61
  173. package/.claude/skills/monodesign/scripts/lib/design-parser.mjs +0 -809
  174. package/.claude/skills/monodesign/scripts/lib/is-generated.mjs +0 -69
  175. package/.claude/skills/monodesign/scripts/lib/monodesign-config.mjs +0 -640
  176. package/.claude/skills/monodesign/scripts/lib/monodesign-paths.mjs +0 -129
  177. package/.claude/skills/monodesign/scripts/lib/provider.mjs +0 -4
  178. package/.claude/skills/monodesign/scripts/lib/target-args.mjs +0 -42
  179. package/.claude/skills/monodesign/scripts/live/browser-script-parts.mjs +0 -50
  180. package/.claude/skills/monodesign/scripts/live/completion.mjs +0 -19
  181. package/.claude/skills/monodesign/scripts/live/event-validation.mjs +0 -137
  182. package/.claude/skills/monodesign/scripts/live/insert-ui.mjs +0 -458
  183. package/.claude/skills/monodesign/scripts/live/manual-apply.mjs +0 -939
  184. package/.claude/skills/monodesign/scripts/live/manual-edit-routes.mjs +0 -357
  185. package/.claude/skills/monodesign/scripts/live/manual-edits-buffer.mjs +0 -152
  186. package/.claude/skills/monodesign/scripts/live/session-store.mjs +0 -293
  187. package/.claude/skills/monodesign/scripts/live/svelte-component.mjs +0 -826
  188. package/.claude/skills/monodesign/scripts/live/sveltekit-adapter.mjs +0 -279
  189. package/.claude/skills/monodesign/scripts/live/ui-core.mjs +0 -180
  190. package/.claude/skills/monodesign/scripts/live/vocabulary.mjs +0 -36
  191. package/.claude/skills/monodesign/scripts/live-accept.mjs +0 -812
  192. package/.claude/skills/monodesign/scripts/live-browser-dom.js +0 -147
  193. package/.claude/skills/monodesign/scripts/live-browser-session.js +0 -124
  194. package/.claude/skills/monodesign/scripts/live-browser.js +0 -11213
  195. package/.claude/skills/monodesign/scripts/live-commit-manual-edits.mjs +0 -1241
  196. package/.claude/skills/monodesign/scripts/live-complete.mjs +0 -75
  197. package/.claude/skills/monodesign/scripts/live-copy-edit-agent.mjs +0 -683
  198. package/.claude/skills/monodesign/scripts/live-discard-manual-edits.mjs +0 -51
  199. package/.claude/skills/monodesign/scripts/live-inject.mjs +0 -596
  200. package/.claude/skills/monodesign/scripts/live-insert.mjs +0 -272
  201. package/.claude/skills/monodesign/scripts/live-manual-edit-evidence.mjs +0 -363
  202. package/.claude/skills/monodesign/scripts/live-poll.mjs +0 -384
  203. package/.claude/skills/monodesign/scripts/live-resume.mjs +0 -94
  204. package/.claude/skills/monodesign/scripts/live-server.mjs +0 -1210
  205. package/.claude/skills/monodesign/scripts/live-status.mjs +0 -61
  206. package/.claude/skills/monodesign/scripts/live-target.mjs +0 -30
  207. package/.claude/skills/monodesign/scripts/live-wrap.mjs +0 -884
  208. package/.claude/skills/monodesign/scripts/live.mjs +0 -297
  209. package/.claude/skills/monodesign/scripts/modern-screenshot.umd.js +0 -14
  210. package/.claude/skills/monodesign/scripts/palette.mjs +0 -635
  211. package/.claude/skills/monodesign/scripts/pin.mjs +0 -221
  212. package/.claude/skills/monodesign/shape.md +0 -71
  213. package/.claude/skills/monodesign/teach.md +0 -18
  214. package/.claude/skills/monodesign/typeset.md +0 -59
@@ -1,884 +0,0 @@
1
- /**
2
- * CLI helper: find an element in source and wrap it in a variant container.
3
- *
4
- * Usage:
5
- * node <scripts_path>/live-wrap.mjs --id SESSION_ID --count N --query "hero-combined-left" [--file path]
6
- *
7
- * Searches project files for the element matching the query (class name, ID, or
8
- * text snippet), wraps it with the variant scaffolding, and prints the file path
9
- * + line range where the agent should insert variant HTML.
10
- *
11
- * This replaces 3-4 agent tool calls (grep + read + edit) with a single CLI call.
12
- */
13
-
14
- import fs from 'node:fs';
15
- import path from 'node:path';
16
- import { isGeneratedFile } from './lib/is-generated.mjs';
17
- import { readBuffer as readManualEditsBuffer } from './live/manual-edits-buffer.mjs';
18
- import {
19
- buildSvelteComponentCssAuthoring,
20
- scaffoldSvelteComponentSession,
21
- shouldUseSvelteComponentInjection,
22
- } from './live/svelte-component.mjs';
23
-
24
- const EXTENSIONS = ['.html', '.jsx', '.tsx', '.vue', '.svelte', '.astro'];
25
-
26
- export async function wrapCli() {
27
- const args = process.argv.slice(2);
28
-
29
- if (args.includes('--help') || args.includes('-h')) {
30
- console.log(`Usage: monodesign wrap [options]
31
-
32
- Find an element in source and wrap it in a variant container.
33
-
34
- Required:
35
- --id ID Session ID for the variant wrapper
36
- --count N Number of expected variants (1-8)
37
-
38
- Element identification (at least one required):
39
- --element-id ID HTML id attribute of the element
40
- --classes A,B,C Comma- or space-separated CSS class names
41
- --tag TAG Tag name (div, section, etc.)
42
- --query TEXT Fallback: raw text to search for
43
-
44
- Optional:
45
- --file PATH Source file to search in (skips auto-detection)
46
- --text TEXT Picked element's textContent. Used to disambiguate when
47
- classes/tag match multiple sibling elements (e.g. a list
48
- of <Card>s with the same className). Pass the first ~80
49
- chars of event.element.textContent.
50
- --page-url URL Current page URL. Required when pending manual edits may
51
- affect the picked source block. Pending edits are filtered
52
- to this page so an edit on /a doesn't bleed into /b.
53
- --help Show this help message
54
-
55
- Output (JSON):
56
- { file, startLine, endLine, insertLine, commentSyntax }
57
-
58
- The agent should insert variant HTML at insertLine.`);
59
- process.exit(0);
60
- }
61
-
62
- const id = argVal(args, '--id');
63
- // biome-ignore lint/correctness/useParseIntRadix: --count is caller-supplied CLI input; radix 10 would change how a 0x value parses
64
- const count = parseInt(argVal(args, '--count') || '3');
65
- const elementId = argVal(args, '--element-id');
66
- const classes = argVal(args, '--classes');
67
- const tag = argVal(args, '--tag');
68
- const query = argVal(args, '--query');
69
- const filePath = argVal(args, '--file');
70
- const text = argVal(args, '--text');
71
- const pageUrl = argVal(args, '--page-url');
72
-
73
- if (!id) { console.error('Missing --id'); process.exit(1); }
74
- if (!elementId && !classes && !query) {
75
- console.error('Need at least one of: --element-id, --classes, --query');
76
- process.exit(1);
77
- }
78
-
79
- // Build search queries in priority order (most specific first)
80
- const queries = buildSearchQueries(elementId, classes, tag, query);
81
-
82
- const genOpts = { cwd: process.cwd() };
83
-
84
- // Find the source file. Generated files are excluded from auto-search so we
85
- // don't silently write variants into a file the next build will wipe.
86
- let targetFile = filePath;
87
- if (!targetFile) {
88
- for (const q of queries) {
89
- targetFile = findFileWithQuery(q, process.cwd(), genOpts);
90
- if (targetFile) break;
91
- }
92
- if (!targetFile) {
93
- // Nothing in source. Did the element show up in a generated file? That
94
- // tells the agent "fall back to the agent-driven flow" vs "element just
95
- // doesn't exist in this project."
96
- let generatedHit = null;
97
- for (const q of queries) {
98
- generatedHit = findFileWithQuery(q, process.cwd(), { ...genOpts, includeGenerated: true });
99
- if (generatedHit) break;
100
- }
101
- if (generatedHit) {
102
- console.error(JSON.stringify({
103
- error: 'element_not_in_source',
104
- fallback: 'agent-driven',
105
- generatedMatch: path.relative(process.cwd(), generatedHit).split(path.sep).join('/'),
106
- hint: 'Element found only in a generated file. See "Handle fallback" in live.md.',
107
- }));
108
- } else {
109
- console.error(JSON.stringify({
110
- error: 'element_not_found',
111
- fallback: 'agent-driven',
112
- hint: 'Element not found in any project file. It may be runtime-injected (JS component, etc.). See "Handle fallback" in live.md.',
113
- }));
114
- }
115
- process.exit(1);
116
- }
117
- } else {
118
- if (isGeneratedFile(targetFile, genOpts)) {
119
- console.error(JSON.stringify({
120
- error: 'file_is_generated',
121
- fallback: 'agent-driven',
122
- file: path.relative(process.cwd(), path.resolve(process.cwd(), targetFile)).split(path.sep).join('/'),
123
- hint: 'Explicit --file points at a generated file. Writing here gets wiped by the next build. See "Handle fallback" in live.md.',
124
- }));
125
- process.exit(1);
126
- }
127
- }
128
-
129
- const content = fs.readFileSync(targetFile, 'utf-8');
130
- const lines = content.split('\n');
131
-
132
- // Find the element, trying each query in priority order. When `--text` is
133
- // supplied, collect every candidate the queries surface and disambiguate
134
- // by the picked element's textContent. Without `--text`, fall back to the
135
- // legacy first-match behavior so unmodified callers keep working.
136
- let match = null;
137
- if (text) {
138
- const candidates = [];
139
- for (const q of queries) {
140
- const all = findAllElements(lines, q, tag);
141
- for (const c of all) {
142
- if (!candidates.some((x) => x.startLine === c.startLine)) {
143
- candidates.push(c);
144
- }
145
- }
146
- // Once a more-specific query (ID, full className combo) yielded a unique
147
- // result, stop — falling through to the loose tag+single-class query
148
- // would readmit the siblings we just disambiguated past.
149
- if (candidates.length === 1) break;
150
- }
151
- if (candidates.length === 0) {
152
- console.error(JSON.stringify({ error: `Found file but could not locate element in ${targetFile}. Searched for: ${queries.join(', ')}` }));
153
- process.exit(1);
154
- }
155
- if (candidates.length === 1) {
156
- match = candidates[0];
157
- } else {
158
- const filtered = filterByText(candidates, lines, text);
159
- if (filtered.length === 1) {
160
- match = filtered[0];
161
- } else if (filtered.length === 0) {
162
- // Source uses dynamic content (`<h1>{title}</h1>` etc.) so the
163
- // browser-side textContent doesn't appear literally in source. Fall
164
- // back to first-match rather than refusing — this is the same
165
- // behavior unmodified callers see, just preserved.
166
- match = candidates[0];
167
- } else {
168
- // Multiple candidates ALSO match the text. Truly ambiguous — refuse
169
- // rather than pick wrong, and hand the agent the candidate locations
170
- // so it can disambiguate by reading the file.
171
- console.error(JSON.stringify({
172
- error: 'element_ambiguous',
173
- fallback: 'agent-driven',
174
- file: path.relative(process.cwd(), targetFile).split(path.sep).join('/'),
175
- candidates: filtered.map((c) => ({
176
- startLine: c.startLine + 1,
177
- endLine: c.endLine + 1,
178
- })),
179
- hint: 'Multiple source elements match both classes/tag and textContent. Pass --element-id, a more specific --text, or write the wrapper manually. See "Handle fallback" in live.md.',
180
- }));
181
- process.exit(1);
182
- }
183
- }
184
- } else {
185
- for (const q of queries) {
186
- match = findElement(lines, q, tag);
187
- if (match) break;
188
- }
189
- if (!match) {
190
- console.error(JSON.stringify({ error: `Found file but could not locate element in ${targetFile}. Searched for: ${queries.join(', ')}` }));
191
- process.exit(1);
192
- }
193
- }
194
-
195
- const { startLine, endLine } = match;
196
- const commentSyntax = detectCommentSyntax(targetFile);
197
- const styleMode = detectStyleMode(targetFile);
198
- const isJsx = commentSyntax.open === '{/*';
199
- const indent = lines[startLine].match(/^(\s*)/)[1];
200
-
201
- // Extract the original element. Reindent under the wrapper while preserving
202
- // the relative depth between lines — `l.trimStart()` would strip ALL leading
203
- // whitespace and collapse e.g. `<aside>`/` <h1>`/`</aside>` (6/8/6 spaces)
204
- // to a single uniform indent, so on accept/discard the round-trip restores
205
- // the inner element at its parent's depth instead of nested inside it.
206
- // Strip only the COMMON minimum leading whitespace across the picked lines;
207
- // `deindentContent` on the accept side already mirrors this convention.
208
- let originalLines = lines.slice(startLine, endLine + 1);
209
-
210
- // Buffer-aware "original" content: if the user has pending manual edits for
211
- // this page whose originalText appears in the picked source range, apply
212
- // them so the wrap block's "original" variant reflects what the user was
213
- // looking at (their edited DOM), not the raw source. Source itself stays
214
- // untouched here — only the wrap block's embedded "original" copy is
215
- // adjusted. The pending edits remain in the buffer until committed.
216
- //
217
- // Apply buffered edits only when the browser provided the current page URL.
218
- // Without it, fail if pending edits plausibly touch this exact source range;
219
- // otherwise skip buffer awareness so unrelated staged edits on another page
220
- // do not block normal wrap work.
221
- let pendingBuffer = { entries: [] };
222
- try { pendingBuffer = readManualEditsBuffer(process.cwd()); } catch {}
223
- const pendingEntriesForTarget = pageUrl
224
- ? []
225
- : pendingEntriesThatMayAffectWrap(pendingBuffer.entries, targetFile, originalLines, startLine, process.cwd());
226
- if (pendingEntriesForTarget.length > 0) {
227
- console.error(JSON.stringify({
228
- error: 'missing_page_url_with_pending_edits',
229
- pendingEntries: pendingEntriesForTarget.length,
230
- hint: 'Pending manual edits may affect the selected source block. Pass --page-url=$event.pageUrl so the wrap block reflects the user\'s staged DOM.',
231
- }));
232
- process.exit(1);
233
- }
234
- if (pageUrl) {
235
- const failedBufferedOps = [];
236
- for (const entry of pendingBuffer.entries || []) {
237
- if (entry.pageUrl !== pageUrl) continue;
238
- for (const op of entry.ops || []) {
239
- const mayAffectWrap = manualEditMayAffectWrap(op, targetFile, originalLines, startLine, process.cwd());
240
- const result = applyBufferedManualEditToLines(originalLines, startLine, op);
241
- if (result.changed) {
242
- originalLines = result.lines;
243
- continue;
244
- }
245
- if (!mayAffectWrap) continue;
246
- failedBufferedOps.push({
247
- entryId: entry.id,
248
- ref: op?.ref || null,
249
- originalText: op?.originalText || null,
250
- reason: 'ambiguous_or_unmatched_pending_edit',
251
- });
252
- }
253
- }
254
- if (failedBufferedOps.length > 0) {
255
- console.error(JSON.stringify({
256
- error: 'manual_edit_buffer_apply_failed',
257
- pendingOps: failedBufferedOps,
258
- hint: 'A staged copy edit appears to affect the selected source block, but could not be applied unambiguously to the wrap original. Apply or discard copy edits first, or write the wrapper manually.',
259
- }));
260
- process.exit(1);
261
- }
262
- }
263
-
264
- const originalBaseIndent = minLeadingSpaces(originalLines);
265
- const reindentOriginal = (extra) => originalLines
266
- .map((l) => (l.trim() === '' ? '' : indent + extra + l.slice(originalBaseIndent)))
267
- .join('\n');
268
- const originalIndented = reindentOriginal(' ');
269
- const relTargetFile = path.relative(process.cwd(), targetFile).split(path.sep).join('/');
270
- const useSvelteComponent = shouldUseSvelteComponentInjection(targetFile);
271
-
272
- // Wrapper attributes differ by syntax. HTML allows plain string attrs;
273
- // JSX requires object-literal style and parses string attrs as HTML (which
274
- // either type-errors or renders a literal CSS string).
275
- const styleContents = isJsx ? 'style={{ display: "contents" }}' : 'style="display: contents"';
276
-
277
- // JSX/TSX guard: the picked element occupies a single JSX child slot
278
- // (inside `return (...)`, an array `.map(...)`, an `asChild` branch, or
279
- // any other expression position). Replacing it with `comment + <div> +
280
- // comment` yields three adjacent siblings — invalid JSX. We can't use a
281
- // Fragment `<></>` either: parents that clone children (Radix `asChild`,
282
- // Headless UI, etc.) hit "Invalid prop supplied to React.Fragment" when
283
- // they try to pass an `id` through.
284
- //
285
- // Solution: keep the wrapper `<div>` as the single JSX-slot child and
286
- // tuck both marker comments INSIDE it. accept/discard then expands its
287
- // replacement range to include the wrapper's `<div>` open / close lines
288
- // so the entire scaffold gets removed cleanly.
289
- const wrapperLines = isJsx ? [
290
- `${indent}<div data-monodesign-variants="${id}" data-monodesign-variant-count="${count}" ${styleContents}>`,
291
- `${indent} ${commentSyntax.open} monodesign-variants-start ${id} ${commentSyntax.close}`,
292
- `${indent} ${commentSyntax.open} Original ${commentSyntax.close}`,
293
- `${indent} <div data-monodesign-variant="original">`,
294
- reindentOriginal(' '),
295
- `${indent} </div>`,
296
- `${indent} ${commentSyntax.open} Variants: insert below this line ${commentSyntax.close}`,
297
- `${indent} ${commentSyntax.open} monodesign-variants-end ${id} ${commentSyntax.close}`,
298
- `${indent}</div>`,
299
- ] : [
300
- `${indent + commentSyntax.open} monodesign-variants-start ${id} ${commentSyntax.close}`,
301
- `${indent}<div data-monodesign-variants="${id}" data-monodesign-variant-count="${count}" ${styleContents}>`,
302
- `${indent} ${commentSyntax.open} Original ${commentSyntax.close}`,
303
- `${indent} <div data-monodesign-variant="original">`,
304
- originalIndented,
305
- `${indent} </div>`,
306
- `${indent} ${commentSyntax.open} Variants: insert below this line ${commentSyntax.close}`,
307
- `${indent}</div>`,
308
- `${indent + commentSyntax.open} monodesign-variants-end ${id} ${commentSyntax.close}`,
309
- ];
310
-
311
- let outputFile = targetFile;
312
- let outputStartLine = startLine + 1;
313
- let outputEndLine = startLine + wrapperLines.length + (originalLines.length - 1);
314
- let insertLine;
315
- let svelteSession = null;
316
-
317
- if (useSvelteComponent) {
318
- // Svelte/SvelteKit resets component-local state on markup HMR updates.
319
- // Keep generation source-neutral: agents write real variant components
320
- // under the generated componentDir, the browser mounts them into the live
321
- // DOM, and live-accept.mjs inlines the accepted variant back into the route.
322
- svelteSession = scaffoldSvelteComponentSession({
323
- id,
324
- count,
325
- sourceFile: relTargetFile,
326
- sourceStartLine: startLine + 1,
327
- sourceEndLine: endLine + 1,
328
- originalLines,
329
- cwd: process.cwd(),
330
- });
331
- outputFile = path.resolve(process.cwd(), svelteSession.manifestFile);
332
- outputStartLine = 1;
333
- outputEndLine = 1;
334
- insertLine = 1;
335
- } else {
336
- // Replace the original element with the wrapper
337
- const newLines = [
338
- ...lines.slice(0, startLine),
339
- ...wrapperLines,
340
- ...lines.slice(endLine + 1),
341
- ];
342
- fs.writeFileSync(targetFile, newLines.join('\n'), 'utf-8');
343
-
344
- // Calculate insert line (the "insert below this line" comment).
345
- // 0-indexed file position. Both HTML and JSX wrappers have 6 lines above
346
- // the insert marker (HTML: start-comment + outer-div + Original-comment +
347
- // original-div + content + close-original-div; JSX: outer-div +
348
- // start-comment + Original-comment + original-div + content +
349
- // close-original-div). Multi-line originals push the marker by their
350
- // extra line count.
351
- insertLine = startLine + 6 + (originalLines.length - 1) + 1;
352
- }
353
-
354
- const outputRelFile = path.relative(process.cwd(), outputFile).split(path.sep).join('/');
355
-
356
- const svelteComponentAuthoring = useSvelteComponent ? buildSvelteComponentCssAuthoring(count) : null;
357
-
358
- console.log(JSON.stringify({
359
- file: outputRelFile,
360
- sourceFile: useSvelteComponent ? relTargetFile : undefined,
361
- previewMode: useSvelteComponent ? 'svelte-component' : undefined,
362
- componentDir: svelteSession?.componentDir,
363
- propContract: svelteSession?.propContract,
364
- sourceStartLine: useSvelteComponent ? startLine + 1 : undefined,
365
- sourceEndLine: useSvelteComponent ? endLine + 1 : undefined,
366
- startLine: outputStartLine, // 1-indexed for the agent
367
- // wrapperLines is an array but one element (the original-content slot)
368
- // is a `\n`-joined multi-line string, so the actual file-row count is
369
- // wrapperLines.length + (originalLines.length - 1). Without the offset,
370
- // endLine pointed inside the wrapper for any picked element that
371
- // spanned more than one source line.
372
- endLine: outputEndLine, // 1-indexed
373
- insertLine, // 1-indexed: where variants go
374
- commentSyntax: commentSyntax,
375
- styleMode: useSvelteComponent ? 'svelte-component' : styleMode.mode,
376
- styleTag: useSvelteComponent ? null : styleMode.styleTag,
377
- cssSelectorPrefixExamples: useSvelteComponent ? [] : buildCssSelectorPrefixExamples(styleMode.mode, count),
378
- cssAuthoring: useSvelteComponent ? svelteComponentAuthoring : buildCssAuthoring(styleMode, count),
379
- originalLineCount: originalLines.length,
380
- }));
381
- }
382
-
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
- // Auto-execute when run directly (node live-wrap.mjs ...)
867
- const _running = process.argv[1];
868
- if (_running?.endsWith('live-wrap.mjs') || _running?.endsWith('live-wrap.mjs/')) {
869
- wrapCli();
870
- }
871
-
872
- // Test exports (used by tests/live-wrap.test.mjs)
873
- export {
874
- buildSearchQueries,
875
- findElement,
876
- findClosingLine,
877
- detectCommentSyntax,
878
- findAllElements,
879
- filterByText,
880
- findFileWithQuery,
881
- detectStyleMode,
882
- buildCssAuthoring,
883
- buildCssSelectorPrefixExamples,
884
- };