huminmin
7 天以前 1feea304776ab97ab04f953a3e1b2334dfdc8732
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
/**
 * CLI helper: find an anchor element in source and splice an insert-variant
 * wrapper before or after it (no original variant — net-new content).
 *
 * Usage:
 *   node live-insert.mjs --id SESSION_ID --count N --position after \
 *     --classes "hero" --tag section [--file path]
 */
 
import fs from 'node:fs';
import path from 'node:path';
import { isGeneratedFile } from './lib/is-generated.mjs';
import {
  buildSearchQueries,
  findElement,
  findAllElements,
  filterByText,
  findFileWithQuery,
  detectCommentSyntax,
  detectStyleMode,
  buildCssAuthoring,
  buildCssSelectorPrefixExamples,
} from './live-wrap.mjs';
import {
  buildSvelteComponentCssAuthoring,
  scaffoldSvelteComponentInsertSession,
  shouldUseSvelteComponentInjection,
} from './live/svelte-component.mjs';
import { enterLiveRoot } from './live/roots.mjs';
 
const INSERT_POSITIONS = new Set(['before', 'after']);
 
export function isInsertPosition(value) {
  return INSERT_POSITIONS.has(value);
}
 
export function computeInsertLine(startLine, endLine, position) {
  return position === 'before' ? startLine : endLine + 1;
}
 
export function buildInsertWrapperLines({ id, count, indent, commentSyntax, isJsx }) {
  const styleContents = isJsx ? 'style={{ display: "contents" }}' : 'style="display: contents"';
  const attrs =
    'data-impeccable-variants="' + id + '" ' +
    'data-impeccable-mode="insert" ' +
    'data-impeccable-variant-count="' + count + '" ' +
    styleContents;
 
  if (isJsx) {
    return [
      indent + '<div ' + attrs + '>',
      indent + '  ' + commentSyntax.open + ' impeccable-variants-start ' + id + ' ' + commentSyntax.close,
      indent + '  ' + commentSyntax.open + ' Variants: insert below this line ' + commentSyntax.close,
      indent + '  ' + commentSyntax.open + ' impeccable-variants-end ' + id + ' ' + commentSyntax.close,
      indent + '</div>',
    ];
  }
 
  return [
    indent + commentSyntax.open + ' impeccable-variants-start ' + id + ' ' + commentSyntax.close,
    indent + '<div ' + attrs + '>',
    indent + '  ' + commentSyntax.open + ' Variants: insert below this line ' + commentSyntax.close,
    indent + '</div>',
    indent + commentSyntax.open + ' impeccable-variants-end ' + id + ' ' + commentSyntax.close,
  ];
}
 
function argVal(args, flag) {
  const idx = args.indexOf(flag);
  return idx !== -1 && idx + 1 < args.length ? args[idx + 1] : null;
}
 
function resolveElementMatch({ lines, queries, tag, text }) {
  if (text) {
    const candidates = [];
    for (const q of queries) {
      const all = findAllElements(lines, q, tag);
      for (const c of all) {
        if (!candidates.some((x) => x.startLine === c.startLine)) candidates.push(c);
      }
      if (candidates.length === 1) break;
    }
    if (candidates.length === 0) return { error: 'element_not_found' };
    if (candidates.length === 1) return { match: candidates[0] };
    const filtered = filterByText(candidates, lines, text);
    if (filtered.length === 1) return { match: filtered[0] };
    if (filtered.length === 0) return { match: candidates[0] };
    return { error: 'element_ambiguous', candidates: filtered };
  }
 
  for (const q of queries) {
    const match = findElement(lines, q, tag);
    if (match) return { match };
  }
  return { error: 'element_not_found' };
}
 
export async function insertCli() {
  const args = process.argv.slice(2);
 
  if (args.includes('--help') || args.includes('-h')) {
    console.log(`Usage: node live-insert.mjs [options]
 
Find an anchor element in source and splice an insert-variant wrapper.
 
Required:
  --id ID            Session ID for the variant wrapper
  --count N          Number of expected variants (1-8)
  --position POS     before | after (relative to the anchor element)
 
Element identification (at least one required):
  --element-id ID    HTML id attribute of the anchor element
  --classes A,B,C    Comma-separated CSS class names
  --tag TAG          Tag name (div, section, etc.)
  --query TEXT       Fallback: raw text to search for
 
Optional:
  --file PATH        Source file to search in (skips auto-detection)
  --text TEXT        Anchor textContent for disambiguation (~80 chars)
 
Output (JSON):
  { mode: "insert", file, position, insertLine, commentSyntax, styleMode, styleTag, cssAuthoring }`);
    process.exit(0);
  }
 
  const id = argVal(args, '--id');
  const count = parseInt(argVal(args, '--count') || '3', 10);
  const position = argVal(args, '--position');
  const elementId = argVal(args, '--element-id');
  const classes = argVal(args, '--classes');
  const tag = argVal(args, '--tag');
  const query = argVal(args, '--query');
  const filePath = argVal(args, '--file');
  const text = argVal(args, '--text');
  // See live-wrap.mjs: preflight computes the scaffold but leaves source
  // untouched so the agent's single edit is the only framework reload.
  const deferSourceWrite = args.includes('--defer-source-write');
 
  if (!id) { console.error('Missing --id'); process.exit(1); }
  if (!position) { console.error('Missing --position (before | after)'); process.exit(1); }
  if (!isInsertPosition(position)) { console.error('Invalid --position: ' + position); process.exit(1); }
  if (!elementId && !classes && !query) {
    console.error('Need at least one of: --element-id, --classes, --query');
    process.exit(1);
  }
 
  const queries = buildSearchQueries(elementId, classes, tag, query);
  const genOpts = { cwd: process.cwd() };
 
  let targetFile = filePath;
  if (!targetFile) {
    for (const q of queries) {
      targetFile = findFileWithQuery(q, process.cwd(), genOpts);
      if (targetFile) break;
    }
    if (!targetFile) {
      let generatedHit = null;
      for (const q of queries) {
        generatedHit = findFileWithQuery(q, process.cwd(), { ...genOpts, includeGenerated: true });
        if (generatedHit) break;
      }
      console.error(JSON.stringify({
        error: generatedHit ? 'element_not_in_source' : 'element_not_found',
        fallback: 'agent-driven',
        hint: 'See "Handle fallback" in live.md.',
      }));
      process.exit(1);
    }
  } else if (isGeneratedFile(targetFile, genOpts)) {
    console.error(JSON.stringify({
      error: 'file_is_generated',
      fallback: 'agent-driven',
      file: path.relative(process.cwd(), path.resolve(process.cwd(), targetFile)),
    }));
    process.exit(1);
  }
 
  const content = fs.readFileSync(targetFile, 'utf-8');
  const lines = content.split('\n');
  const resolved = resolveElementMatch({ lines, queries, tag, text });
 
  if (resolved.error === 'element_ambiguous') {
    console.error(JSON.stringify({
      error: 'element_ambiguous',
      fallback: 'agent-driven',
      file: path.relative(process.cwd(), targetFile),
      candidates: resolved.candidates.map((c) => ({
        startLine: c.startLine + 1,
        endLine: c.endLine + 1,
      })),
    }));
    process.exit(1);
  }
  if (!resolved.match) {
    console.error(JSON.stringify({ error: 'element_not_found', fallback: 'agent-driven' }));
    process.exit(1);
  }
 
  const { startLine, endLine } = resolved.match;
  const commentSyntax = detectCommentSyntax(targetFile);
  const styleMode = detectStyleMode(targetFile);
  const isJsx = commentSyntax.open === '{/*';
  const spliceIndex = computeInsertLine(startLine, endLine, position);
  const relTargetFile = path.relative(process.cwd(), targetFile).split(path.sep).join('/');
 
  if (shouldUseSvelteComponentInjection(targetFile)) {
    const session = scaffoldSvelteComponentInsertSession({
      id,
      count,
      sourceFile: relTargetFile,
      insertLine: spliceIndex + 1,
      position,
      anchorStartLine: startLine + 1,
      anchorEndLine: endLine + 1,
      anchorLines: lines.slice(startLine, endLine + 1),
      cwd: process.cwd(),
    });
    console.log(JSON.stringify({
      mode: 'insert',
      position,
      file: session.manifestFile,
      sourceFile: relTargetFile,
      previewMode: 'svelte-component',
      componentDir: session.componentDir,
      propContract: session.propContract,
      insertLine: 1,
      sourceInsertLine: spliceIndex + 1,
      anchorStartLine: startLine + 1,
      anchorEndLine: endLine + 1,
      commentSyntax,
      styleMode: 'svelte-component',
      styleTag: null,
      cssSelectorPrefixExamples: [],
      cssAuthoring: buildSvelteComponentCssAuthoring(count),
    }));
    return;
  }
 
  const indent = lines[spliceIndex]?.match(/^(\s*)/)?.[1]
    ?? lines[startLine]?.match(/^(\s*)/)?.[1]
    ?? '';
 
  const wrapperLines = buildInsertWrapperLines({
    id,
    count,
    indent,
    commentSyntax,
    isJsx,
  });
 
  let deferredWrapper = null;
  if (deferSourceWrite) {
    // Insert-as-empty-range: the agent inserts `wrapperBlock` (variants spliced
    // at the marker) at spliceIndex without removing any source line.
    deferredWrapper = {
      block: wrapperLines.join('\n'),
      replaceStartLine: spliceIndex + 1,
      replaceEndLine: spliceIndex, // empty range (endLine < startLine) => insertion
    };
  } else {
    const newLines = [
      ...lines.slice(0, spliceIndex),
      ...wrapperLines,
      ...lines.slice(spliceIndex),
    ];
    fs.writeFileSync(targetFile, newLines.join('\n'), 'utf-8');
  }
 
  const insertLine = spliceIndex + 3;
 
  console.log(JSON.stringify({
    mode: 'insert',
    position,
    file: relTargetFile,
    sourceWritten: deferredWrapper ? false : undefined,
    wrapperBlock: deferredWrapper ? deferredWrapper.block : undefined,
    replaceStartLine: deferredWrapper ? deferredWrapper.replaceStartLine : undefined,
    replaceEndLine: deferredWrapper ? deferredWrapper.replaceEndLine : undefined,
    insertLine: insertLine + 1,
    commentSyntax,
    styleMode: styleMode.mode,
    styleTag: styleMode.styleTag,
    cssSelectorPrefixExamples: buildCssSelectorPrefixExamples(styleMode.mode, count),
    cssAuthoring: buildCssAuthoring(styleMode, count),
  }));
}
 
const _running = process.argv[1];
if (_running?.endsWith('live-insert.mjs') || _running?.endsWith('live-insert.mjs/')) {
  enterLiveRoot();
  insertCli();
}