chore(infra): 更新 Nginx 部署配置与项目上下文文档
- 更新 CI/CD 子域名反向代理配置 - 调整 Nginx 静态文件服务器配置 - 更新 CONTEXT.md 领域共享语言文档 - 添加 CLAUDE.md 代理工作指南 - 更新 Playwright E2E 测试配置
This commit is contained in:
@@ -0,0 +1,49 @@
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
|
||||
export const LIVE_BROWSER_SCRIPT_PARTS = Object.freeze([
|
||||
Object.freeze({ name: 'session-state', file: 'live-browser-session.js' }),
|
||||
Object.freeze({ name: 'dom-helpers', file: 'live-browser-dom.js' }),
|
||||
Object.freeze({ name: 'browser-ui', file: 'live-browser.js' }),
|
||||
]);
|
||||
|
||||
export function resolveLiveBrowserScriptParts(scriptsDir, parts = LIVE_BROWSER_SCRIPT_PARTS) {
|
||||
if (!scriptsDir) throw new Error('scriptsDir is required');
|
||||
return parts.map((part, index) => ({
|
||||
...part,
|
||||
index,
|
||||
path: path.join(scriptsDir, part.file),
|
||||
}));
|
||||
}
|
||||
|
||||
export function assertLiveBrowserScriptParts(parts, exists = fs.existsSync) {
|
||||
for (const part of parts) {
|
||||
if (!exists(part.path)) {
|
||||
throw new Error(`Live browser script part missing: ${part.name} (${part.path})`);
|
||||
}
|
||||
}
|
||||
return parts;
|
||||
}
|
||||
|
||||
export function readLiveBrowserScriptParts(parts, readFile = (filePath) => fs.readFileSync(filePath, 'utf-8')) {
|
||||
return parts.map((part) => ({
|
||||
...part,
|
||||
source: readFile(part.path),
|
||||
}));
|
||||
}
|
||||
|
||||
export function assembleLiveBrowserScript({ token, port, vocabulary, parts }) {
|
||||
const prelude =
|
||||
`window.__IMPECCABLE_TOKEN__ = '${token}';\n` +
|
||||
`window.__IMPECCABLE_PORT__ = ${port};\n` +
|
||||
// Canonical command vocabulary (values + labels + icons). live-browser.js
|
||||
// builds its action picker from this instead of an inline copy.
|
||||
`window.__IMPECCABLE_VOCAB__ = ${JSON.stringify(vocabulary)};\n`;
|
||||
|
||||
const body = parts.map((part) => {
|
||||
const file = part.file || path.basename(part.path || '');
|
||||
return `// --- impeccable live script part: ${part.name} (${file}) ---\n${part.source}`;
|
||||
}).join('\n');
|
||||
|
||||
return prelude + body;
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
export function completionTypeForAcceptResult(eventType, acceptResult) {
|
||||
if (eventType === 'discard') return acceptResult?.handled === true ? 'discarded' : 'error';
|
||||
if (acceptResult?.handled === true && acceptResult?.carbonize === true) return 'agent_done';
|
||||
if (acceptResult?.handled === true) return 'complete';
|
||||
if (acceptResult?.mode === 'error') return 'error';
|
||||
if (eventType === 'accept' && acceptResult?.previewMode === 'svelte-component') return 'error';
|
||||
return 'agent_done';
|
||||
}
|
||||
|
||||
export function completionAckForAcceptResult(eventId, completionType, acceptResult) {
|
||||
const ack = { ok: true, type: completionType };
|
||||
if (acceptResult?.handled === true && acceptResult?.carbonize === true) {
|
||||
ack.final = false;
|
||||
ack.requiresComplete = true;
|
||||
ack.nextCommand = `live-complete.mjs --id ${eventId}`;
|
||||
ack.message = 'Carbonize cleanup must be verified, then the session must be completed explicitly before polling again.';
|
||||
}
|
||||
return ack;
|
||||
}
|
||||
@@ -0,0 +1,137 @@
|
||||
/**
|
||||
* Shared event validation for the live helper server.
|
||||
* Extracted for unit testing (insert mode rules).
|
||||
*/
|
||||
|
||||
import { canCreateInsert } from './insert-ui.mjs';
|
||||
|
||||
// The accepted visual action values come from the canonical vocabulary so the
|
||||
// validator, the picker UI, and the marketing demo never drift. Imported (not
|
||||
// just re-exported) so it is also in scope for the validators below.
|
||||
import { VISUAL_ACTIONS } from './vocabulary.mjs';
|
||||
export { VISUAL_ACTIONS };
|
||||
|
||||
const ID_PATTERN = /^[0-9a-f]{8}$/;
|
||||
const VARIANT_ID_PATTERN = /^[0-9]{1,3}$/;
|
||||
const INSERT_POSITIONS = new Set(['before', 'after']);
|
||||
const FORBIDDEN_MANUAL_EDIT_TEXT_CHARS = ['<', '{', '}', '`'];
|
||||
|
||||
function isValidId(v) { return typeof v === 'string' && ID_PATTERN.test(v); }
|
||||
function isValidVariantId(v) { return typeof v === 'string' && VARIANT_ID_PATTERN.test(v); }
|
||||
|
||||
function validateManualEditText(newText) {
|
||||
if (typeof newText !== 'string') return null;
|
||||
const hits = FORBIDDEN_MANUAL_EDIT_TEXT_CHARS.filter((char) => newText.includes(char));
|
||||
return hits.length > 0 ? hits : null;
|
||||
}
|
||||
|
||||
function validateAnnotationFields(msg) {
|
||||
if (msg.screenshotPath !== undefined && typeof msg.screenshotPath !== 'string') {
|
||||
return 'generate: screenshotPath must be string';
|
||||
}
|
||||
if (msg.comments !== undefined && !Array.isArray(msg.comments)) {
|
||||
return 'generate: comments must be array';
|
||||
}
|
||||
if (msg.strokes !== undefined && !Array.isArray(msg.strokes)) {
|
||||
return 'generate: strokes must be array';
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function validateInsertGenerate(msg) {
|
||||
if (!msg.insert || typeof msg.insert !== 'object') return 'generate: insert mode requires insert object';
|
||||
if (!INSERT_POSITIONS.has(msg.insert.position)) return 'generate: insert.position must be before or after';
|
||||
const anchor = msg.insert.anchor;
|
||||
if (!anchor || typeof anchor !== 'object') return 'generate: insert.anchor required';
|
||||
if (!anchor.tagName && !anchor.outerHTML && !(Array.isArray(anchor.classes) && anchor.classes.length)) {
|
||||
return 'generate: insert.anchor needs tagName, classes, or outerHTML';
|
||||
}
|
||||
if (!msg.placeholder || typeof msg.placeholder !== 'object') return 'generate: insert mode requires placeholder dimensions';
|
||||
if (!Number.isFinite(msg.placeholder.width) || !Number.isFinite(msg.placeholder.height)) {
|
||||
return 'generate: placeholder width and height must be numbers';
|
||||
}
|
||||
if (!canCreateInsert({
|
||||
prompt: msg.freeformPrompt,
|
||||
comments: msg.comments,
|
||||
strokes: msg.strokes,
|
||||
})) {
|
||||
return 'generate: insert requires freeformPrompt or annotations';
|
||||
}
|
||||
return validateAnnotationFields(msg);
|
||||
}
|
||||
|
||||
function validateReplaceGenerate(msg) {
|
||||
if (!msg.action || !VISUAL_ACTIONS.includes(msg.action)) return 'generate: invalid action';
|
||||
if (!msg.element || !msg.element.outerHTML) return 'generate: missing element context';
|
||||
return validateAnnotationFields(msg);
|
||||
}
|
||||
|
||||
function validateManualEditEvent(msg, label) {
|
||||
if (!isValidId(msg.id)) return label + ': missing or malformed id';
|
||||
if (!msg.pageUrl || typeof msg.pageUrl !== 'string') return label + ': missing pageUrl';
|
||||
if (!msg.element || typeof msg.element !== 'object') return label + ': missing element';
|
||||
if (!Array.isArray(msg.ops) || msg.ops.length === 0) return label + ': ops must be non-empty array';
|
||||
if (msg.ops.length > 100) return label + ': too many ops (max 100)';
|
||||
for (const op of msg.ops) {
|
||||
if (typeof op.ref !== 'string') return label + ': op.ref required';
|
||||
if (typeof op.tag !== 'string') return label + ': op.tag required';
|
||||
if (typeof op.originalText !== 'string') return label + ': op.originalText required';
|
||||
if (op.deleted !== true && typeof op.newText !== 'string') {
|
||||
return label + ': text op requires newText';
|
||||
}
|
||||
if (typeof op.newText === 'string') {
|
||||
if (op.deleted !== true && op.newText.trim().length === 0) {
|
||||
return label + ': newText cannot be empty';
|
||||
}
|
||||
const forbidden = validateManualEditText(op.newText);
|
||||
if (forbidden) {
|
||||
return label + ': newText cannot contain ' + forbidden.join(' ') + ' (plain text only; ask the AI to insert markup)';
|
||||
}
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
export function validateEvent(msg) {
|
||||
if (!msg || typeof msg !== 'object' || !msg.type) return 'Missing or invalid message';
|
||||
switch (msg.type) {
|
||||
case 'generate':
|
||||
if (!isValidId(msg.id)) return 'generate: missing or malformed id';
|
||||
if (!Number.isInteger(msg.count) || msg.count < 1 || msg.count > 8) return 'generate: count must be 1-8';
|
||||
if (msg.mode === 'insert') return validateInsertGenerate(msg);
|
||||
return validateReplaceGenerate(msg);
|
||||
case 'accept':
|
||||
if (!isValidId(msg.id)) return 'accept: missing or malformed id';
|
||||
if (!isValidVariantId(msg.variantId)) return 'accept: missing or malformed variantId';
|
||||
if (msg.paramValues !== undefined) {
|
||||
if (typeof msg.paramValues !== 'object' || msg.paramValues === null || Array.isArray(msg.paramValues)) {
|
||||
return 'accept: paramValues must be an object';
|
||||
}
|
||||
}
|
||||
return null;
|
||||
case 'discard':
|
||||
return isValidId(msg.id) ? null : 'discard: missing or malformed id';
|
||||
case 'checkpoint':
|
||||
if (!isValidId(msg.id)) return 'checkpoint: missing or malformed id';
|
||||
if (!Number.isInteger(msg.revision) || msg.revision < 0) return 'checkpoint: revision must be a non-negative integer';
|
||||
if (msg.paramValues !== undefined && (typeof msg.paramValues !== 'object' || msg.paramValues === null || Array.isArray(msg.paramValues))) {
|
||||
return 'checkpoint: paramValues must be an object';
|
||||
}
|
||||
return null;
|
||||
case 'exit':
|
||||
return null;
|
||||
case 'prefetch':
|
||||
if (!msg.pageUrl || typeof msg.pageUrl !== 'string') return 'prefetch: missing pageUrl';
|
||||
return null;
|
||||
case 'manual_edits':
|
||||
return validateManualEditEvent(msg, 'manual_edits');
|
||||
case 'steer':
|
||||
if (!isValidId(msg.id)) return 'steer: missing or malformed id';
|
||||
if (typeof msg.message !== 'string' || !msg.message.trim()) return 'steer: message required';
|
||||
if (msg.message.length > 4000) return 'steer: message too long';
|
||||
if (msg.pageUrl !== undefined && typeof msg.pageUrl !== 'string') return 'steer: pageUrl must be string';
|
||||
return null;
|
||||
default:
|
||||
return 'Unknown event type: ' + msg.type;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,458 @@
|
||||
/**
|
||||
* Pure helpers for live-mode insert UI (browser + tests).
|
||||
* Kept separate from live-browser.js so insert logic is unit-testable.
|
||||
*/
|
||||
|
||||
export const PLACEHOLDER_DEFAULT_HEIGHT = 80;
|
||||
export const PLACEHOLDER_MIN_HEIGHT = 48;
|
||||
export const PLACEHOLDER_MIN_WIDTH = 120;
|
||||
|
||||
/** @typedef {'before' | 'after'} InsertPosition */
|
||||
/** @typedef {'row' | 'column'} InsertAxis */
|
||||
|
||||
/**
|
||||
* Infer sibling flow axis from a container's computed layout styles.
|
||||
* @param {{ display?: string, flexDirection?: string, gridTemplateColumns?: string, gridAutoFlow?: string }} style
|
||||
* @returns {InsertAxis}
|
||||
*/
|
||||
export function detectInsertAxisFromStyle(style) {
|
||||
const display = style?.display || 'block';
|
||||
if (display.includes('flex')) {
|
||||
const dir = style.flexDirection || 'row';
|
||||
return dir.startsWith('row') ? 'row' : 'column';
|
||||
}
|
||||
if (display === 'grid' || display === 'inline-grid') {
|
||||
const flow = style.gridAutoFlow || 'row';
|
||||
if (flow.includes('column')) return 'column';
|
||||
const cols = (style.gridTemplateColumns || '').trim();
|
||||
if (cols && cols !== 'none') {
|
||||
const colCount = cols.split(/\s+/).filter(Boolean).length;
|
||||
if (colCount > 1) return 'row';
|
||||
}
|
||||
return 'row';
|
||||
}
|
||||
return 'column';
|
||||
}
|
||||
|
||||
/**
|
||||
* Pick insertion side from pointer position against an anchor element box.
|
||||
* @param {number} clientX
|
||||
* @param {number} clientY
|
||||
* @param {{ top: number, left: number, width: number, height: number, bottom?: number, right?: number }} rect
|
||||
* @param {InsertAxis} [axis]
|
||||
* @returns {InsertPosition}
|
||||
*/
|
||||
export function computeInsertPosition(clientX, clientY, rect, axis = 'column') {
|
||||
if (!rect) return 'after';
|
||||
if (axis === 'row') {
|
||||
if (!Number.isFinite(rect.left) || !Number.isFinite(rect.width) || rect.width <= 0) return 'after';
|
||||
const mid = rect.left + rect.width / 2;
|
||||
return clientX < mid ? 'before' : 'after';
|
||||
}
|
||||
if (!Number.isFinite(rect.top) || !Number.isFinite(rect.height) || rect.height <= 0) return 'after';
|
||||
const mid = rect.top + rect.height / 2;
|
||||
return clientY < mid ? 'before' : 'after';
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether Create is allowed for an insert session.
|
||||
* Requires a non-empty prompt OR at least one annotation.
|
||||
*/
|
||||
export function canCreateInsert({ prompt, comments, strokes }) {
|
||||
const hasPrompt = typeof prompt === 'string' && prompt.trim().length > 0;
|
||||
const hasComments = Array.isArray(comments) && comments.length > 0;
|
||||
const hasStrokes = Array.isArray(strokes) && strokes.some(
|
||||
(s) => Array.isArray(s?.points) && s.points.length >= 2,
|
||||
);
|
||||
return hasPrompt || hasComments || hasStrokes;
|
||||
}
|
||||
|
||||
/** Tooltip/title when Create is disabled. */
|
||||
export function insertCreateDisabledReason({ prompt, comments, strokes }) {
|
||||
if (canCreateInsert({ prompt, comments, strokes })) return null;
|
||||
return 'Add a prompt or annotate the placeholder to create';
|
||||
}
|
||||
|
||||
/**
|
||||
* Fixed-position insert line coordinates (viewport px).
|
||||
* @param {{ top: number, left: number, width: number, height: number, bottom?: number, right?: number }} rect
|
||||
* @param {InsertPosition} position
|
||||
* @param {InsertAxis} [axis]
|
||||
*/
|
||||
export function insertLineCoords(rect, position, axis = 'column') {
|
||||
if (axis === 'row') {
|
||||
const right = rect.right ?? rect.left + rect.width;
|
||||
const x = position === 'before' ? rect.left - 2 : right + 2;
|
||||
return { axis: 'row', top: rect.top, left: x, width: 0, height: rect.height };
|
||||
}
|
||||
const bottom = rect.bottom ?? rect.top + rect.height;
|
||||
const y = position === 'before' ? rect.top - 2 : bottom + 2;
|
||||
return { axis: 'column', top: y, left: rect.left, width: rect.width, height: 0 };
|
||||
}
|
||||
|
||||
/** Cursor while hovering an insert boundary. */
|
||||
export function cursorForInsertAxis(axis) {
|
||||
return axis === 'row' ? 'ew-resize' : 'ns-resize';
|
||||
}
|
||||
|
||||
function groupSiblingRows(siblings, rowThreshold = 8) {
|
||||
const sorted = [...siblings].sort((a, b) => a.rect.top - b.rect.top || a.rect.left - b.rect.left);
|
||||
const rows = [];
|
||||
for (const entry of sorted) {
|
||||
let placed = false;
|
||||
for (const row of rows) {
|
||||
if (Math.abs(entry.rect.top - row[0].rect.top) <= rowThreshold) {
|
||||
row.push(entry);
|
||||
placed = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (!placed) rows.push([entry]);
|
||||
}
|
||||
return rows;
|
||||
}
|
||||
|
||||
function horizontalOverlap(a, b) {
|
||||
const left = Math.max(a.left, b.left);
|
||||
const right = Math.min(a.right ?? a.left + a.width, b.right ?? b.left + b.width);
|
||||
return Math.max(0, right - left);
|
||||
}
|
||||
|
||||
/**
|
||||
* Hit-test the gap between adjacent siblings (flex rows, grid columns, stacked blocks).
|
||||
* @param {number} clientX
|
||||
* @param {number} clientY
|
||||
* @param {Array<{ el: unknown, rect: { top: number, left: number, width: number, height: number, bottom?: number, right?: number } }>} siblings
|
||||
* @param {{ slop?: number, minOverlap?: number }} [opts]
|
||||
*/
|
||||
export function hitSiblingInsertGap(clientX, clientY, siblings, opts = {}) {
|
||||
if (!Array.isArray(siblings) || siblings.length < 2) return null;
|
||||
const slop = opts.slop ?? 12;
|
||||
const minOverlap = opts.minOverlap ?? 0.25;
|
||||
|
||||
for (const row of groupSiblingRows(siblings)) {
|
||||
if (row.length < 2) continue;
|
||||
const sorted = [...row].sort((a, b) => a.rect.left - b.rect.left);
|
||||
for (let i = 0; i < sorted.length - 1; i++) {
|
||||
const a = sorted[i];
|
||||
const b = sorted[i + 1];
|
||||
const aRight = a.rect.right ?? a.rect.left + a.rect.width;
|
||||
const bLeft = b.rect.left;
|
||||
if (bLeft <= aRight) continue;
|
||||
const top = Math.max(a.rect.top, b.rect.top);
|
||||
const aBottom = a.rect.bottom ?? a.rect.top + a.rect.height;
|
||||
const bBottom = b.rect.bottom ?? b.rect.top + b.rect.height;
|
||||
const bottom = Math.min(aBottom, bBottom);
|
||||
const span = bottom - top;
|
||||
const minH = Math.min(a.rect.height, b.rect.height);
|
||||
if (span < minH * minOverlap) continue;
|
||||
|
||||
const inX = clientX >= aRight - slop && clientX <= bLeft + slop;
|
||||
const inY = clientY >= top - slop && clientY <= bottom + slop;
|
||||
if (!inX || !inY) continue;
|
||||
|
||||
const midX = (aRight + bLeft) / 2;
|
||||
return {
|
||||
anchor: b.el,
|
||||
position: 'before',
|
||||
axis: 'row',
|
||||
line: { axis: 'row', left: midX, top, width: 0, height: span },
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
const sortedCol = [...siblings].sort((a, b) => a.rect.top - b.rect.top || a.rect.left - b.rect.left);
|
||||
for (let i = 0; i < sortedCol.length - 1; i++) {
|
||||
const a = sortedCol[i];
|
||||
const b = sortedCol[i + 1];
|
||||
const overlap = horizontalOverlap(a.rect, b.rect);
|
||||
const minW = Math.min(a.rect.width, b.rect.width);
|
||||
if (overlap < minW * minOverlap) continue;
|
||||
|
||||
const aBottom = a.rect.bottom ?? a.rect.top + a.rect.height;
|
||||
const gapTop = aBottom;
|
||||
const gapBottom = b.rect.top;
|
||||
if (gapBottom <= gapTop) continue;
|
||||
|
||||
const overlapLeft = Math.max(a.rect.left, b.rect.left);
|
||||
const overlapRight = Math.min(
|
||||
a.rect.right ?? a.rect.left + a.rect.width,
|
||||
b.rect.right ?? b.rect.left + b.rect.width,
|
||||
);
|
||||
const inY = clientY >= gapTop - slop && clientY <= gapBottom + slop;
|
||||
const inX = clientX >= overlapLeft - slop && clientX <= overlapRight + slop;
|
||||
if (!inY || !inX) continue;
|
||||
|
||||
const midY = (gapTop + gapBottom) / 2;
|
||||
return {
|
||||
anchor: b.el,
|
||||
position: 'before',
|
||||
axis: 'column',
|
||||
line: { axis: 'column', top: midY, left: overlapLeft, width: overlap, height: 0 },
|
||||
};
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve insert hover target, side, axis, and indicator line for the pointer.
|
||||
*/
|
||||
export function resolveInsertHover({ clientX, clientY, target, rect, axis, siblings }) {
|
||||
const gap = hitSiblingInsertGap(clientX, clientY, siblings);
|
||||
if (gap) return gap;
|
||||
|
||||
const position = computeInsertPosition(clientX, clientY, rect, axis);
|
||||
const line = insertLineCoords(rect, position, axis);
|
||||
return { anchor: target, position, axis, line };
|
||||
}
|
||||
|
||||
/**
|
||||
* How the in-flow placeholder should participate in layout.
|
||||
* Prefer implicit sizing (flex / %) so row inserts don't inherit the full parent width in px.
|
||||
* @returns {{ kind: 'flex', flex: string, minWidth: number } | { kind: 'percent' } | { kind: 'auto' } | { kind: 'explicit', width: number }}
|
||||
*/
|
||||
export function placeholderSizing({ axis, parentDisplay, parentWidth, anchorFlex }) {
|
||||
const display = parentDisplay || 'block';
|
||||
const w = Number.isFinite(parentWidth) ? parentWidth : 0;
|
||||
|
||||
if (axis === 'row') {
|
||||
if (display.includes('flex')) {
|
||||
const flex = anchorFlex && anchorFlex !== 'none' && anchorFlex !== '0 1 auto'
|
||||
? anchorFlex
|
||||
: '1 1 0';
|
||||
return { kind: 'flex', flex, minWidth: 0 };
|
||||
}
|
||||
if (display === 'grid' || display === 'inline-grid') {
|
||||
return { kind: 'auto' };
|
||||
}
|
||||
}
|
||||
|
||||
if (w >= PLACEHOLDER_MIN_WIDTH) {
|
||||
return { kind: 'percent' };
|
||||
}
|
||||
|
||||
return {
|
||||
kind: 'explicit',
|
||||
width: Math.max(PLACEHOLDER_MIN_WIDTH, w || PLACEHOLDER_MIN_WIDTH),
|
||||
};
|
||||
}
|
||||
|
||||
/** Width kinds that need materializing to px before edge-resize. */
|
||||
export function placeholderWidthIsImplicit(kind) {
|
||||
return kind === 'flex' || kind === 'percent' || kind === 'auto';
|
||||
}
|
||||
|
||||
/**
|
||||
* Clamp user-resized placeholder dimensions.
|
||||
*/
|
||||
export function clampPlaceholderSize(width, height, parentWidth, opts = {}) {
|
||||
const minW = opts.minWidth ?? PLACEHOLDER_MIN_WIDTH;
|
||||
const minH = opts.minHeight ?? PLACEHOLDER_MIN_HEIGHT;
|
||||
const maxW = opts.maxWidth ?? Math.max(minW, parentWidth || minW);
|
||||
return {
|
||||
width: Math.min(maxW, Math.max(minW, Math.round(width))),
|
||||
height: Math.max(minH, Math.round(height)),
|
||||
};
|
||||
}
|
||||
|
||||
/** CSS cursor for a placeholder edge resize handle. */
|
||||
export function cursorForPlaceholderEdge(edge) {
|
||||
if (edge === 'n' || edge === 's') return 'ns-resize';
|
||||
if (edge === 'e' || edge === 'w') return 'ew-resize';
|
||||
return 'default';
|
||||
}
|
||||
|
||||
/**
|
||||
* Compute placeholder box after dragging one edge (in-flow margins shift for n/w).
|
||||
* @param {{ width: number, height: number, marginLeft?: number, marginTop?: number }} start
|
||||
* @param {'n'|'e'|'s'|'w'} edge
|
||||
* @param {number} dx pointer delta X since drag start
|
||||
* @param {number} dy pointer delta Y since drag start
|
||||
* @param {number} parentWidth
|
||||
*/
|
||||
export function resizePlaceholderFromEdge(start, edge, dx, dy, parentWidth, opts = {}) {
|
||||
const base = {
|
||||
width: start.width,
|
||||
height: start.height,
|
||||
marginLeft: start.marginLeft ?? 0,
|
||||
marginTop: start.marginTop ?? 0,
|
||||
};
|
||||
if (edge === 'e') base.width = start.width + dx;
|
||||
else if (edge === 'w') {
|
||||
base.width = start.width - dx;
|
||||
base.marginLeft = start.marginLeft + dx;
|
||||
} else if (edge === 's') base.height = start.height + dy;
|
||||
else if (edge === 'n') {
|
||||
base.height = start.height - dy;
|
||||
base.marginTop = start.marginTop + dy;
|
||||
}
|
||||
|
||||
const clamped = clampPlaceholderSize(base.width, base.height, parentWidth, opts);
|
||||
if (edge === 'w') {
|
||||
base.marginLeft = start.marginLeft + start.width - clamped.width;
|
||||
} else if (edge === 'n') {
|
||||
base.marginTop = start.marginTop + start.height - clamped.height;
|
||||
}
|
||||
|
||||
return {
|
||||
width: clamped.width,
|
||||
height: clamped.height,
|
||||
marginLeft: Math.round(base.marginLeft),
|
||||
marginTop: Math.round(base.marginTop),
|
||||
};
|
||||
}
|
||||
|
||||
/** Pick and insert toggles are independent but turning one ON turns the other OFF. */
|
||||
export function applyPickToggle(pickActive, insertActive) {
|
||||
const nextPick = !pickActive;
|
||||
return {
|
||||
pickActive: nextPick,
|
||||
insertActive: nextPick ? false : insertActive,
|
||||
};
|
||||
}
|
||||
|
||||
export function applyInsertToggle(pickActive, insertActive) {
|
||||
const nextInsert = !insertActive;
|
||||
return {
|
||||
pickActive: nextInsert ? false : pickActive,
|
||||
insertActive: nextInsert,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Build the browser generate payload for insert mode.
|
||||
*/
|
||||
export function buildInsertGeneratePayload({
|
||||
id,
|
||||
count,
|
||||
pageUrl,
|
||||
anchorContext,
|
||||
position,
|
||||
placeholder,
|
||||
freeformPrompt,
|
||||
comments,
|
||||
strokes,
|
||||
screenshotPath,
|
||||
}) {
|
||||
const payload = {
|
||||
type: 'generate',
|
||||
mode: 'insert',
|
||||
id,
|
||||
count,
|
||||
pageUrl,
|
||||
insert: {
|
||||
position,
|
||||
anchor: anchorContext,
|
||||
},
|
||||
placeholder,
|
||||
freeformPrompt: freeformPrompt?.trim() || undefined,
|
||||
};
|
||||
if (comments?.length) payload.comments = comments;
|
||||
if (strokes?.length) payload.strokes = strokes;
|
||||
if (screenshotPath) payload.screenshotPath = screenshotPath;
|
||||
return payload;
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether a variant wrapper is currently shown (handles `hidden` and display:none).
|
||||
* @param {{ hidden?: boolean, style?: { display?: string } } | null | undefined} el
|
||||
*/
|
||||
export function isVariantShown(el) {
|
||||
if (!el) return false;
|
||||
if (el.hidden) return false;
|
||||
if (el.style?.display === 'none') return false;
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Show or hide a variant wrapper for cycling.
|
||||
* @param {{ hidden?: boolean, style?: { display?: string }, removeAttribute?: (name: string) => void, setAttribute?: (name: string, value?: string) => void } | null | undefined} el
|
||||
* @param {boolean} shown
|
||||
*/
|
||||
export function setVariantShown(el, shown) {
|
||||
if (!el) return;
|
||||
if (shown) {
|
||||
el.removeAttribute?.('hidden');
|
||||
if (el.style) el.style.display = '';
|
||||
} else {
|
||||
el.setAttribute?.('hidden', '');
|
||||
if (el.style) el.style.display = 'none';
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Pick the best live anchor during an insert session (placeholder until variants land).
|
||||
* @param {{
|
||||
* wrapper?: unknown,
|
||||
* variantCount?: number,
|
||||
* visibleVariant?: number,
|
||||
* placeholder?: unknown,
|
||||
* insertAnchor?: unknown,
|
||||
* pickVariantContent?: (wrapper: unknown, index: number) => unknown,
|
||||
* }} opts
|
||||
*/
|
||||
export function resolveInsertSessionAnchor(opts) {
|
||||
const {
|
||||
wrapper,
|
||||
variantCount = 0,
|
||||
visibleVariant = 0,
|
||||
placeholder,
|
||||
insertAnchor,
|
||||
pickVariantContent,
|
||||
} = opts || {};
|
||||
if (wrapper && variantCount > 0 && visibleVariant > 0 && pickVariantContent) {
|
||||
const vis = pickVariantContent(wrapper, visibleVariant);
|
||||
if (vis) return vis;
|
||||
}
|
||||
return placeholder || insertAnchor || null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Snapshot placeholder geometry + anchor fingerprint so HMR can recreate the box.
|
||||
* @param {{
|
||||
* tagName?: string,
|
||||
* className?: string,
|
||||
* textContent?: string,
|
||||
* }} anchor
|
||||
* @param {{
|
||||
* offsetWidth?: number,
|
||||
* offsetHeight?: number,
|
||||
* style?: { marginLeft?: string, marginTop?: string },
|
||||
* }} placeholder
|
||||
* @param {{ position: 'before' | 'after', layoutAxis?: 'row' | 'column' }} meta
|
||||
*/
|
||||
export function buildInsertPlaceholderSnapshot(anchor, placeholder, { position, layoutAxis }) {
|
||||
return {
|
||||
width: Math.round(placeholder.offsetWidth || 0),
|
||||
height: Math.round(placeholder.offsetHeight || PLACEHOLDER_DEFAULT_HEIGHT),
|
||||
marginLeft: parseFloat(placeholder.style?.marginLeft || '') || 0,
|
||||
marginTop: parseFloat(placeholder.style?.marginTop || '') || 0,
|
||||
position,
|
||||
layoutAxis: layoutAxis || 'column',
|
||||
anchorTag: anchor.tagName || 'DIV',
|
||||
anchorClasses: anchor.className || '',
|
||||
anchorText: (anchor.textContent || '').trim().slice(0, 120),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Re-find an insert anchor after framework HMR replaced the live DOM node.
|
||||
* @param {Pick<Document, 'body' | 'querySelectorAll'>} doc
|
||||
* @param {ReturnType<typeof buildInsertPlaceholderSnapshot> | null | undefined} snapshot
|
||||
* @param {Element | null | undefined} liveAnchor
|
||||
*/
|
||||
export function findInsertAnchorInDom(doc, snapshot, liveAnchor = null) {
|
||||
if (liveAnchor && doc.body.contains(liveAnchor)) return liveAnchor;
|
||||
if (!snapshot) return null;
|
||||
const tag = (snapshot.anchorTag || 'div').toLowerCase();
|
||||
const cls = (snapshot.anchorClasses || '').split(/\s+/).filter(Boolean)[0];
|
||||
const needle = snapshot.anchorText || '';
|
||||
const sel = cls ? `${tag}.${cls}` : tag;
|
||||
const candidates = doc.querySelectorAll(sel);
|
||||
for (const candidate of candidates) {
|
||||
if (needle && !(candidate.textContent || '').includes(needle.slice(0, 40))) continue;
|
||||
return candidate;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
@@ -0,0 +1,939 @@
|
||||
import { randomUUID } from 'node:crypto';
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import { getLiveDir } from '../lib/impeccable-paths.mjs';
|
||||
import { readBuffer as readManualEditsBuffer } from './manual-edits-buffer.mjs';
|
||||
|
||||
const APPLY_EVENT_HARD_TIMEOUT_MS = Number(process.env.IMPECCABLE_LIVE_APPLY_EVENT_HARD_TIMEOUT_MS || 150_000);
|
||||
const APPLY_EVENT_SOFT_DEADLINE_MS = Number(process.env.IMPECCABLE_LIVE_APPLY_EVENT_SOFT_DEADLINE_MS || 120_000);
|
||||
const DEFAULT_MANUAL_EDIT_APPLY_CHUNK_SIZE = 3;
|
||||
const MIN_MANUAL_EDIT_APPLY_CHUNK_SIZE = 1;
|
||||
const MAX_MANUAL_EDIT_APPLY_CHUNK_SIZE = 20;
|
||||
const MANUAL_APPLY_COMPACT_TEXT_LIMIT = 240;
|
||||
const MANUAL_APPLY_COMPACT_NEARBY_LIMIT = 4;
|
||||
|
||||
export function createManualApplyController({
|
||||
pendingEvents,
|
||||
pendingApplyDeferreds,
|
||||
timedOutApplyIds,
|
||||
enqueueEvent,
|
||||
acknowledgePendingEvent,
|
||||
flushPendingPolls,
|
||||
recordManualEditActivity,
|
||||
cwd = () => process.cwd(),
|
||||
} = {}) {
|
||||
const projectCwd = () => typeof cwd === 'function' ? cwd() : cwd || process.cwd();
|
||||
|
||||
function tombstoneTimedOutApplyId(eventId, details = {}) {
|
||||
if (!eventId) return;
|
||||
timedOutApplyIds.set(eventId, details);
|
||||
if (timedOutApplyIds.size <= 200) return;
|
||||
const oldest = timedOutApplyIds.keys().next().value;
|
||||
timedOutApplyIds.delete(oldest);
|
||||
}
|
||||
|
||||
function pushApplyEventAndWait(batch, pageUrl, chunk = null, repair = null) {
|
||||
const cwdValue = projectCwd();
|
||||
const eventId = randomUUID().replace(/-/g, '').slice(0, 8);
|
||||
const evidencePath = writeManualApplyEvidence(eventId, batch, cwdValue);
|
||||
const event = {
|
||||
type: 'manual_edit_apply',
|
||||
id: eventId,
|
||||
pageUrl,
|
||||
batch: compactManualApplyBatch(batch, cwdValue),
|
||||
evidencePath,
|
||||
agentAction: buildManualApplyAgentAction(eventId),
|
||||
schemaVersion: 1,
|
||||
deadlineMs: APPLY_EVENT_SOFT_DEADLINE_MS,
|
||||
};
|
||||
if (chunk) event.chunk = chunk;
|
||||
if (repair) event.repair = repair;
|
||||
const rollbackSnapshot = snapshotApplyEventFiles(batch, cwdValue);
|
||||
recordManualEditActivity('manual_edit_apply_dispatched', {
|
||||
id: eventId,
|
||||
pageUrl,
|
||||
chunk,
|
||||
repair,
|
||||
entryCount: Array.isArray(batch.entries) ? batch.entries.length : 0,
|
||||
opCount: countManualApplyOps(batch),
|
||||
fileCount: collectManualApplyFiles(batch, [], cwdValue).length,
|
||||
});
|
||||
return new Promise((resolve, reject) => {
|
||||
const timer = setTimeout(() => {
|
||||
pendingApplyDeferreds.delete(eventId);
|
||||
tombstoneTimedOutApplyId(eventId, { batch, rollbackSnapshot, cwd: cwdValue });
|
||||
acknowledgePendingEvent(eventId);
|
||||
removeManualApplyEvidence(evidencePath, cwdValue);
|
||||
recordManualEditActivity('manual_edit_apply_timeout', {
|
||||
id: eventId,
|
||||
pageUrl,
|
||||
chunk,
|
||||
entryCount: Array.isArray(batch.entries) ? batch.entries.length : 0,
|
||||
opCount: countManualApplyOps(batch),
|
||||
});
|
||||
reject(new Error('chat_agent_timeout'));
|
||||
}, APPLY_EVENT_HARD_TIMEOUT_MS);
|
||||
pendingApplyDeferreds.set(eventId, { resolve, reject, timer, event, batch, pageUrl, rollbackSnapshot, cwd: cwdValue });
|
||||
enqueueEvent(event);
|
||||
});
|
||||
}
|
||||
|
||||
async function pushBatchInChunksAndWait(batch, pageUrl, context = {}) {
|
||||
const repair = context?.repair || batch?.repair || null;
|
||||
if (repair) return pushApplyEventAndWait(batch, pageUrl, null, repair);
|
||||
const chunks = splitManualApplyBatch(batch, manualEditApplyChunkSize());
|
||||
if (chunks.length <= 1) return pushApplyEventAndWait(batch, pageUrl);
|
||||
|
||||
const expectedOpsByEntry = new Map();
|
||||
for (const entry of batch?.entries || []) {
|
||||
expectedOpsByEntry.set(entry.id, Array.isArray(entry.ops) ? entry.ops.length : 0);
|
||||
}
|
||||
|
||||
const appliedOpsByEntry = new Map();
|
||||
const failedByEntry = new Map();
|
||||
const files = new Set();
|
||||
const notes = [];
|
||||
let aborted = false;
|
||||
|
||||
for (const chunk of chunks) {
|
||||
if (aborted) {
|
||||
markChunkEntriesFailed(failedByEntry, chunk, 'manual_edit_chunk_aborted');
|
||||
continue;
|
||||
}
|
||||
|
||||
let result;
|
||||
try {
|
||||
result = normalizeApplyChunkResult(await pushApplyEventAndWait(chunk.batch, pageUrl, chunk.meta));
|
||||
} catch (err) {
|
||||
markChunkEntriesFailed(failedByEntry, chunk, err.message || 'chat_agent_error');
|
||||
aborted = true;
|
||||
continue;
|
||||
}
|
||||
|
||||
for (const file of result.files) files.add(file);
|
||||
notes.push(...result.notes);
|
||||
|
||||
const chunkFailedIds = new Set();
|
||||
for (const item of result.failed) {
|
||||
const entryId = item.entryId || item.id;
|
||||
if (!entryId) continue;
|
||||
chunkFailedIds.add(entryId);
|
||||
if (!failedByEntry.has(entryId)) {
|
||||
failedByEntry.set(entryId, {
|
||||
entryId,
|
||||
reason: item.reason || item.message || 'failed',
|
||||
candidates: Array.isArray(item.candidates) ? item.candidates : [],
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
if (result.status === 'error') {
|
||||
markChunkEntriesFailed(failedByEntry, chunk, result.message || firstFailureReason(result) || 'chat_agent_error');
|
||||
aborted = true;
|
||||
continue;
|
||||
}
|
||||
|
||||
const reportedAppliedIds = new Set(result.appliedEntryIds);
|
||||
for (const entryId of reportedAppliedIds) {
|
||||
if (!chunk.entryIds.has(entryId) || chunkFailedIds.has(entryId)) continue;
|
||||
appliedOpsByEntry.set(entryId, (appliedOpsByEntry.get(entryId) || 0) + (chunk.opCountsByEntry.get(entryId) || 0));
|
||||
}
|
||||
|
||||
for (const entryId of chunk.entryIds) {
|
||||
if (reportedAppliedIds.has(entryId) || chunkFailedIds.has(entryId)) continue;
|
||||
if (!failedByEntry.has(entryId)) {
|
||||
failedByEntry.set(entryId, { entryId, reason: 'not_reported_applied', candidates: [] });
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const appliedEntryIds = [];
|
||||
for (const [entryId, expectedOps] of expectedOpsByEntry.entries()) {
|
||||
if (failedByEntry.has(entryId)) continue;
|
||||
if ((appliedOpsByEntry.get(entryId) || 0) === expectedOps && expectedOps > 0) {
|
||||
appliedEntryIds.push(entryId);
|
||||
} else if (!failedByEntry.has(entryId)) {
|
||||
failedByEntry.set(entryId, { entryId, reason: 'not_reported_applied', candidates: [] });
|
||||
}
|
||||
}
|
||||
|
||||
const failed = [...failedByEntry.values()];
|
||||
return {
|
||||
status: failed.length === 0 ? 'done' : appliedEntryIds.length > 0 ? 'partial' : 'error',
|
||||
appliedEntryIds,
|
||||
failed,
|
||||
files: [...files],
|
||||
notes,
|
||||
};
|
||||
}
|
||||
|
||||
function getDeferred(eventId) {
|
||||
return pendingApplyDeferreds.get(eventId) || null;
|
||||
}
|
||||
|
||||
function hasTimedOutId(eventId) {
|
||||
return timedOutApplyIds.has(eventId);
|
||||
}
|
||||
|
||||
function resolveDeferred(eventId, body) {
|
||||
const deferred = pendingApplyDeferreds.get(eventId);
|
||||
if (!deferred) return false;
|
||||
pendingApplyDeferreds.delete(eventId);
|
||||
clearTimeout(deferred.timer);
|
||||
removeManualApplyEvidence(deferred.event?.evidencePath, deferred.cwd || projectCwd());
|
||||
deferred.resolve(body);
|
||||
return true;
|
||||
}
|
||||
|
||||
function rejectDeferred(eventId, reason) {
|
||||
const deferred = pendingApplyDeferreds.get(eventId);
|
||||
if (!deferred) return false;
|
||||
pendingApplyDeferreds.delete(eventId);
|
||||
clearTimeout(deferred.timer);
|
||||
removeManualApplyEvidence(deferred.event?.evidencePath, deferred.cwd || projectCwd());
|
||||
deferred.reject(new Error(reason || 'chat_agent_error'));
|
||||
return true;
|
||||
}
|
||||
|
||||
function referencedManualApplyEvidencePaths(cwdValue = projectCwd()) {
|
||||
const referenced = new Set();
|
||||
const add = (event) => {
|
||||
const fullPath = normalizeManualApplyEvidencePath(event?.evidencePath, cwdValue);
|
||||
if (fullPath) referenced.add(fullPath);
|
||||
};
|
||||
for (const entry of pendingEvents) add(entry.event);
|
||||
for (const deferred of pendingApplyDeferreds.values()) add(deferred.event);
|
||||
return referenced;
|
||||
}
|
||||
|
||||
function pruneStaleEvidence(cwdValue = projectCwd()) {
|
||||
const dir = manualApplyEvidenceDir(cwdValue);
|
||||
if (!fs.existsSync(dir)) return [];
|
||||
const referenced = referencedManualApplyEvidencePaths(cwdValue);
|
||||
const removed = [];
|
||||
for (const name of fs.readdirSync(dir)) {
|
||||
if (!name.endsWith('.json')) continue;
|
||||
const fullPath = path.join(dir, name);
|
||||
if (referenced.has(fullPath)) continue;
|
||||
try {
|
||||
fs.unlinkSync(fullPath);
|
||||
removed.push(fullPath);
|
||||
} catch {
|
||||
// Stale evidence cleanup is best-effort; Apply verification never relies
|
||||
// on deleting these files.
|
||||
}
|
||||
}
|
||||
return removed;
|
||||
}
|
||||
|
||||
function rollbackTimedOutReply(msg) {
|
||||
const details = timedOutApplyIds.get(msg.id);
|
||||
if (!details) return { rolledBackFiles: [], rollbackFailures: [] };
|
||||
timedOutApplyIds.delete(msg.id);
|
||||
return rollbackApplySnapshot(
|
||||
details.batch,
|
||||
details.rollbackSnapshot,
|
||||
msg.data?.files || [],
|
||||
'stale_manual_edit_apply_reply',
|
||||
details.cwd || projectCwd(),
|
||||
);
|
||||
}
|
||||
|
||||
function cancelPendingEvents(pageUrl, reason = 'manual_edit_discarded') {
|
||||
const canceledById = new Map();
|
||||
const shouldCancel = (event) => event?.type === 'manual_edit_apply' && (!pageUrl || event.pageUrl === pageUrl);
|
||||
|
||||
for (let i = pendingEvents.length - 1; i >= 0; i -= 1) {
|
||||
const event = pendingEvents[i]?.event;
|
||||
if (!shouldCancel(event)) continue;
|
||||
pendingEvents.splice(i, 1);
|
||||
removeManualApplyEvidence(event.evidencePath, projectCwd());
|
||||
canceledById.set(event.id, {
|
||||
id: event.id,
|
||||
pageUrl: event.pageUrl,
|
||||
entryCount: event.batch?.entries?.length || 0,
|
||||
});
|
||||
}
|
||||
|
||||
for (const [eventId, deferred] of [...pendingApplyDeferreds.entries()]) {
|
||||
if (!shouldCancel(deferred.event)) continue;
|
||||
pendingApplyDeferreds.delete(eventId);
|
||||
clearTimeout(deferred.timer);
|
||||
const cwdValue = deferred.cwd || projectCwd();
|
||||
const rollback = rollbackApplySnapshot(deferred.batch, deferred.rollbackSnapshot, [], reason, cwdValue);
|
||||
tombstoneTimedOutApplyId(eventId, {
|
||||
batch: deferred.batch,
|
||||
rollbackSnapshot: deferred.rollbackSnapshot,
|
||||
reason,
|
||||
cwd: cwdValue,
|
||||
});
|
||||
removeManualApplyEvidence(deferred.event?.evidencePath, cwdValue);
|
||||
canceledById.set(eventId, {
|
||||
id: eventId,
|
||||
pageUrl: deferred.pageUrl,
|
||||
entryCount: deferred.batch?.entries?.length || 0,
|
||||
rolledBackFiles: rollback.rolledBackFiles,
|
||||
rollbackFailures: rollback.rollbackFailures,
|
||||
});
|
||||
deferred.reject(new Error(reason));
|
||||
}
|
||||
|
||||
if (canceledById.size > 0) flushPendingPolls();
|
||||
return [...canceledById.values()];
|
||||
}
|
||||
|
||||
return {
|
||||
buildAgentAction: buildManualApplyAgentAction,
|
||||
cancelPendingEvents,
|
||||
clearTransaction: (transactionId = null) => clearManualApplyTransaction(projectCwd(), transactionId),
|
||||
countOps: countManualApplyOps,
|
||||
getDeferred,
|
||||
hasTimedOutId,
|
||||
pruneStaleEvidence,
|
||||
pushBatchInChunksAndWait,
|
||||
readTransaction: () => readManualApplyTransaction(projectCwd()),
|
||||
rejectDeferred,
|
||||
resolveDeferred,
|
||||
rollbackTimedOutReply,
|
||||
rollbackTransaction: (opts = {}) => rollbackManualApplyTransaction({
|
||||
cwd: projectCwd(),
|
||||
recordManualEditActivity,
|
||||
...opts,
|
||||
}),
|
||||
summarizeEvent: (event = {}, batch = event.batch) => summarizeManualApplyEvent(event, batch, projectCwd()),
|
||||
validateResultMessage: validateManualApplyResultMessage,
|
||||
writeTransaction: (opts = {}) => writeManualApplyTransaction({ cwd: projectCwd(), ...opts }),
|
||||
};
|
||||
}
|
||||
|
||||
export function manualEditApplyChunkSize(env = process.env) {
|
||||
const raw = Number(env.IMPECCABLE_LIVE_MANUAL_EDIT_CHUNK_SIZE);
|
||||
if (!Number.isFinite(raw)) return DEFAULT_MANUAL_EDIT_APPLY_CHUNK_SIZE;
|
||||
const size = Math.trunc(raw);
|
||||
return Math.max(MIN_MANUAL_EDIT_APPLY_CHUNK_SIZE, Math.min(MAX_MANUAL_EDIT_APPLY_CHUNK_SIZE, size));
|
||||
}
|
||||
|
||||
export function countManualApplyOps(entriesOrBatch) {
|
||||
const entries = Array.isArray(entriesOrBatch)
|
||||
? entriesOrBatch
|
||||
: Array.isArray(entriesOrBatch?.entries) ? entriesOrBatch.entries : [];
|
||||
let count = 0;
|
||||
for (const entry of entries) count += Array.isArray(entry.ops) ? entry.ops.length : 0;
|
||||
return count;
|
||||
}
|
||||
|
||||
export function writeManualApplyEvidence(eventId, batch, cwd = process.cwd()) {
|
||||
const dir = manualApplyEvidenceDir(cwd);
|
||||
fs.mkdirSync(dir, { recursive: true });
|
||||
const evidencePath = path.join(dir, `${eventId}.json`);
|
||||
fs.writeFileSync(evidencePath, JSON.stringify(batch, null, 2) + '\n', 'utf-8');
|
||||
return evidencePath;
|
||||
}
|
||||
|
||||
export function manualApplyEvidenceDir(cwd = process.cwd()) {
|
||||
return path.join(getLiveDir(cwd), 'manual-edit-evidence');
|
||||
}
|
||||
|
||||
export function normalizeManualApplyEvidencePath(evidencePath, cwd = process.cwd()) {
|
||||
if (!evidencePath || typeof evidencePath !== 'string') return null;
|
||||
const fullPath = path.isAbsolute(evidencePath) ? evidencePath : path.resolve(cwd, evidencePath);
|
||||
const evidenceDir = manualApplyEvidenceDir(cwd);
|
||||
const relative = path.relative(evidenceDir, fullPath);
|
||||
if (!relative || relative.startsWith('..') || path.isAbsolute(relative)) return null;
|
||||
if (path.extname(relative) !== '.json') return null;
|
||||
return fullPath;
|
||||
}
|
||||
|
||||
export function removeManualApplyEvidence(evidencePath, cwd = process.cwd()) {
|
||||
const fullPath = normalizeManualApplyEvidencePath(evidencePath, cwd);
|
||||
if (!fullPath) return false;
|
||||
try {
|
||||
fs.unlinkSync(fullPath);
|
||||
return true;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
export function compactManualApplyBatch(batch = {}, cwd = process.cwd()) {
|
||||
const entries = (batch.entries || []).map(compactManualApplyEntry);
|
||||
const candidates = compactManualApplyCandidates(batch.candidates || [], cwd);
|
||||
return {
|
||||
version: batch.version,
|
||||
pageUrl: batch.pageUrl || null,
|
||||
count: batch.count,
|
||||
entries,
|
||||
ops: entries.flatMap((entry) => entry.ops.map((op) => ({ ...op, entryId: entry.id }))),
|
||||
candidates: candidates.length > 0 ? candidates : undefined,
|
||||
context: batch.context ? {
|
||||
bufferPath: batch.context.bufferPath,
|
||||
totalEntries: batch.context.totalEntries,
|
||||
totalOps: batch.context.totalOps,
|
||||
chunkIndex: batch.context.chunkIndex,
|
||||
chunkTotal: batch.context.chunkTotal,
|
||||
totalApplyOps: batch.context.totalApplyOps,
|
||||
} : undefined,
|
||||
};
|
||||
}
|
||||
|
||||
export function compactManualApplyCandidates(candidates, cwd = process.cwd()) {
|
||||
return (Array.isArray(candidates) ? candidates : [])
|
||||
.slice(0, 24)
|
||||
.map((candidate) => ({
|
||||
entryId: candidate.entryId,
|
||||
ref: candidate.ref,
|
||||
sourceHint: compactManualApplySourceMatch(candidate.sourceHint, cwd),
|
||||
textMatches: compactManualApplySourceMatches(candidate.textMatches, 8, cwd),
|
||||
objectKeyMatches: compactManualApplySourceMatches(candidate.objectKeyMatches, 8, cwd),
|
||||
contextTextMatches: compactManualApplySourceMatches(candidate.contextTextMatches, 8, cwd),
|
||||
locatorMatches: compactManualApplySourceMatches(candidate.locatorMatches, 6, cwd),
|
||||
}));
|
||||
}
|
||||
|
||||
function compactManualApplySourceMatches(matches, limit, cwd) {
|
||||
return (Array.isArray(matches) ? matches : [])
|
||||
.slice(0, limit)
|
||||
.map((match) => compactManualApplySourceMatch(match, cwd))
|
||||
.filter(Boolean);
|
||||
}
|
||||
|
||||
function compactManualApplySourceMatch(match, cwd) {
|
||||
if (!match || typeof match !== 'object') return null;
|
||||
const file = match.relativeFile || match.file;
|
||||
if (!file && !match.line) return null;
|
||||
return {
|
||||
file: summarizeManualLogFile(file, cwd),
|
||||
line: match.line || null,
|
||||
column: match.column || null,
|
||||
reason: match.reason || match.kind || undefined,
|
||||
status: match.status || undefined,
|
||||
};
|
||||
}
|
||||
|
||||
function compactManualApplyEntry(entry = {}) {
|
||||
return {
|
||||
id: entry.id,
|
||||
pageUrl: entry.pageUrl,
|
||||
stagedAt: entry.stagedAt || null,
|
||||
element: compactManualApplyContext(entry.element),
|
||||
ops: (entry.ops || []).map(compactManualApplyOp),
|
||||
};
|
||||
}
|
||||
|
||||
function compactManualApplyOp(op = {}) {
|
||||
return {
|
||||
entryId: op.entryId,
|
||||
ref: op.ref,
|
||||
contextRef: op.contextRef,
|
||||
tag: op.tag,
|
||||
elementId: op.elementId,
|
||||
classes: Array.isArray(op.classes) ? op.classes : [],
|
||||
originalText: op.originalText,
|
||||
newText: op.newText,
|
||||
deleted: op.deleted === true || undefined,
|
||||
sourceHint: op.sourceHint || null,
|
||||
leaf: compactManualApplyContext(op.leaf),
|
||||
nearbyEditableTexts: compactNearbyManualEditTexts(op.nearbyEditableTexts),
|
||||
container: compactManualApplyContext(op.container),
|
||||
contextHints: Array.isArray(op.contextHints) ? op.contextHints.slice(0, 8) : undefined,
|
||||
};
|
||||
}
|
||||
|
||||
function compactManualApplyContext(value) {
|
||||
if (!value || typeof value !== 'object') return null;
|
||||
return {
|
||||
ref: value.ref,
|
||||
tagName: value.tagName || value.tag || null,
|
||||
id: value.id || null,
|
||||
classes: Array.isArray(value.classes) ? value.classes : [],
|
||||
textContent: truncateManualApplyText(value.textContent, MANUAL_APPLY_COMPACT_TEXT_LIMIT),
|
||||
};
|
||||
}
|
||||
|
||||
function compactNearbyManualEditTexts(items) {
|
||||
return (Array.isArray(items) ? items : [])
|
||||
.slice(0, MANUAL_APPLY_COMPACT_NEARBY_LIMIT)
|
||||
.map((item) => typeof item === 'string' ? { text: truncateManualApplyText(item, MANUAL_APPLY_COMPACT_TEXT_LIMIT) } : {
|
||||
ref: item?.ref,
|
||||
tag: item?.tag,
|
||||
classes: Array.isArray(item?.classes) ? item.classes : [],
|
||||
text: truncateManualApplyText(item?.text, MANUAL_APPLY_COMPACT_TEXT_LIMIT),
|
||||
});
|
||||
}
|
||||
|
||||
function truncateManualApplyText(value, max) {
|
||||
if (typeof value !== 'string') return value || null;
|
||||
return value.length > max ? value.slice(0, max) : value;
|
||||
}
|
||||
|
||||
function normalizeApplyChunkResult(result) {
|
||||
const status = result?.status === 'partial' ? 'partial' : result?.status === 'error' ? 'error' : 'done';
|
||||
return {
|
||||
status,
|
||||
message: typeof result?.message === 'string' ? result.message : null,
|
||||
appliedEntryIds: Array.isArray(result?.appliedEntryIds) ? result.appliedEntryIds.filter((id) => typeof id === 'string') : [],
|
||||
failed: Array.isArray(result?.failed) ? result.failed.filter(Boolean) : [],
|
||||
files: Array.isArray(result?.files) ? result.files.filter((file) => typeof file === 'string') : [],
|
||||
notes: Array.isArray(result?.notes) ? result.notes.filter((note) => typeof note === 'string') : [],
|
||||
};
|
||||
}
|
||||
|
||||
function manualApplyResultShapeHint(eventId = 'EVENT_ID') {
|
||||
return `Use live-poll.mjs --reply ${eventId} done --data '{"status":"done","appliedEntryIds":["ENTRY_ID"],"failed":[],"files":["src/page.html"],"notes":[]}'`;
|
||||
}
|
||||
|
||||
function invalidManualApplyResult(reason, eventId, extra = {}) {
|
||||
return {
|
||||
ok: false,
|
||||
body: {
|
||||
error: 'invalid_manual_apply_result',
|
||||
reason,
|
||||
hint: manualApplyResultShapeHint(eventId),
|
||||
...extra,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
export function validateManualApplyResultMessage(msg, deferred) {
|
||||
let data = msg?.data;
|
||||
const eventId = msg?.id || deferred?.event?.id || 'EVENT_ID';
|
||||
if (!data || typeof data !== 'object' || Array.isArray(data)) {
|
||||
return invalidManualApplyResult('missing_result_data', eventId);
|
||||
}
|
||||
if ('entries' in data || 'ops' in data) {
|
||||
return invalidManualApplyResult('summary_result_not_allowed', eventId);
|
||||
}
|
||||
if (!['done', 'partial', 'error'].includes(data.status)) {
|
||||
return invalidManualApplyResult('invalid_status', eventId, { status: data.status ?? null });
|
||||
}
|
||||
|
||||
for (const key of ['appliedEntryIds', 'failed', 'files', 'notes']) {
|
||||
if (!Array.isArray(data[key])) {
|
||||
return invalidManualApplyResult(`${key}_must_be_array`, eventId);
|
||||
}
|
||||
}
|
||||
|
||||
for (const [index, value] of data.appliedEntryIds.entries()) {
|
||||
if (typeof value !== 'string' || !value) {
|
||||
return invalidManualApplyResult('appliedEntryIds_must_contain_strings', eventId, { index });
|
||||
}
|
||||
}
|
||||
for (const [index, value] of data.files.entries()) {
|
||||
if (typeof value !== 'string' || !value) {
|
||||
return invalidManualApplyResult('files_must_contain_strings', eventId, { index });
|
||||
}
|
||||
}
|
||||
for (const [index, value] of data.notes.entries()) {
|
||||
if (typeof value !== 'string') {
|
||||
return invalidManualApplyResult('notes_must_contain_strings', eventId, { index });
|
||||
}
|
||||
}
|
||||
for (const [index, item] of data.failed.entries()) {
|
||||
if (!item || typeof item !== 'object' || Array.isArray(item)) {
|
||||
return invalidManualApplyResult('failed_must_contain_objects', eventId, { index });
|
||||
}
|
||||
if (typeof item.entryId !== 'string' || !item.entryId) {
|
||||
return invalidManualApplyResult('failed_entryId_required', eventId, { index });
|
||||
}
|
||||
if (typeof item.reason !== 'string' || !item.reason) {
|
||||
return invalidManualApplyResult('failed_reason_required', eventId, { index });
|
||||
}
|
||||
}
|
||||
|
||||
const eventEntryIds = new Set((deferred?.batch?.entries || []).map((entry) => entry.id).filter(Boolean));
|
||||
for (const entryId of data.appliedEntryIds) {
|
||||
if (eventEntryIds.size > 0 && !eventEntryIds.has(entryId)) {
|
||||
return invalidManualApplyResult('applied_entry_id_not_in_event', eventId, { entryId });
|
||||
}
|
||||
}
|
||||
for (const item of data.failed) {
|
||||
if (eventEntryIds.size > 0 && !eventEntryIds.has(item.entryId)) {
|
||||
return invalidManualApplyResult('failed_entry_id_not_in_event', eventId, { entryId: item.entryId });
|
||||
}
|
||||
}
|
||||
|
||||
if (data.status === 'done') {
|
||||
if (data.failed.length > 0) {
|
||||
return invalidManualApplyResult('done_result_has_failed_entries', eventId);
|
||||
}
|
||||
if (countManualApplyOps(deferred?.batch) > 0 && data.appliedEntryIds.length === 0) {
|
||||
return invalidManualApplyResult('done_result_missing_applied_entry_ids', eventId);
|
||||
}
|
||||
}
|
||||
if (data.status === 'partial' && data.appliedEntryIds.length === 0 && data.failed.length === 0) {
|
||||
return invalidManualApplyResult('partial_result_has_no_entries', eventId);
|
||||
}
|
||||
if (data.status === 'error' && data.appliedEntryIds.length > 0) {
|
||||
return invalidManualApplyResult('error_result_has_applied_entries', eventId);
|
||||
}
|
||||
|
||||
return {
|
||||
ok: true,
|
||||
result: {
|
||||
status: data.status,
|
||||
message: typeof data.message === 'string' ? data.message : undefined,
|
||||
appliedEntryIds: data.appliedEntryIds,
|
||||
failed: data.failed,
|
||||
files: data.files,
|
||||
notes: data.notes,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function firstFailureReason(result) {
|
||||
const first = Array.isArray(result?.failed) ? result.failed.find(Boolean) : null;
|
||||
return first?.reason || first?.message || null;
|
||||
}
|
||||
|
||||
function markChunkEntriesFailed(failedByEntry, chunk, reason) {
|
||||
for (const entryId of chunk.entryIds) {
|
||||
if (failedByEntry.has(entryId)) continue;
|
||||
failedByEntry.set(entryId, { entryId, reason, candidates: [] });
|
||||
}
|
||||
}
|
||||
|
||||
export function splitManualApplyBatch(batch, maxOps) {
|
||||
const totalOpCount = countManualApplyOps(batch);
|
||||
if (totalOpCount <= maxOps) {
|
||||
return [{
|
||||
batch,
|
||||
meta: null,
|
||||
entryIds: new Set((batch?.entries || []).map((entry) => entry.id).filter(Boolean)),
|
||||
opCountsByEntry: new Map((batch?.entries || []).map((entry) => [entry.id, Array.isArray(entry.ops) ? entry.ops.length : 0])),
|
||||
}];
|
||||
}
|
||||
|
||||
const rawChunks = [];
|
||||
let current = createManualApplyChunkBuilder();
|
||||
for (const entry of batch?.entries || []) {
|
||||
const ops = entry.ops || [];
|
||||
if (ops.length <= maxOps) {
|
||||
if (current.opCount > 0 && current.opCount + ops.length > maxOps) {
|
||||
rawChunks.push(current);
|
||||
current = createManualApplyChunkBuilder();
|
||||
}
|
||||
for (const op of ops) addOpToManualApplyChunk(current, entry, op);
|
||||
continue;
|
||||
}
|
||||
if (current.opCount > 0) {
|
||||
rawChunks.push(current);
|
||||
current = createManualApplyChunkBuilder();
|
||||
}
|
||||
for (const op of ops) {
|
||||
if (current.opCount >= maxOps) {
|
||||
rawChunks.push(current);
|
||||
current = createManualApplyChunkBuilder();
|
||||
}
|
||||
addOpToManualApplyChunk(current, entry, op);
|
||||
}
|
||||
}
|
||||
if (current.opCount > 0) rawChunks.push(current);
|
||||
|
||||
return rawChunks.map((chunk, index) => ({
|
||||
batch: {
|
||||
...batch,
|
||||
count: chunk.opCount,
|
||||
entries: chunk.entries,
|
||||
ops: chunk.ops,
|
||||
candidates: filterManualApplyChunkCandidates(batch, chunk.refsByEntry),
|
||||
context: {
|
||||
...(batch?.context || {}),
|
||||
totalEntries: chunk.entries.length,
|
||||
totalOps: chunk.opCount,
|
||||
chunkIndex: index + 1,
|
||||
chunkTotal: rawChunks.length,
|
||||
totalApplyOps: totalOpCount,
|
||||
},
|
||||
},
|
||||
meta: {
|
||||
index: index + 1,
|
||||
total: rawChunks.length,
|
||||
opCount: chunk.opCount,
|
||||
totalOpCount,
|
||||
},
|
||||
entryIds: new Set(chunk.entries.map((entry) => entry.id).filter(Boolean)),
|
||||
opCountsByEntry: chunk.opCountsByEntry,
|
||||
}));
|
||||
}
|
||||
|
||||
function createManualApplyChunkBuilder() {
|
||||
return {
|
||||
entries: [],
|
||||
entryById: new Map(),
|
||||
entryIds: new Set(),
|
||||
ops: [],
|
||||
refsByEntry: new Map(),
|
||||
opCountsByEntry: new Map(),
|
||||
opCount: 0,
|
||||
};
|
||||
}
|
||||
|
||||
function addOpToManualApplyChunk(chunk, entry, op) {
|
||||
let chunkEntry = chunk.entryById.get(entry.id);
|
||||
if (!chunkEntry) {
|
||||
chunkEntry = { ...entry, ops: [] };
|
||||
chunk.entryById.set(entry.id, chunkEntry);
|
||||
chunk.entryIds.add(entry.id);
|
||||
chunk.entries.push(chunkEntry);
|
||||
}
|
||||
chunkEntry.ops.push(op);
|
||||
chunk.ops.push({ ...op, entryId: op.entryId || entry.id });
|
||||
if (!chunk.refsByEntry.has(entry.id)) chunk.refsByEntry.set(entry.id, new Set());
|
||||
if (op.ref) chunk.refsByEntry.get(entry.id).add(op.ref);
|
||||
chunk.opCountsByEntry.set(entry.id, (chunk.opCountsByEntry.get(entry.id) || 0) + 1);
|
||||
chunk.opCount += 1;
|
||||
}
|
||||
|
||||
function filterManualApplyChunkCandidates(batch, refsByEntry) {
|
||||
return (batch?.candidates || []).filter((candidate) => {
|
||||
const refs = refsByEntry.get(candidate.entryId);
|
||||
if (!refs) return false;
|
||||
if (!candidate.ref) return true;
|
||||
return refs.has(candidate.ref);
|
||||
});
|
||||
}
|
||||
|
||||
export function snapshotApplyEventFiles(batch, cwd = process.cwd()) {
|
||||
const snapshot = new Map();
|
||||
for (const relativeFile of collectManualApplyFiles(batch, [], cwd)) {
|
||||
const absolute = path.resolve(cwd, relativeFile);
|
||||
try {
|
||||
snapshot.set(relativeFile, {
|
||||
exists: fs.existsSync(absolute),
|
||||
content: fs.existsSync(absolute) ? fs.readFileSync(absolute, 'utf-8') : '',
|
||||
});
|
||||
} catch {
|
||||
// If a file cannot be read before dispatch, do not attempt late rollback.
|
||||
}
|
||||
}
|
||||
return snapshot;
|
||||
}
|
||||
|
||||
export function manualApplyTransactionPath(cwd = process.cwd()) {
|
||||
return path.join(getLiveDir(cwd), 'manual-edit-apply-transaction.json');
|
||||
}
|
||||
|
||||
export function readManualApplyTransaction(cwd = process.cwd()) {
|
||||
const file = manualApplyTransactionPath(cwd);
|
||||
if (!fs.existsSync(file)) return null;
|
||||
try {
|
||||
return JSON.parse(fs.readFileSync(file, 'utf-8'));
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
export function writeManualApplyTransaction({ cwd = process.cwd(), pageUrl = null, batch }) {
|
||||
const file = manualApplyTransactionPath(cwd);
|
||||
const files = collectManualApplyFiles(batch, [], cwd);
|
||||
const transaction = {
|
||||
version: 1,
|
||||
id: randomUUID().replace(/-/g, '').slice(0, 8),
|
||||
createdAt: new Date().toISOString(),
|
||||
pageUrl,
|
||||
entryIds: (batch?.entries || []).map((entry) => entry.id).filter(Boolean),
|
||||
files: files.map((relativeFile) => {
|
||||
const absolute = path.resolve(cwd, relativeFile);
|
||||
const exists = fs.existsSync(absolute);
|
||||
return {
|
||||
file: relativeFile,
|
||||
exists,
|
||||
content: exists ? fs.readFileSync(absolute, 'utf-8') : '',
|
||||
};
|
||||
}),
|
||||
};
|
||||
fs.mkdirSync(path.dirname(file), { recursive: true });
|
||||
fs.writeFileSync(`${file}.tmp`, JSON.stringify(transaction, null, 2) + '\n', 'utf-8');
|
||||
fs.renameSync(`${file}.tmp`, file);
|
||||
return transaction;
|
||||
}
|
||||
|
||||
export function clearManualApplyTransaction(cwd = process.cwd(), transactionId = null) {
|
||||
const file = manualApplyTransactionPath(cwd);
|
||||
if (!fs.existsSync(file)) return false;
|
||||
if (transactionId) {
|
||||
const existing = readManualApplyTransaction(cwd);
|
||||
if (existing?.id && existing.id !== transactionId) return false;
|
||||
}
|
||||
try {
|
||||
fs.unlinkSync(file);
|
||||
return true;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
export function rollbackManualApplyTransaction({
|
||||
cwd = process.cwd(),
|
||||
pageUrl = null,
|
||||
reason = 'manual_edit_transaction_rollback',
|
||||
recordManualEditActivity = null,
|
||||
} = {}) {
|
||||
const transaction = readManualApplyTransaction(cwd);
|
||||
if (!transaction) return null;
|
||||
if (pageUrl && transaction.pageUrl && transaction.pageUrl !== pageUrl) return null;
|
||||
|
||||
let pendingIds = new Set();
|
||||
try {
|
||||
const buffer = readManualEditsBuffer(cwd);
|
||||
pendingIds = new Set((buffer.entries || []).map((entry) => entry.id).filter(Boolean));
|
||||
} catch {
|
||||
pendingIds = new Set(transaction.entryIds || []);
|
||||
}
|
||||
const shouldRollback = (transaction.entryIds || []).some((id) => pendingIds.has(id));
|
||||
if (!shouldRollback) {
|
||||
clearManualApplyTransaction(cwd, transaction.id);
|
||||
return { id: transaction.id, reason, rolledBackFiles: [], rollbackFailures: [], skipped: 'entries_not_pending' };
|
||||
}
|
||||
|
||||
const rolledBackFiles = [];
|
||||
const rollbackFailures = [];
|
||||
for (const item of transaction.files || []) {
|
||||
const relativeFile = normalizeProjectFile(item.file, cwd);
|
||||
if (!relativeFile) continue;
|
||||
const absolute = path.resolve(cwd, relativeFile);
|
||||
try {
|
||||
if (item.exists) {
|
||||
fs.mkdirSync(path.dirname(absolute), { recursive: true });
|
||||
fs.writeFileSync(absolute, item.content || '', 'utf-8');
|
||||
} else if (fs.existsSync(absolute)) {
|
||||
fs.rmSync(absolute);
|
||||
}
|
||||
rolledBackFiles.push(relativeFile);
|
||||
} catch (err) {
|
||||
rollbackFailures.push({ file: relativeFile, reason: 'restore_failed', message: err.message || String(err) });
|
||||
}
|
||||
}
|
||||
clearManualApplyTransaction(cwd, transaction.id);
|
||||
recordManualEditActivity?.('manual_edit_transaction_rolled_back', {
|
||||
id: transaction.id,
|
||||
pageUrl: transaction.pageUrl || null,
|
||||
reason,
|
||||
entryIds: transaction.entryIds || [],
|
||||
rolledBackFiles: rolledBackFiles.map((file) => summarizeManualLogFile(file, cwd)).filter(Boolean),
|
||||
rollbackFailures: summarizeManualDiagnostics(rollbackFailures, cwd),
|
||||
});
|
||||
return { id: transaction.id, reason, rolledBackFiles, rollbackFailures };
|
||||
}
|
||||
|
||||
export function collectManualApplyFiles(batch, extraFiles = [], cwd = process.cwd()) {
|
||||
const files = [];
|
||||
for (const entry of batch?.entries || []) {
|
||||
for (const op of entry.ops || []) files.push(op.sourceHint?.file);
|
||||
}
|
||||
for (const candidate of batch?.candidates || []) {
|
||||
files.push(candidate.sourceHint?.relativeFile, candidate.sourceHint?.file);
|
||||
for (const item of candidate.textMatches || []) files.push(item.file);
|
||||
for (const item of candidate.objectKeyMatches || []) files.push(item.file);
|
||||
for (const item of candidate.locatorMatches || []) files.push(item.file);
|
||||
for (const item of candidate.contextTextMatches || []) files.push(item.file);
|
||||
}
|
||||
files.push(...(extraFiles || []));
|
||||
return [...new Set(files)]
|
||||
.map((file) => normalizeProjectFile(file, cwd))
|
||||
.filter(Boolean);
|
||||
}
|
||||
|
||||
function normalizeProjectFile(file, cwd = process.cwd()) {
|
||||
if (!file || typeof file !== 'string') return null;
|
||||
const absolute = path.isAbsolute(file) ? file : path.resolve(cwd, file);
|
||||
const relative = path.relative(cwd, absolute);
|
||||
if (!relative || relative.startsWith('..') || path.isAbsolute(relative)) return null;
|
||||
return relative;
|
||||
}
|
||||
|
||||
export function rollbackApplySnapshot(
|
||||
batch,
|
||||
rollbackSnapshot,
|
||||
extraFiles = [],
|
||||
_reason = 'manual_edit_apply_snapshot_rollback',
|
||||
cwd = process.cwd(),
|
||||
) {
|
||||
const scope = collectManualApplyFiles(batch, extraFiles, cwd);
|
||||
const rolledBackFiles = [];
|
||||
const rollbackFailures = [];
|
||||
for (const relativeFile of scope) {
|
||||
const before = rollbackSnapshot?.get(relativeFile);
|
||||
if (!before) continue;
|
||||
const absolute = path.resolve(cwd, relativeFile);
|
||||
try {
|
||||
if (before.exists) {
|
||||
fs.mkdirSync(path.dirname(absolute), { recursive: true });
|
||||
fs.writeFileSync(absolute, before.content, 'utf-8');
|
||||
} else if (fs.existsSync(absolute)) {
|
||||
fs.rmSync(absolute);
|
||||
}
|
||||
rolledBackFiles.push(relativeFile);
|
||||
} catch (err) {
|
||||
rollbackFailures.push({ file: relativeFile, reason: 'restore_failed', message: err.message || String(err) });
|
||||
}
|
||||
}
|
||||
return { rolledBackFiles, rollbackFailures };
|
||||
}
|
||||
|
||||
function manualApplyReplyCommand(eventOrId = 'EVENT_ID') {
|
||||
const id = typeof eventOrId === 'string' ? eventOrId : eventOrId?.id || 'EVENT_ID';
|
||||
return `live-poll.mjs --reply ${id} done --data '<json>'`;
|
||||
}
|
||||
|
||||
export function buildManualApplyAgentAction(eventOrId = 'EVENT_ID') {
|
||||
return {
|
||||
kind: 'manual_edit_apply',
|
||||
required: 'apply_source_edits_then_reply',
|
||||
replyCommand: manualApplyReplyCommand(eventOrId),
|
||||
warning: 'Polling only leases this work item; it does not commit source edits.',
|
||||
};
|
||||
}
|
||||
|
||||
export function summarizeManualApplyEvent(event = {}, batch = event.batch, cwd = process.cwd()) {
|
||||
const entries = Array.isArray(batch?.entries) ? batch.entries : [];
|
||||
const opCount = entries.reduce((sum, entry) => sum + (Array.isArray(entry.ops) ? entry.ops.length : 0), 0);
|
||||
return {
|
||||
pageUrl: event.pageUrl || null,
|
||||
chunk: event.chunk || null,
|
||||
entryCount: entries.length,
|
||||
opCount,
|
||||
files: collectManualApplyFiles(batch, [], cwd),
|
||||
};
|
||||
}
|
||||
|
||||
export function summarizeManualApplyFailures(failed, cwd = process.cwd()) {
|
||||
if (!Array.isArray(failed)) return [];
|
||||
return failed.slice(0, 20).map((item) => ({
|
||||
id: item.id || item.entryId || null,
|
||||
reason: item.reason || item.message || 'failed',
|
||||
message: compactManualLogText(item.message, 300),
|
||||
files: Array.isArray(item.files) ? item.files.slice(0, 12).map((file) => summarizeManualLogFile(file, cwd)).filter(Boolean) : undefined,
|
||||
checks: summarizeManualDiagnostics(item.checks, cwd),
|
||||
failures: summarizeManualDiagnostics(item.failures, cwd),
|
||||
candidates: summarizeManualDiagnostics(item.candidates, cwd),
|
||||
}));
|
||||
}
|
||||
|
||||
export function summarizeManualDiagnostics(items, cwd = process.cwd()) {
|
||||
if (!Array.isArray(items) || items.length === 0) return undefined;
|
||||
return items.slice(0, 12).map((item) => ({
|
||||
reason: item.reason || item.kind || undefined,
|
||||
detail: compactManualLogText(item.detail, 220),
|
||||
message: compactManualLogText(item.message, 300),
|
||||
file: summarizeManualLogFile(item.file || item.relativeFile, cwd),
|
||||
line: item.line || undefined,
|
||||
ref: compactManualLogText(item.ref, 180),
|
||||
marker: compactManualLogText(item.marker, 120),
|
||||
files: Array.isArray(item.files) ? item.files.slice(0, 8).map((file) => summarizeManualLogFile(file, cwd)).filter(Boolean) : undefined,
|
||||
}));
|
||||
}
|
||||
|
||||
export function summarizeManualLogFile(file, cwd = process.cwd()) {
|
||||
if (!file || typeof file !== 'string') return undefined;
|
||||
if (!path.isAbsolute(file)) return file;
|
||||
const relative = path.relative(cwd, file);
|
||||
return relative && !relative.startsWith('..') && !path.isAbsolute(relative) ? relative : file;
|
||||
}
|
||||
|
||||
export function compactManualLogText(value, max = 200) {
|
||||
if (typeof value !== 'string') return undefined;
|
||||
const normalized = value.replace(/\s+/g, ' ').trim();
|
||||
if (normalized.length <= max) return normalized;
|
||||
return normalized.slice(0, max) + `... [truncated ${normalized.length - max} chars]`;
|
||||
}
|
||||
@@ -0,0 +1,357 @@
|
||||
import { validateEvent } from './event-validation.mjs';
|
||||
import {
|
||||
countByPage as countPendingByPage,
|
||||
readBuffer as readManualEditsBuffer,
|
||||
removeEntries as removeManualEditEntries,
|
||||
stageEntry as stageManualEditEntry,
|
||||
truncateBuffer as truncateManualEditsBuffer,
|
||||
} from './manual-edits-buffer.mjs';
|
||||
import {
|
||||
summarizeManualApplyFailures,
|
||||
summarizeManualDiagnostics,
|
||||
summarizeManualLogFile,
|
||||
} from './manual-apply.mjs';
|
||||
import { buildManualEditEvidence } from '../live-manual-edit-evidence.mjs';
|
||||
import { commitManualEdits } from '../live-commit-manual-edits.mjs';
|
||||
|
||||
export function createManualEditRoutes({
|
||||
getToken,
|
||||
manualApply,
|
||||
recordManualEditActivity,
|
||||
getManualEditStatus,
|
||||
chatAgentLikelyActive,
|
||||
cwd = () => process.cwd(),
|
||||
env = () => process.env,
|
||||
} = {}) {
|
||||
const projectCwd = () => typeof cwd === 'function' ? cwd() : cwd || process.cwd();
|
||||
const currentEnv = () => typeof env === 'function' ? env() : env || process.env;
|
||||
|
||||
return function handleManualEditRoute(req, res, url) {
|
||||
const p = url.pathname;
|
||||
|
||||
// Save stages entries; Apply commits the staged page batch through the
|
||||
// local AI copy-edit runner.
|
||||
if (p === '/manual-edit-stash' && req.method === 'POST') {
|
||||
let body = '';
|
||||
req.on('data', (c) => { body += c; });
|
||||
req.on('end', () => {
|
||||
let msg;
|
||||
try { msg = JSON.parse(body); } catch {
|
||||
sendJson(res, 400, { error: 'Invalid JSON' });
|
||||
return;
|
||||
}
|
||||
if (msg.token !== getToken()) {
|
||||
sendJson(res, 401, { error: 'Unauthorized' });
|
||||
return;
|
||||
}
|
||||
const error = validateEvent({ ...msg, type: 'manual_edits' });
|
||||
if (error) {
|
||||
sendJson(res, 400, { error });
|
||||
return;
|
||||
}
|
||||
try {
|
||||
stageManualEditEntry(projectCwd(), {
|
||||
id: msg.id,
|
||||
pageUrl: msg.pageUrl,
|
||||
element: msg.element,
|
||||
ops: msg.ops,
|
||||
});
|
||||
} catch (err) {
|
||||
sendJson(res, 500, { error: 'stash_write_failed', message: err.message });
|
||||
return;
|
||||
}
|
||||
const { totalCount, perPage } = countPendingByPage(projectCwd());
|
||||
const pendingCount = perPage[msg.pageUrl] || 0;
|
||||
recordManualEditActivity('manual_edit_stashed', {
|
||||
id: msg.id,
|
||||
pageUrl: msg.pageUrl,
|
||||
opCount: msg.ops.length,
|
||||
pendingCount,
|
||||
totalCount,
|
||||
hintedFileCount: new Set((msg.ops || []).map((op) => summarizeManualLogFile(op.sourceHint?.file, projectCwd())).filter(Boolean)).size,
|
||||
});
|
||||
sendJson(res, 200, { ok: true, pendingCount, totalCount, perPage });
|
||||
});
|
||||
return true;
|
||||
}
|
||||
|
||||
if (p === '/manual-edit-stash' && req.method === 'GET') {
|
||||
const token = url.searchParams.get('token');
|
||||
if (token !== getToken()) { res.writeHead(401); res.end('Unauthorized'); return true; }
|
||||
const pageUrl = url.searchParams.get('pageUrl') || '';
|
||||
const { totalCount, perPage } = countPendingByPage(projectCwd());
|
||||
const buffer = readManualEditsBuffer(projectCwd());
|
||||
const entriesForPage = pageUrl ? buffer.entries.filter((e) => e.pageUrl === pageUrl) : buffer.entries;
|
||||
sendJson(res, 200, {
|
||||
count: pageUrl ? (perPage[pageUrl] || 0) : totalCount,
|
||||
totalCount,
|
||||
perPage,
|
||||
entries: entriesForPage,
|
||||
});
|
||||
return true;
|
||||
}
|
||||
|
||||
if (p === '/manual-edit-commit' && req.method === 'POST') {
|
||||
const token = url.searchParams.get('token');
|
||||
if (token !== getToken()) { res.writeHead(401); res.end('Unauthorized'); return true; }
|
||||
const pageUrl = url.searchParams.get('pageUrl');
|
||||
const asyncMode = /^(1|true|yes)$/i.test(url.searchParams.get('async') || '');
|
||||
const repairOnly = /^(1|true|yes)$/i.test(url.searchParams.get('repair') || '');
|
||||
const existingTransaction = manualApply.readTransaction();
|
||||
if (repairOnly && !existingTransaction) {
|
||||
sendJson(res, 409, { error: 'manual_edit_repair_transaction_missing' });
|
||||
return true;
|
||||
}
|
||||
const recoveredTransaction = repairOnly ? null : manualApply.rollbackTransaction({
|
||||
pageUrl,
|
||||
reason: 'manual_edit_commit_recovered_abandoned_transaction',
|
||||
});
|
||||
const before = getManualEditStatus();
|
||||
const pendingCount = pageUrl ? (before.perPage[pageUrl] || 0) : before.totalCount;
|
||||
recordManualEditActivity('manual_edit_commit_started', {
|
||||
pageUrl,
|
||||
repairOnly,
|
||||
pendingCount,
|
||||
totalCount: before.totalCount,
|
||||
recoveredTransaction: recoveredTransaction ? {
|
||||
id: recoveredTransaction.id,
|
||||
reason: recoveredTransaction.reason,
|
||||
skipped: recoveredTransaction.skipped,
|
||||
rolledBackFiles: recoveredTransaction.rolledBackFiles,
|
||||
rollbackFailures: summarizeManualDiagnostics(recoveredTransaction.rollbackFailures, projectCwd()),
|
||||
} : null,
|
||||
...summarizePendingManualEditBatch(projectCwd(), pageUrl),
|
||||
});
|
||||
if (asyncMode) {
|
||||
sendJson(res, 202, {
|
||||
status: 'started',
|
||||
pendingCount,
|
||||
totalCount: before.totalCount,
|
||||
perPage: before.perPage,
|
||||
});
|
||||
}
|
||||
(async () => {
|
||||
let result;
|
||||
let routedProvider = 'subprocess';
|
||||
let transaction = null;
|
||||
let commitBatch = null;
|
||||
try {
|
||||
if (pendingCount > 0) {
|
||||
const transactionBatch = buildManualEditEvidence({ cwd: projectCwd(), pageUrl });
|
||||
commitBatch = transactionBatch;
|
||||
if (!repairOnly && manualApply.countOps(transactionBatch) > 0) {
|
||||
transaction = manualApply.writeTransaction({
|
||||
pageUrl,
|
||||
batch: transactionBatch,
|
||||
});
|
||||
} else if (repairOnly && existingTransaction) {
|
||||
transaction = existingTransaction;
|
||||
}
|
||||
}
|
||||
const envValue = currentEnv();
|
||||
const requestedMode = (envValue.IMPECCABLE_LIVE_COPY_AGENT || 'auto').trim().toLowerCase();
|
||||
const useChatRoute = requestedMode === 'chat'
|
||||
|| (requestedMode === 'auto' && chatAgentLikelyActive());
|
||||
if (useChatRoute) {
|
||||
routedProvider = 'chat';
|
||||
const timeoutMs = Number(envValue.IMPECCABLE_LIVE_COPY_AGENT_TIMEOUT_MS || 120000);
|
||||
result = await commitManualEdits({
|
||||
cwd: projectCwd(),
|
||||
pageUrl,
|
||||
provider: 'chat',
|
||||
env: envValue,
|
||||
timeoutMs,
|
||||
chatAvailable: chatAgentLikelyActive,
|
||||
applyBatchToSource: (batch, context) => manualApply.pushBatchInChunksAndWait(batch, pageUrl, context),
|
||||
repairOnly,
|
||||
transactionId: transaction?.id || existingTransaction?.id || null,
|
||||
batch: commitBatch,
|
||||
});
|
||||
} else {
|
||||
const timeoutMs = Number(envValue.IMPECCABLE_LIVE_COPY_AGENT_TIMEOUT_MS || 120000);
|
||||
const provider = ['codex', 'claude', 'mock'].includes(requestedMode) ? requestedMode : undefined;
|
||||
result = await commitManualEdits({
|
||||
cwd: projectCwd(),
|
||||
pageUrl,
|
||||
provider,
|
||||
env: envValue,
|
||||
timeoutMs,
|
||||
chatAvailable: chatAgentLikelyActive,
|
||||
repairOnly,
|
||||
transactionId: transaction?.id || existingTransaction?.id || null,
|
||||
batch: commitBatch,
|
||||
});
|
||||
}
|
||||
} catch (err) {
|
||||
if (transaction) {
|
||||
manualApply.rollbackTransaction({
|
||||
pageUrl,
|
||||
reason: 'manual_edit_commit_exception',
|
||||
});
|
||||
}
|
||||
const message = err.stderr?.toString?.() || err.message;
|
||||
recordManualEditActivity('manual_edit_commit_failed', {
|
||||
pageUrl,
|
||||
provider: routedProvider,
|
||||
error: 'manual_edit_commit_failed',
|
||||
message,
|
||||
transactionId: transaction?.id || null,
|
||||
});
|
||||
if (!asyncMode) {
|
||||
sendJson(res, 500, {
|
||||
error: 'manual_edit_commit_failed',
|
||||
message,
|
||||
});
|
||||
}
|
||||
return;
|
||||
} finally {
|
||||
if (transaction) {
|
||||
const shouldKeepTransaction = result?.needsManualDecision === true;
|
||||
if (!shouldKeepTransaction) manualApply.clearTransaction(transaction.id);
|
||||
}
|
||||
}
|
||||
const { totalCount, perPage } = countPendingByPage(projectCwd());
|
||||
if (result?.needsManualDecision) {
|
||||
recordManualEditActivity('manual_edit_repair_needs_decision', {
|
||||
pageUrl,
|
||||
provider: routedProvider,
|
||||
transactionId: transaction?.id || existingTransaction?.id || null,
|
||||
repair: result.repair || null,
|
||||
failed: summarizeManualApplyFailures(result.failed, projectCwd()),
|
||||
files: Array.isArray(result.files) ? result.files.slice(0, 20).map((file) => summarizeManualLogFile(file, projectCwd())).filter(Boolean) : [],
|
||||
remainingCount: pageUrl ? (perPage[pageUrl] || 0) : totalCount,
|
||||
totalCount,
|
||||
});
|
||||
} else {
|
||||
recordManualEditActivity('manual_edit_commit_done', {
|
||||
pageUrl,
|
||||
provider: routedProvider,
|
||||
reason: result.reason || null,
|
||||
repair: result.repair || null,
|
||||
appliedCount: Array.isArray(result.applied) ? result.applied.length : 0,
|
||||
failedCount: Array.isArray(result.failed) ? result.failed.length : 0,
|
||||
failed: summarizeManualApplyFailures(result.failed, projectCwd()),
|
||||
files: Array.isArray(result.files) ? result.files.slice(0, 20).map((file) => summarizeManualLogFile(file, projectCwd())).filter(Boolean) : [],
|
||||
warnings: summarizeManualDiagnostics(result.warnings, projectCwd()),
|
||||
rolledBackFiles: Array.isArray(result.rolledBackFiles) ? result.rolledBackFiles.slice(0, 20).map((file) => summarizeManualLogFile(file, projectCwd())).filter(Boolean) : [],
|
||||
rollbackFailures: summarizeManualDiagnostics(result.rollbackFailures, projectCwd()),
|
||||
unreportedFiles: Array.isArray(result.unreportedFiles) ? result.unreportedFiles.slice(0, 20).map((file) => summarizeManualLogFile(file, projectCwd())).filter(Boolean) : undefined,
|
||||
noteCount: Array.isArray(result.notes) ? result.notes.length : 0,
|
||||
cleared: result.cleared || 0,
|
||||
remainingCount: pageUrl ? (perPage[pageUrl] || 0) : totalCount,
|
||||
totalCount,
|
||||
});
|
||||
}
|
||||
if (!asyncMode) {
|
||||
sendJson(res, 200, { ...result, totalCount, perPage });
|
||||
}
|
||||
})();
|
||||
return true;
|
||||
}
|
||||
|
||||
if (p === '/manual-edit-repair-decision' && req.method === 'POST') {
|
||||
let body = '';
|
||||
req.on('data', (chunk) => { body += chunk; });
|
||||
req.on('end', () => {
|
||||
let payload = {};
|
||||
try { payload = body ? JSON.parse(body) : {}; } catch {
|
||||
sendJson(res, 400, { error: 'Invalid JSON' });
|
||||
return;
|
||||
}
|
||||
const token = payload.token || url.searchParams.get('token');
|
||||
if (token !== getToken()) { res.writeHead(401); res.end('Unauthorized'); return; }
|
||||
const pageUrl = payload.pageUrl || url.searchParams.get('pageUrl') || null;
|
||||
const action = String(payload.action || url.searchParams.get('action') || '').trim().toLowerCase();
|
||||
if (action !== 'rollback') {
|
||||
sendJson(res, 400, { error: 'unsupported_manual_edit_repair_decision', action });
|
||||
return;
|
||||
}
|
||||
const rollback = manualApply.rollbackTransaction({
|
||||
pageUrl,
|
||||
reason: 'manual_edit_user_requested_rollback',
|
||||
});
|
||||
const { totalCount, perPage } = countPendingByPage(projectCwd());
|
||||
const response = {
|
||||
action,
|
||||
pageUrl,
|
||||
rollback,
|
||||
remainingCount: pageUrl ? (perPage[pageUrl] || 0) : totalCount,
|
||||
totalCount,
|
||||
perPage,
|
||||
};
|
||||
recordManualEditActivity('manual_edit_repair_rollback_done', response);
|
||||
sendJson(res, 200, response);
|
||||
});
|
||||
return true;
|
||||
}
|
||||
|
||||
if (p === '/manual-edit-discard' && req.method === 'POST') {
|
||||
const token = url.searchParams.get('token');
|
||||
if (token !== getToken()) { res.writeHead(401); res.end('Unauthorized'); return true; }
|
||||
const pageUrl = url.searchParams.get('pageUrl');
|
||||
let discarded;
|
||||
let discardedEntries = [];
|
||||
let canceledApplyEvents = [];
|
||||
let transactionRollback = null;
|
||||
try {
|
||||
const buffer = readManualEditsBuffer(projectCwd());
|
||||
transactionRollback = manualApply.rollbackTransaction({
|
||||
pageUrl,
|
||||
reason: 'manual_edit_discarded',
|
||||
});
|
||||
if (pageUrl) {
|
||||
discardedEntries = buffer.entries.filter((entry) => entry.pageUrl === pageUrl);
|
||||
discarded = removeManualEditEntries(projectCwd(), (entry) => entry.pageUrl === pageUrl);
|
||||
} else {
|
||||
discardedEntries = buffer.entries;
|
||||
discarded = truncateManualEditsBuffer(projectCwd());
|
||||
}
|
||||
canceledApplyEvents = manualApply.cancelPendingEvents(pageUrl);
|
||||
} catch (err) {
|
||||
sendJson(res, 500, { error: 'discard_failed', message: err.message });
|
||||
return true;
|
||||
}
|
||||
const { totalCount, perPage } = countPendingByPage(projectCwd());
|
||||
recordManualEditActivity('manual_edit_discarded', {
|
||||
pageUrl,
|
||||
discarded,
|
||||
canceledApplyIds: canceledApplyEvents.map((event) => event.id),
|
||||
transactionRollback: transactionRollback ? {
|
||||
id: transactionRollback.id,
|
||||
rolledBackFiles: transactionRollback.rolledBackFiles?.map((file) => summarizeManualLogFile(file, projectCwd())).filter(Boolean) || [],
|
||||
rollbackFailures: summarizeManualDiagnostics(transactionRollback.rollbackFailures, projectCwd()),
|
||||
skipped: transactionRollback.skipped,
|
||||
} : undefined,
|
||||
totalCount,
|
||||
});
|
||||
sendJson(res, 200, { discarded, entries: discardedEntries, canceledApplyEvents, totalCount, perPage });
|
||||
return true;
|
||||
}
|
||||
|
||||
if (p === '/manual-edit' && req.method === 'POST') {
|
||||
sendJson(res, 410, { error: '/manual-edit is removed; use /manual-edit-stash and /manual-edit-commit for staged copy edits.' });
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
};
|
||||
}
|
||||
|
||||
function sendJson(res, status, body) {
|
||||
res.writeHead(status, { 'Content-Type': 'application/json' });
|
||||
res.end(JSON.stringify(body));
|
||||
}
|
||||
|
||||
function summarizePendingManualEditBatch(cwd, pageUrl = null) {
|
||||
try {
|
||||
const buffer = readManualEditsBuffer(cwd);
|
||||
const entries = (buffer.entries || [])
|
||||
.filter((entry) => !pageUrl || entry.pageUrl === pageUrl);
|
||||
return {
|
||||
pendingEntryCount: entries.length,
|
||||
pendingOpCount: entries.reduce((sum, entry) => sum + (entry.ops?.length || 0), 0),
|
||||
};
|
||||
} catch (err) {
|
||||
return { pendingSummaryError: err.message || String(err) };
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,152 @@
|
||||
/**
|
||||
* Shared helpers for the pending-manual-edits buffer on disk.
|
||||
*
|
||||
* Location: .impeccable/live/pending-manual-edits.json (project-local).
|
||||
* Schema: { version: 1, entries: [{ id, pageUrl, element, ops, stagedAt }] }
|
||||
*
|
||||
* Each entry corresponds to one Save action from the browser. Ops merge by
|
||||
* (pageUrl, ref): if the user re-edits the same element before committing, the
|
||||
* existing entry's `newText` is replaced and `originalText` is kept (it holds
|
||||
* the real source state).
|
||||
*/
|
||||
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import { getLiveDir } from '../lib/impeccable-paths.mjs';
|
||||
|
||||
const BUFFER_VERSION = 1;
|
||||
const BUFFER_FILENAME = 'pending-manual-edits.json';
|
||||
|
||||
export function getBufferPath(cwd = process.cwd()) {
|
||||
return path.join(getLiveDir(cwd), BUFFER_FILENAME);
|
||||
}
|
||||
|
||||
export function readBuffer(cwd = process.cwd()) {
|
||||
return readBufferInternal(cwd, { strict: false });
|
||||
}
|
||||
|
||||
export function readBufferStrict(cwd = process.cwd()) {
|
||||
return readBufferInternal(cwd, { strict: true });
|
||||
}
|
||||
|
||||
function readBufferInternal(cwd, { strict }) {
|
||||
const filePath = getBufferPath(cwd);
|
||||
try {
|
||||
const raw = fs.readFileSync(filePath, 'utf-8');
|
||||
const parsed = JSON.parse(raw);
|
||||
if (!parsed || typeof parsed !== 'object' || !Array.isArray(parsed.entries)) {
|
||||
if (strict) throw new Error('manual_edit_buffer_invalid_schema');
|
||||
return { version: BUFFER_VERSION, entries: [] };
|
||||
}
|
||||
return { version: BUFFER_VERSION, entries: parsed.entries };
|
||||
} catch (err) {
|
||||
if (strict && err?.code !== 'ENOENT') {
|
||||
throw new Error('manual_edit_buffer_unreadable: ' + (err.message || String(err)));
|
||||
}
|
||||
return { version: BUFFER_VERSION, entries: [] };
|
||||
}
|
||||
}
|
||||
|
||||
export function writeBuffer(cwd, buffer) {
|
||||
const filePath = getBufferPath(cwd);
|
||||
fs.mkdirSync(path.dirname(filePath), { recursive: true });
|
||||
fs.writeFileSync(filePath, JSON.stringify({ version: BUFFER_VERSION, entries: buffer.entries }, null, 2));
|
||||
}
|
||||
|
||||
/**
|
||||
* Merge a new entry into the buffer. For each op in the new entry, if there's
|
||||
* already a buffered op for the same (pageUrl, ref), update that op's newText
|
||||
* and keep its original originalText (the true source state). Otherwise add
|
||||
* the op (creating an entry if needed).
|
||||
*
|
||||
* Multiple ops in one Save are allowed; each is keyed by (pageUrl, ref).
|
||||
*/
|
||||
export function stageEntry(cwd, newEntry) {
|
||||
const buf = readBufferStrict(cwd);
|
||||
const pageUrl = newEntry.pageUrl;
|
||||
for (const newOp of newEntry.ops) {
|
||||
let mergedIntoExisting = false;
|
||||
for (const existing of buf.entries) {
|
||||
if (existing.pageUrl !== pageUrl) continue;
|
||||
const existingOpIdx = existing.ops.findIndex((op) => op.ref === newOp.ref);
|
||||
if (existingOpIdx >= 0) {
|
||||
// Keep the original source text but refresh the latest DOM/source evidence.
|
||||
existing.ops[existingOpIdx] = {
|
||||
...newOp,
|
||||
originalText: existing.ops[existingOpIdx].originalText,
|
||||
newText: newOp.newText,
|
||||
deleted: newOp.deleted || false,
|
||||
};
|
||||
if (newEntry.element) existing.element = newEntry.element;
|
||||
existing.stagedAt = new Date().toISOString();
|
||||
mergedIntoExisting = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (mergedIntoExisting) continue;
|
||||
// No existing op for this (pageUrl, ref). Find or create an entry to hold it.
|
||||
let entry = buf.entries.find((e) => e.pageUrl === pageUrl && e.id === newEntry.id);
|
||||
if (!entry) {
|
||||
entry = {
|
||||
id: newEntry.id,
|
||||
pageUrl,
|
||||
element: newEntry.element,
|
||||
ops: [],
|
||||
stagedAt: new Date().toISOString(),
|
||||
};
|
||||
buf.entries.push(entry);
|
||||
}
|
||||
entry.ops.push(newOp);
|
||||
entry.stagedAt = new Date().toISOString();
|
||||
}
|
||||
writeBuffer(cwd, buf);
|
||||
return buf;
|
||||
}
|
||||
|
||||
/**
|
||||
* Remove entries matching a predicate. Returns count of removed *ops* (not
|
||||
* entries) so callers report a unit consistent with truncateBuffer and the
|
||||
* pill's per-page op count. Empty entries (no ops left) are also pruned.
|
||||
*/
|
||||
export function removeEntries(cwd, predicate) {
|
||||
const buf = readBuffer(cwd);
|
||||
let removedOps = 0;
|
||||
const kept = [];
|
||||
for (const entry of buf.entries) {
|
||||
if (predicate(entry)) {
|
||||
removedOps += entry.ops?.length || 0;
|
||||
} else if (entry.ops && entry.ops.length > 0) {
|
||||
kept.push(entry);
|
||||
}
|
||||
}
|
||||
buf.entries = kept;
|
||||
writeBuffer(cwd, buf);
|
||||
return removedOps;
|
||||
}
|
||||
|
||||
/**
|
||||
* Count by page for the counter UI. Returns { totalCount, perPage: {[pageUrl]: count} }.
|
||||
*/
|
||||
export function countByPage(cwd = process.cwd()) {
|
||||
const buf = readBuffer(cwd);
|
||||
const perPage = {};
|
||||
let totalCount = 0;
|
||||
for (const entry of buf.entries) {
|
||||
const n = entry.ops.length;
|
||||
perPage[entry.pageUrl] = (perPage[entry.pageUrl] || 0) + n;
|
||||
totalCount += n;
|
||||
}
|
||||
return { totalCount, perPage };
|
||||
}
|
||||
|
||||
/**
|
||||
* Truncate the buffer to empty (used by discard-all). Returns the count of
|
||||
* removed ops.
|
||||
*/
|
||||
export function truncateBuffer(cwd) {
|
||||
const buf = readBuffer(cwd);
|
||||
let removed = 0;
|
||||
for (const entry of buf.entries) removed += entry.ops.length;
|
||||
writeBuffer(cwd, { version: BUFFER_VERSION, entries: [] });
|
||||
return removed;
|
||||
}
|
||||
@@ -0,0 +1,289 @@
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import { getLegacyLiveSessionsDir, getLiveSessionsDir } from '../lib/impeccable-paths.mjs';
|
||||
|
||||
const COMPLETED_PHASES = new Set(['completed', 'discarded']);
|
||||
|
||||
export function createLiveSessionStore({ cwd = process.cwd(), sessionId } = {}) {
|
||||
const rootDir = getLiveSessionsDir(cwd);
|
||||
const legacyRootDir = getLegacyLiveSessionsDir(cwd);
|
||||
fs.mkdirSync(rootDir, { recursive: true });
|
||||
const snapshotCache = new Map();
|
||||
|
||||
function loadCachedOrRebuild(id) {
|
||||
const cached = snapshotCache.get(id);
|
||||
if (cached) return cached;
|
||||
const journalPath = getReadableJournalPath(id);
|
||||
const rebuilt = rebuildSnapshotFromJournal(journalPath, id);
|
||||
snapshotCache.set(id, rebuilt);
|
||||
return rebuilt;
|
||||
}
|
||||
|
||||
function getReadableJournalPath(id) {
|
||||
const primary = getJournalPath(rootDir, id);
|
||||
if (fs.existsSync(primary)) return primary;
|
||||
const legacy = getJournalPath(legacyRootDir, id);
|
||||
if (fs.existsSync(legacy)) return legacy;
|
||||
return primary;
|
||||
}
|
||||
|
||||
return {
|
||||
rootDir,
|
||||
legacyRootDir,
|
||||
appendEvent(event) {
|
||||
const normalized = normalizeEvent(event, sessionId);
|
||||
const journalPath = getJournalPath(rootDir, normalized.id);
|
||||
const snapshotPath = getSnapshotPath(rootDir, normalized.id);
|
||||
const legacyJournalPath = getJournalPath(legacyRootDir, normalized.id);
|
||||
if (!fs.existsSync(journalPath) && fs.existsSync(legacyJournalPath)) {
|
||||
fs.copyFileSync(legacyJournalPath, journalPath);
|
||||
}
|
||||
const prior = loadCachedOrRebuild(normalized.id);
|
||||
const seq = prior.nextSeq;
|
||||
const entry = {
|
||||
seq,
|
||||
id: normalized.id,
|
||||
type: normalized.type,
|
||||
ts: new Date().toISOString(),
|
||||
event: normalized,
|
||||
};
|
||||
fs.appendFileSync(journalPath, JSON.stringify(entry) + '\n');
|
||||
const next = applyEvent(prior.snapshot, entry, prior.diagnostics);
|
||||
snapshotCache.set(normalized.id, { snapshot: next, diagnostics: next.diagnostics || [], nextSeq: seq + 1 });
|
||||
writeSnapshot(snapshotPath, next);
|
||||
return next;
|
||||
},
|
||||
getSnapshot(id = sessionId, opts = {}) {
|
||||
if (!id) throw new Error('session id required');
|
||||
const journalPath = getReadableJournalPath(id);
|
||||
const snapshotPath = getSnapshotPath(rootDir, id);
|
||||
const rebuilt = rebuildSnapshotFromJournal(journalPath, id);
|
||||
snapshotCache.set(id, rebuilt);
|
||||
writeSnapshot(snapshotPath, rebuilt.snapshot);
|
||||
if (!opts.includeCompleted && COMPLETED_PHASES.has(rebuilt.snapshot.phase)) return null;
|
||||
return rebuilt.snapshot;
|
||||
},
|
||||
listActiveSessions() {
|
||||
const ids = new Set();
|
||||
for (const dir of [legacyRootDir, rootDir]) {
|
||||
if (!fs.existsSync(dir)) continue;
|
||||
for (const name of fs.readdirSync(dir)) {
|
||||
if (name.endsWith('.jsonl')) ids.add(name.slice(0, -'.jsonl'.length));
|
||||
}
|
||||
}
|
||||
return [...ids]
|
||||
.sort()
|
||||
.map((id) => this.getSnapshot(id))
|
||||
.filter(Boolean);
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function normalizeEvent(event, fallbackId) {
|
||||
if (!event || typeof event !== 'object') throw new Error('event object required');
|
||||
const id = event.id || fallbackId;
|
||||
if (!id || typeof id !== 'string') throw new Error('event id required');
|
||||
if (!event.type || typeof event.type !== 'string') throw new Error('event type required');
|
||||
return { ...event, id };
|
||||
}
|
||||
|
||||
function getJournalPath(rootDir, id) {
|
||||
return path.join(rootDir, safeSessionId(id) + '.jsonl');
|
||||
}
|
||||
|
||||
function getSnapshotPath(rootDir, id) {
|
||||
return path.join(rootDir, safeSessionId(id) + '.snapshot.json');
|
||||
}
|
||||
|
||||
function safeSessionId(id) {
|
||||
if (!/^[A-Za-z0-9_-]{1,128}$/.test(id)) throw new Error('invalid session id: ' + id);
|
||||
return id;
|
||||
}
|
||||
|
||||
function baseSnapshot(id) {
|
||||
return {
|
||||
id,
|
||||
phase: 'new',
|
||||
pageUrl: null,
|
||||
sourceFile: null,
|
||||
previewFile: null,
|
||||
previewMode: null,
|
||||
expectedVariants: 0,
|
||||
arrivedVariants: 0,
|
||||
visibleVariant: null,
|
||||
paramValues: {},
|
||||
pendingEventSeq: null,
|
||||
pendingEvent: null,
|
||||
deliveryLease: null,
|
||||
checkpointRevision: 0,
|
||||
activeOwner: null,
|
||||
sourceMarkers: {},
|
||||
fallbackMode: null,
|
||||
annotationArtifacts: [],
|
||||
diagnostics: [],
|
||||
updatedAt: null,
|
||||
};
|
||||
}
|
||||
|
||||
function rebuildSnapshotFromJournal(journalPath, id) {
|
||||
let snapshot = baseSnapshot(id);
|
||||
const diagnostics = [];
|
||||
let nextSeq = 1;
|
||||
if (!fs.existsSync(journalPath)) return { snapshot, diagnostics, nextSeq };
|
||||
|
||||
const lines = fs.readFileSync(journalPath, 'utf-8').split('\n');
|
||||
for (let i = 0; i < lines.length; i++) {
|
||||
const line = lines[i];
|
||||
if (!line.trim()) continue;
|
||||
try {
|
||||
const entry = JSON.parse(line);
|
||||
if (!entry || typeof entry !== 'object') throw new Error('entry is not object');
|
||||
if (Number.isInteger(entry.seq)) nextSeq = Math.max(nextSeq, entry.seq + 1);
|
||||
snapshot = applyEvent(snapshot, entry);
|
||||
} catch (err) {
|
||||
diagnostics.push({
|
||||
error: 'journal_parse_failed',
|
||||
line: i + 1,
|
||||
message: err.message,
|
||||
});
|
||||
}
|
||||
}
|
||||
snapshot.diagnostics = [...snapshot.diagnostics, ...diagnostics];
|
||||
return { snapshot, diagnostics, nextSeq };
|
||||
}
|
||||
|
||||
function applyEvent(snapshot, entry, inheritedDiagnostics = []) {
|
||||
const event = entry.event || entry;
|
||||
const next = {
|
||||
...snapshot,
|
||||
paramValues: { ...(snapshot.paramValues || {}) },
|
||||
sourceMarkers: { ...(snapshot.sourceMarkers || {}) },
|
||||
annotationArtifacts: [...(snapshot.annotationArtifacts || [])],
|
||||
diagnostics: [...(snapshot.diagnostics || [])],
|
||||
updatedAt: entry.ts || new Date().toISOString(),
|
||||
};
|
||||
|
||||
if (inheritedDiagnostics.length && next.diagnostics.length === 0) {
|
||||
next.diagnostics = [...inheritedDiagnostics];
|
||||
}
|
||||
|
||||
switch (event.type) {
|
||||
case 'generate':
|
||||
next.phase = 'generate_requested';
|
||||
next.pageUrl = event.pageUrl ?? next.pageUrl;
|
||||
next.expectedVariants = event.count ?? next.expectedVariants;
|
||||
next.pendingEventSeq = entry.seq ?? next.pendingEventSeq;
|
||||
next.pendingEvent = toPendingEvent(event);
|
||||
if (event.screenshotPath) upsertArtifact(next.annotationArtifacts, { type: 'screenshot', path: event.screenshotPath });
|
||||
break;
|
||||
case 'variants_ready':
|
||||
case 'agent_done':
|
||||
next.phase = event.carbonize === true ? 'carbonize_required' : 'variants_ready';
|
||||
next.sourceFile = event.sourceFile ?? event.file ?? next.sourceFile;
|
||||
next.previewFile = event.previewFile ?? next.previewFile;
|
||||
next.previewMode = event.previewMode ?? next.previewMode;
|
||||
next.arrivedVariants = event.arrivedVariants ?? (next.expectedVariants || next.arrivedVariants || 0);
|
||||
next.pendingEventSeq = null;
|
||||
next.pendingEvent = null;
|
||||
if (event.carbonize === true) {
|
||||
next.diagnostics.push({
|
||||
error: 'carbonize_cleanup_required',
|
||||
file: event.file || null,
|
||||
message: 'Accepted variant still has carbonize markers that must be folded into source CSS.',
|
||||
});
|
||||
}
|
||||
break;
|
||||
case 'checkpoint':
|
||||
if (COMPLETED_PHASES.has(next.phase)) {
|
||||
next.diagnostics.push({ error: 'checkpoint_after_terminal_ignored', phase: event.phase ?? null, revision: event.revision ?? null });
|
||||
break;
|
||||
}
|
||||
if ((event.revision ?? 0) >= (next.checkpointRevision ?? 0)) {
|
||||
next.phase = event.phase ?? next.phase;
|
||||
next.checkpointRevision = event.revision ?? next.checkpointRevision;
|
||||
next.activeOwner = event.owner ?? next.activeOwner;
|
||||
next.arrivedVariants = event.arrivedVariants ?? next.arrivedVariants;
|
||||
next.visibleVariant = event.visibleVariant ?? next.visibleVariant;
|
||||
next.sourceFile = event.sourceFile ?? next.sourceFile;
|
||||
next.previewFile = event.previewFile ?? next.previewFile;
|
||||
next.previewMode = event.previewMode ?? next.previewMode;
|
||||
if (event.paramValues) next.paramValues = { ...event.paramValues };
|
||||
} else {
|
||||
next.diagnostics.push({ error: 'stale_checkpoint_ignored', revision: event.revision });
|
||||
}
|
||||
break;
|
||||
case 'accept':
|
||||
case 'accept_intent':
|
||||
next.phase = 'accept_requested';
|
||||
next.visibleVariant = Number(event.variantId ?? next.visibleVariant);
|
||||
if (event.paramValues) next.paramValues = { ...event.paramValues };
|
||||
next.pendingEventSeq = entry.seq ?? next.pendingEventSeq;
|
||||
next.pendingEvent = toPendingEvent(event);
|
||||
break;
|
||||
case 'manual_edit_apply':
|
||||
next.phase = 'manual_edit_apply_requested';
|
||||
next.pageUrl = event.pageUrl ?? next.pageUrl;
|
||||
next.pendingEventSeq = entry.seq ?? next.pendingEventSeq;
|
||||
next.pendingEvent = toPendingEvent(event);
|
||||
break;
|
||||
case 'steer':
|
||||
next.phase = 'steer_requested';
|
||||
next.pageUrl = event.pageUrl ?? next.pageUrl;
|
||||
next.pendingEventSeq = entry.seq ?? next.pendingEventSeq;
|
||||
next.pendingEvent = toPendingEvent(event);
|
||||
break;
|
||||
case 'steer_done':
|
||||
next.phase = 'steer_done';
|
||||
next.sourceFile = event.sourceFile ?? event.file ?? next.sourceFile;
|
||||
next.previewFile = event.previewFile ?? next.previewFile;
|
||||
next.previewMode = event.previewMode ?? next.previewMode;
|
||||
next.message = event.message ?? next.message;
|
||||
next.pendingEventSeq = null;
|
||||
next.pendingEvent = null;
|
||||
break;
|
||||
case 'discard':
|
||||
next.phase = 'discard_requested';
|
||||
next.pendingEventSeq = entry.seq ?? next.pendingEventSeq;
|
||||
next.pendingEvent = toPendingEvent(event);
|
||||
break;
|
||||
case 'discarded':
|
||||
next.phase = 'discarded';
|
||||
next.pendingEventSeq = null;
|
||||
next.pendingEvent = null;
|
||||
break;
|
||||
case 'complete':
|
||||
next.phase = 'completed';
|
||||
next.sourceFile = event.sourceFile ?? event.file ?? next.sourceFile;
|
||||
next.previewFile = event.previewFile ?? next.previewFile;
|
||||
next.previewMode = event.previewMode ?? next.previewMode;
|
||||
next.pendingEventSeq = null;
|
||||
next.pendingEvent = null;
|
||||
break;
|
||||
case 'agent_error':
|
||||
next.phase = 'agent_error';
|
||||
next.pendingEventSeq = null;
|
||||
next.pendingEvent = null;
|
||||
next.diagnostics.push({ error: 'agent_error', message: event.message || 'unknown agent error' });
|
||||
break;
|
||||
default:
|
||||
next.diagnostics.push({ error: 'unknown_event_type', type: event.type });
|
||||
break;
|
||||
}
|
||||
return next;
|
||||
}
|
||||
|
||||
function toPendingEvent(event) {
|
||||
const pending = { ...event };
|
||||
delete pending.token;
|
||||
return pending;
|
||||
}
|
||||
|
||||
function upsertArtifact(artifacts, artifact) {
|
||||
if (!artifacts.some((existing) => existing.path === artifact.path && existing.type === artifact.type)) {
|
||||
artifacts.push(artifact);
|
||||
}
|
||||
}
|
||||
|
||||
function writeSnapshot(snapshotPath, snapshot) {
|
||||
fs.writeFileSync(snapshotPath, JSON.stringify(snapshot, null, 2) + '\n');
|
||||
}
|
||||
@@ -0,0 +1,826 @@
|
||||
/**
|
||||
* Svelte live-mode component injection helpers.
|
||||
*
|
||||
* Variants are real .svelte components under node_modules/.impeccable-live/<session-id>/.
|
||||
* The browser mounts them via Svelte 5 mount(); accept inlines the chosen
|
||||
* variant back into the route source with props mapped to original bindings.
|
||||
*/
|
||||
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import os from 'node:os';
|
||||
import { createHash } from 'node:crypto';
|
||||
|
||||
export const SVELTE_COMPONENT_ROOT = 'node_modules/.impeccable-live';
|
||||
export const SVELTE_RUNTIME_FILE = `${SVELTE_COMPONENT_ROOT}/__runtime.js`;
|
||||
export const DEFERRED_ACCEPTS_FILE = '.impeccable/live/deferred-svelte-component-accepts.json';
|
||||
|
||||
const MUSTACHE_RE = /\{([^{}]+)\}/g;
|
||||
|
||||
export function shouldUseSvelteComponentInjection(filePath) {
|
||||
if (/^(0|false|no)$/i.test(process.env.IMPECCABLE_LIVE_SVELTE_COMPONENT || '')) return false;
|
||||
return path.extname(filePath).toLowerCase() === '.svelte';
|
||||
}
|
||||
|
||||
export function componentSessionDir(id, cwd = process.cwd()) {
|
||||
return path.join(cwd, SVELTE_COMPONENT_ROOT, id);
|
||||
}
|
||||
|
||||
export function manifestPathForSession(id, cwd = process.cwd()) {
|
||||
return path.join(componentSessionDir(id, cwd), 'manifest.json');
|
||||
}
|
||||
|
||||
export function ensureRuntimeHelper(cwd = process.cwd()) {
|
||||
const file = path.join(cwd, SVELTE_RUNTIME_FILE);
|
||||
if (fs.existsSync(file)) return file;
|
||||
fs.mkdirSync(path.dirname(file), { recursive: true });
|
||||
fs.writeFileSync(file, `export { mount, unmount } from 'svelte';\n`, 'utf-8');
|
||||
return file;
|
||||
}
|
||||
|
||||
/**
|
||||
* Extract ordered unique mustache expressions from markup (not inside <!-- -->).
|
||||
*/
|
||||
export function extractMustacheExpressions(text) {
|
||||
const expressions = [];
|
||||
const seen = new Set();
|
||||
const lines = String(text || '').split('\n');
|
||||
for (const line of lines) {
|
||||
const trimmed = line.trim();
|
||||
if (trimmed.startsWith('<!--')) continue;
|
||||
let match;
|
||||
MUSTACHE_RE.lastIndex = 0;
|
||||
while ((match = MUSTACHE_RE.exec(line)) !== null) {
|
||||
const expr = match[1].trim();
|
||||
if (!expr || seen.has(expr)) continue;
|
||||
seen.add(expr);
|
||||
expressions.push(expr);
|
||||
}
|
||||
}
|
||||
return expressions;
|
||||
}
|
||||
|
||||
export function buildPropContract(expressions) {
|
||||
return expressions.map((expr, index) => {
|
||||
const derived = derivePropName(expr, index);
|
||||
return {
|
||||
prop: derived,
|
||||
expr,
|
||||
placeholder: `{${expr}}`,
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
function derivePropName(expr, index) {
|
||||
const tail = expr.match(/(?:\.|\[)(\w+)\s*\]?$/);
|
||||
if (tail && tail[1] && /^[A-Za-z_$][\w$]*$/.test(tail[1])) {
|
||||
return tail[1];
|
||||
}
|
||||
return `prop${index}`;
|
||||
}
|
||||
|
||||
export function substituteExprsWithProps(markup, contract) {
|
||||
let out = String(markup || '');
|
||||
for (const entry of contract) {
|
||||
out = out.split(entry.placeholder).join(`{${entry.prop}}`);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
export function substitutePropsWithExprs(markup, contract) {
|
||||
let out = String(markup || '');
|
||||
for (const entry of contract) {
|
||||
out = out.split(`{${entry.prop}}`).join(`{${entry.expr}}`);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
export function parseSvelteComponentFile(content) {
|
||||
const text = String(content || '');
|
||||
const scriptMatch = text.match(/^([\s\S]*?)<script\b[^>]*>[\s\S]*?<\/script>/i);
|
||||
const withoutScript = scriptMatch ? text.slice(scriptMatch[0].length) : text;
|
||||
const styleMatch = withoutScript.match(/<style\b[^>]*>[\s\S]*?<\/style\s*>/i);
|
||||
const styleBlock = styleMatch ? styleMatch[0] : '';
|
||||
const markup = styleMatch
|
||||
? withoutScript.slice(0, styleMatch.index).trim()
|
||||
: withoutScript.trim();
|
||||
const cssLines = styleBlock
|
||||
? styleBlock
|
||||
.replace(/^<style\b[^>]*>/i, '')
|
||||
.replace(/<\/style\s*>$/i, '')
|
||||
.split('\n')
|
||||
.map((line) => line.trimEnd())
|
||||
: [];
|
||||
while (cssLines.length > 0 && cssLines[0].trim() === '') cssLines.shift();
|
||||
while (cssLines.length > 0 && cssLines[cssLines.length - 1].trim() === '') cssLines.pop();
|
||||
return { markup, cssLines, styleBlock };
|
||||
}
|
||||
|
||||
function buildPropsScript(contract) {
|
||||
if (contract.length === 0) {
|
||||
return '<script>\n /** @type {Record<string, never>} */\n let {} = $props();\n</script>\n';
|
||||
}
|
||||
const names = contract.map((c) => c.prop).join(', ');
|
||||
const typeFields = contract.map((c) => ` ${c.prop}: string;`).join('\n');
|
||||
return `<script>\n /** @type {{\n${typeFields}\n }} */\n let { ${names} } = $props();\n</script>\n`;
|
||||
}
|
||||
|
||||
function buildVariantStub(variantNum, originalWithProps, contract) {
|
||||
const propsComment = contract.length > 0
|
||||
? `\n<!-- Props: ${contract.map((c) => `${c.prop} <- {${c.expr}}`).join(', ')} -->\n`
|
||||
: '';
|
||||
return `${buildPropsScript(contract)}${propsComment}${originalWithProps.trim()}\n\n<style>\n /* Variant ${variantNum}: add scoped CSS here */\n</style>\n`;
|
||||
}
|
||||
|
||||
function buildInsertVariantStub(variantNum) {
|
||||
return `${buildPropsScript([])}<div class="impeccable-insert-preview">Insert variant ${variantNum}</div>\n\n<style>\n .impeccable-insert-preview { display: block; }\n</style>\n`;
|
||||
}
|
||||
|
||||
export function scaffoldSvelteComponentSession({
|
||||
id,
|
||||
count,
|
||||
sourceFile,
|
||||
sourceStartLine,
|
||||
sourceEndLine,
|
||||
originalLines,
|
||||
cwd = process.cwd(),
|
||||
}) {
|
||||
ensureRuntimeHelper(cwd);
|
||||
const dir = componentSessionDir(id, cwd);
|
||||
fs.mkdirSync(dir, { recursive: true });
|
||||
|
||||
const originalMarkup = originalLines.join('\n');
|
||||
const contract = buildPropContract(extractMustacheExpressions(originalMarkup));
|
||||
const originalWithProps = substituteExprsWithProps(originalMarkup, contract);
|
||||
|
||||
const manifest = {
|
||||
id,
|
||||
previewMode: 'svelte-component',
|
||||
sourceFile: sourceFile.split(path.sep).join('/'),
|
||||
sourceStartLine,
|
||||
sourceEndLine,
|
||||
count,
|
||||
propContract: contract,
|
||||
originalMarkup,
|
||||
componentDir: path.relative(cwd, dir).split(path.sep).join('/'),
|
||||
runtimeModule: `/${SVELTE_RUNTIME_FILE}`,
|
||||
};
|
||||
|
||||
fs.writeFileSync(path.join(dir, 'manifest.json'), JSON.stringify(manifest, null, 2) + '\n', 'utf-8');
|
||||
|
||||
for (let n = 1; n <= count; n++) {
|
||||
const variantFile = path.join(dir, `v${n}.svelte`);
|
||||
if (!fs.existsSync(variantFile)) {
|
||||
fs.writeFileSync(variantFile, buildVariantStub(n, originalWithProps, contract), 'utf-8');
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
manifest,
|
||||
manifestFile: path.relative(cwd, path.join(dir, 'manifest.json')).split(path.sep).join('/'),
|
||||
componentDir: manifest.componentDir,
|
||||
propContract: contract,
|
||||
};
|
||||
}
|
||||
|
||||
export function scaffoldSvelteComponentInsertSession({
|
||||
id,
|
||||
count,
|
||||
sourceFile,
|
||||
insertLine,
|
||||
position,
|
||||
anchorStartLine,
|
||||
anchorEndLine,
|
||||
anchorLines,
|
||||
cwd = process.cwd(),
|
||||
}) {
|
||||
ensureRuntimeHelper(cwd);
|
||||
const dir = componentSessionDir(id, cwd);
|
||||
fs.mkdirSync(dir, { recursive: true });
|
||||
|
||||
const anchorMarkup = (anchorLines || []).join('\n');
|
||||
const manifest = {
|
||||
id,
|
||||
mode: 'insert',
|
||||
previewMode: 'svelte-component',
|
||||
sourceFile: sourceFile.split(path.sep).join('/'),
|
||||
insertLine,
|
||||
position,
|
||||
anchorStartLine,
|
||||
anchorEndLine,
|
||||
originalMarkup: anchorMarkup,
|
||||
anchorMarkup,
|
||||
count,
|
||||
propContract: [],
|
||||
componentDir: path.relative(cwd, dir).split(path.sep).join('/'),
|
||||
runtimeModule: `/${SVELTE_RUNTIME_FILE}`,
|
||||
};
|
||||
|
||||
fs.writeFileSync(path.join(dir, 'manifest.json'), JSON.stringify(manifest, null, 2) + '\n', 'utf-8');
|
||||
|
||||
for (let n = 1; n <= count; n++) {
|
||||
const variantFile = path.join(dir, `v${n}.svelte`);
|
||||
if (!fs.existsSync(variantFile)) {
|
||||
fs.writeFileSync(variantFile, buildInsertVariantStub(n), 'utf-8');
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
manifest,
|
||||
manifestFile: path.relative(cwd, path.join(dir, 'manifest.json')).split(path.sep).join('/'),
|
||||
componentDir: manifest.componentDir,
|
||||
propContract: [],
|
||||
};
|
||||
}
|
||||
|
||||
export function findSvelteComponentManifest(id, cwd = process.cwd()) {
|
||||
const direct = manifestPathForSession(id, cwd);
|
||||
if (fs.existsSync(direct)) {
|
||||
return readManifest(direct);
|
||||
}
|
||||
const root = path.join(cwd, SVELTE_COMPONENT_ROOT);
|
||||
if (!fs.existsSync(root)) return null;
|
||||
for (const entry of fs.readdirSync(root, { withFileTypes: true })) {
|
||||
if (!entry.isDirectory()) continue;
|
||||
const candidate = path.join(root, entry.name, 'manifest.json');
|
||||
if (!fs.existsSync(candidate)) continue;
|
||||
try {
|
||||
const manifest = readManifest(candidate);
|
||||
if (manifest?.id === id) return { ...manifest, manifestPath: candidate };
|
||||
} catch { /* skip */ }
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
export function readManifest(manifestPath) {
|
||||
const data = JSON.parse(fs.readFileSync(manifestPath, 'utf-8'));
|
||||
return {
|
||||
...data,
|
||||
manifestPath,
|
||||
};
|
||||
}
|
||||
|
||||
export function resolveSourceFile(sourceFile, cwd = process.cwd()) {
|
||||
if (!sourceFile || path.isAbsolute(sourceFile)) {
|
||||
throw new Error('Invalid svelte-component source file');
|
||||
}
|
||||
const full = path.resolve(cwd, sourceFile);
|
||||
const rel = path.relative(cwd, full);
|
||||
if (!rel || rel.startsWith('..') || path.isAbsolute(rel)) {
|
||||
throw new Error('Svelte-component source file escapes project root');
|
||||
}
|
||||
if (!fs.existsSync(full)) {
|
||||
throw new Error('Svelte-component source file not found: ' + sourceFile);
|
||||
}
|
||||
return full;
|
||||
}
|
||||
|
||||
function appendCssToSvelteStyle(lines, cssLines) {
|
||||
const closeIdx = findLastStyleCloseLine(lines);
|
||||
const prepared = ['', ...cssLines.map((line) => (line.trim() === '' ? '' : ' ' + line.trimStart()))];
|
||||
if (closeIdx === -1) {
|
||||
return [...lines, '', '<style>', ...prepared.slice(1), '</style>'];
|
||||
}
|
||||
return [
|
||||
...lines.slice(0, closeIdx),
|
||||
...prepared,
|
||||
...lines.slice(closeIdx),
|
||||
];
|
||||
}
|
||||
|
||||
function findLastStyleCloseLine(lines) {
|
||||
for (let i = lines.length - 1; i >= 0; i--) {
|
||||
if (/<\/style\s*>/.test(lines[i])) return i;
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
|
||||
function bakeParamValuesInCss(cssLines, paramValues) {
|
||||
if (!paramValues || Object.keys(paramValues).length === 0) return cssLines;
|
||||
return cssLines.map((line) => {
|
||||
let out = line;
|
||||
for (const [key, value] of Object.entries(paramValues)) {
|
||||
const varName = `--p-${key}`;
|
||||
out = out.replace(new RegExp(`var\\(${escapeRegExp(varName)}(?:,\\s*[^)]+)?\\)`, 'g'), String(value));
|
||||
}
|
||||
return out;
|
||||
});
|
||||
}
|
||||
|
||||
function sanitizeAcceptedSvelteCss(cssLines, variantNum, paramValues = null, rootTag = 'div') {
|
||||
const css = String((cssLines || []).join('\n'));
|
||||
if (!/data-impeccable-variant|impeccable-variant-ready/.test(css)) return cssLines;
|
||||
|
||||
const rules = parseCssRules(css);
|
||||
const output = [];
|
||||
for (const rule of rules) {
|
||||
appendSanitizedCssRule(output, rule, variantNum, paramValues, rootTag);
|
||||
}
|
||||
return output.join('\n')
|
||||
.split('\n')
|
||||
.map((line) => line.trimEnd())
|
||||
.filter((line) => line.trim() !== '');
|
||||
}
|
||||
|
||||
function appendSanitizedCssRule(output, rule, variantNum, paramValues, rootTag) {
|
||||
const prelude = rule.prelude.trim();
|
||||
const body = rule.body.trim();
|
||||
if (!prelude || !body || /--impeccable-variant-ready\s*:/.test(body)) return;
|
||||
|
||||
if (/^@scope\b/i.test(prelude)) {
|
||||
if (/data-impeccable-variant/.test(prelude) && !selectorHasVariant(prelude, variantNum)) return;
|
||||
const inner = parseCssRules(body);
|
||||
for (const innerRule of inner) {
|
||||
const rewrittenPrelude = rewriteAcceptedSvelteSelector(innerRule.prelude, variantNum, paramValues, rootTag, true);
|
||||
if (!rewrittenPrelude || /--impeccable-variant-ready\s*:/.test(innerRule.body)) continue;
|
||||
output.push(formatCssRule(rewrittenPrelude, innerRule.body.trim()));
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
const rewrittenPrelude = rewriteAcceptedSvelteSelector(prelude, variantNum, paramValues, rootTag, false);
|
||||
if (!rewrittenPrelude) return;
|
||||
output.push(formatCssRule(rewrittenPrelude, body));
|
||||
}
|
||||
|
||||
function parseCssRules(css) {
|
||||
const rules = [];
|
||||
const text = String(css || '');
|
||||
let i = 0;
|
||||
while (i < text.length) {
|
||||
while (i < text.length && /\s/.test(text[i])) i++;
|
||||
const preludeStart = i;
|
||||
while (i < text.length && text[i] !== '{') i++;
|
||||
if (i >= text.length) break;
|
||||
const prelude = text.slice(preludeStart, i).trim();
|
||||
i++;
|
||||
const bodyStart = i;
|
||||
let depth = 1;
|
||||
let quote = null;
|
||||
let comment = false;
|
||||
while (i < text.length && depth > 0) {
|
||||
const ch = text[i];
|
||||
const next = text[i + 1];
|
||||
if (comment) {
|
||||
if (ch === '*' && next === '/') {
|
||||
comment = false;
|
||||
i += 2;
|
||||
continue;
|
||||
}
|
||||
i++;
|
||||
continue;
|
||||
}
|
||||
if (quote) {
|
||||
if (ch === '\\') {
|
||||
i += 2;
|
||||
continue;
|
||||
}
|
||||
if (ch === quote) quote = null;
|
||||
i++;
|
||||
continue;
|
||||
}
|
||||
if (ch === '/' && next === '*') {
|
||||
comment = true;
|
||||
i += 2;
|
||||
continue;
|
||||
}
|
||||
if (ch === '"' || ch === "'") {
|
||||
quote = ch;
|
||||
i++;
|
||||
continue;
|
||||
}
|
||||
if (ch === '{') depth++;
|
||||
else if (ch === '}') depth--;
|
||||
i++;
|
||||
}
|
||||
const body = text.slice(bodyStart, Math.max(bodyStart, i - 1));
|
||||
if (prelude) rules.push({ prelude, body });
|
||||
}
|
||||
return rules;
|
||||
}
|
||||
|
||||
function rewriteAcceptedSvelteSelector(prelude, variantNum, paramValues, rootTag, fromScope) {
|
||||
const selectors = splitSelectorList(prelude);
|
||||
const rewritten = [];
|
||||
for (const selector of selectors) {
|
||||
const next = rewriteAcceptedSvelteSelectorPart(selector, variantNum, paramValues, rootTag, fromScope);
|
||||
if (next) rewritten.push(next);
|
||||
}
|
||||
return rewritten.join(', ');
|
||||
}
|
||||
|
||||
function rewriteAcceptedSvelteSelectorPart(selector, variantNum, paramValues, rootTag, fromScope) {
|
||||
let out = selector.trim();
|
||||
const hasVariant = /data-impeccable-variant/.test(out);
|
||||
if (hasVariant && !selectorHasVariant(out, variantNum)) return '';
|
||||
if (hasVariant) {
|
||||
out = out.replace(variantSelectorRegex(variantNum), '');
|
||||
out = out.replace(/\[data-impeccable-variant=(["']).*?\1\]/g, '');
|
||||
}
|
||||
|
||||
const paramResult = rewriteParamSelectors(out, paramValues);
|
||||
if (!paramResult.keep) return '';
|
||||
out = paramResult.selector;
|
||||
|
||||
out = out
|
||||
.replace(/:scope(?:\[[^\]]+\])?\s*>\s*/g, '')
|
||||
.replace(/:scope(?:\[[^\]]+\])?/g, rootTag || '')
|
||||
.replace(/\s+/g, ' ')
|
||||
.trim();
|
||||
|
||||
out = out.replace(/^[>+~]\s*/, '').trim();
|
||||
if (!out && (hasVariant || fromScope)) return rootTag || ':global(*)';
|
||||
return out;
|
||||
}
|
||||
|
||||
function rewriteParamSelectors(selector, paramValues) {
|
||||
let keep = true;
|
||||
const next = selector.replace(/\[data-p-([A-Za-z0-9_-]+)(?:=(["'])(.*?)\2)?\]/g, (_match, key, _quote, expected) => {
|
||||
if (!paramValues || !Object.prototype.hasOwnProperty.call(paramValues, key)) return '';
|
||||
const actual = paramValues[key];
|
||||
if (expected != null && String(actual) !== String(expected)) {
|
||||
keep = false;
|
||||
return '';
|
||||
}
|
||||
if (expected == null && (actual === false || actual == null || actual === 'false' || actual === 'off' || actual === '0')) {
|
||||
keep = false;
|
||||
return '';
|
||||
}
|
||||
return '';
|
||||
});
|
||||
return { keep, selector: next };
|
||||
}
|
||||
|
||||
function splitSelectorList(prelude) {
|
||||
const selectors = [];
|
||||
let start = 0;
|
||||
let bracket = 0;
|
||||
let paren = 0;
|
||||
let quote = null;
|
||||
for (let i = 0; i < prelude.length; i++) {
|
||||
const ch = prelude[i];
|
||||
if (quote) {
|
||||
if (ch === '\\') i++;
|
||||
else if (ch === quote) quote = null;
|
||||
continue;
|
||||
}
|
||||
if (ch === '"' || ch === "'") {
|
||||
quote = ch;
|
||||
continue;
|
||||
}
|
||||
if (ch === '[') bracket++;
|
||||
else if (ch === ']') bracket = Math.max(0, bracket - 1);
|
||||
else if (ch === '(') paren++;
|
||||
else if (ch === ')') paren = Math.max(0, paren - 1);
|
||||
else if (ch === ',' && bracket === 0 && paren === 0) {
|
||||
selectors.push(prelude.slice(start, i));
|
||||
start = i + 1;
|
||||
}
|
||||
}
|
||||
selectors.push(prelude.slice(start));
|
||||
return selectors;
|
||||
}
|
||||
|
||||
function selectorHasVariant(selector, variantNum) {
|
||||
return variantSelectorRegex(variantNum).test(selector);
|
||||
}
|
||||
|
||||
function variantSelectorRegex(variantNum) {
|
||||
return new RegExp(`\\[data-impeccable-variant=(["'])${escapeRegExp(String(variantNum))}\\1\\]`, 'g');
|
||||
}
|
||||
|
||||
function formatCssRule(selector, body) {
|
||||
return `${selector} { ${body.trim()} }`;
|
||||
}
|
||||
|
||||
function escapeRegExp(value) {
|
||||
return String(value).replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
|
||||
}
|
||||
|
||||
export function inlineSvelteComponentAccept(manifest, variantNum, paramValues = null, cwd = process.cwd()) {
|
||||
const sourceFile = resolveSourceFile(manifest.sourceFile, cwd);
|
||||
const variantPath = path.join(cwd, manifest.componentDir, `v${variantNum}.svelte`);
|
||||
const resultBase = {
|
||||
file: manifest.sourceFile,
|
||||
sourceFile: manifest.sourceFile,
|
||||
previewMode: 'svelte-component',
|
||||
componentDir: manifest.componentDir,
|
||||
carbonize: false,
|
||||
};
|
||||
if (!fs.existsSync(variantPath)) {
|
||||
return { handled: false, error: `Variant ${variantNum} not found`, ...resultBase };
|
||||
}
|
||||
|
||||
const { markup, cssLines } = parseSvelteComponentFile(fs.readFileSync(variantPath, 'utf-8'));
|
||||
if (manifest.mode === 'insert') {
|
||||
return inlineSvelteComponentInsertAccept({
|
||||
manifest,
|
||||
markup,
|
||||
cssLines,
|
||||
variantNum,
|
||||
paramValues,
|
||||
sourceFile,
|
||||
resultBase,
|
||||
cwd,
|
||||
});
|
||||
}
|
||||
|
||||
const rootTag = matchOpeningTag(markup)?.tag || 'div';
|
||||
const contract = manifest.propContract || [];
|
||||
const mergedMarkup = mergeOriginalTopLevelAttrs(markup, manifest.originalMarkup || '');
|
||||
const restoredMarkup = substitutePropsWithExprs(mergedMarkup, contract)
|
||||
.split('\n')
|
||||
.map((line) => line.trimEnd());
|
||||
|
||||
const sourceContent = fs.readFileSync(sourceFile, 'utf-8');
|
||||
const sourceLines = sourceContent.split('\n');
|
||||
const start = Number(manifest.sourceStartLine) - 1;
|
||||
const end = Number(manifest.sourceEndLine) - 1;
|
||||
if (!Number.isInteger(start) || !Number.isInteger(end) || start < 0 || end < start || end >= sourceLines.length) {
|
||||
return { handled: false, error: 'Invalid source line range for ' + manifest.sourceFile, ...resultBase };
|
||||
}
|
||||
|
||||
const indent = sourceLines[start].match(/^(\s*)/)?.[1] || '';
|
||||
const indentedMarkup = restoredMarkup.map((line) => {
|
||||
if (line.trim() === '') return '';
|
||||
return indent + line.trimStart();
|
||||
});
|
||||
|
||||
let newLines = [
|
||||
...sourceLines.slice(0, start),
|
||||
...indentedMarkup,
|
||||
...sourceLines.slice(end + 1),
|
||||
];
|
||||
|
||||
const sanitizedCss = sanitizeAcceptedSvelteCss(cssLines, variantNum, paramValues, rootTag);
|
||||
const bakedCss = bakeParamValuesInCss(sanitizedCss, paramValues);
|
||||
if (bakedCss.length > 0) {
|
||||
newLines = appendCssToSvelteStyle(newLines, bakedCss);
|
||||
}
|
||||
|
||||
try {
|
||||
fs.writeFileSync(sourceFile, newLines.join('\n'), 'utf-8');
|
||||
} catch (err) {
|
||||
return { handled: false, error: 'Failed to write Svelte source: ' + err.message, ...resultBase };
|
||||
}
|
||||
removeSvelteComponentSession(manifest.id, cwd);
|
||||
|
||||
return {
|
||||
handled: true,
|
||||
...resultBase,
|
||||
};
|
||||
}
|
||||
|
||||
function inlineSvelteComponentInsertAccept({
|
||||
manifest,
|
||||
markup,
|
||||
cssLines,
|
||||
variantNum,
|
||||
paramValues,
|
||||
sourceFile,
|
||||
resultBase,
|
||||
cwd,
|
||||
}) {
|
||||
if (!svelteMarkupHasVisibleContent(markup)) {
|
||||
return { handled: false, error: 'Accepted Svelte insert variant is empty', ...resultBase };
|
||||
}
|
||||
if (/\bdata-impeccable-[\w-]*\s*=/.test(markup)) {
|
||||
return { handled: false, error: 'Accepted Svelte insert variant contains preview-only data-impeccable attributes', ...resultBase };
|
||||
}
|
||||
|
||||
const rootTag = matchOpeningTag(markup)?.tag || 'div';
|
||||
const restoredMarkup = String(markup || '')
|
||||
.split('\n')
|
||||
.map((line) => line.trimEnd());
|
||||
const sourceContent = fs.readFileSync(sourceFile, 'utf-8');
|
||||
const sourceLines = sourceContent.split('\n');
|
||||
const insertIndex = Number(manifest.insertLine) - 1;
|
||||
if (!Number.isInteger(insertIndex) || insertIndex < 0 || insertIndex > sourceLines.length) {
|
||||
return { handled: false, error: 'Invalid insert line for ' + manifest.sourceFile, ...resultBase };
|
||||
}
|
||||
|
||||
const nearbyLine = sourceLines[insertIndex] ?? sourceLines[insertIndex - 1] ?? '';
|
||||
const indent = nearbyLine.match(/^(\s*)/)?.[1] || '';
|
||||
const indentedMarkup = restoredMarkup.map((line) => {
|
||||
if (line.trim() === '') return '';
|
||||
return indent + line.trimStart();
|
||||
});
|
||||
|
||||
let newLines = [
|
||||
...sourceLines.slice(0, insertIndex),
|
||||
...indentedMarkup,
|
||||
...sourceLines.slice(insertIndex),
|
||||
];
|
||||
|
||||
const sanitizedCss = sanitizeAcceptedSvelteCss(cssLines, variantNum, paramValues, rootTag);
|
||||
const bakedCss = bakeParamValuesInCss(sanitizedCss, paramValues);
|
||||
if (bakedCss.length > 0) {
|
||||
newLines = appendCssToSvelteStyle(newLines, bakedCss);
|
||||
}
|
||||
|
||||
try {
|
||||
fs.writeFileSync(sourceFile, newLines.join('\n'), 'utf-8');
|
||||
} catch (err) {
|
||||
return { handled: false, error: 'Failed to write Svelte source: ' + err.message, ...resultBase };
|
||||
}
|
||||
removeSvelteComponentSession(manifest.id, cwd);
|
||||
|
||||
return {
|
||||
handled: true,
|
||||
...resultBase,
|
||||
};
|
||||
}
|
||||
|
||||
function svelteMarkupHasVisibleContent(markup) {
|
||||
const text = String(markup || '')
|
||||
.replace(/<script[\s\S]*?<\/script>/gi, '')
|
||||
.replace(/<style[\s\S]*?<\/style>/gi, '')
|
||||
.replace(/<!--[\s\S]*?-->/g, '')
|
||||
.replace(/<[^>]+>/g, ' ')
|
||||
.replace(/\s+/g, ' ')
|
||||
.trim();
|
||||
if (text.length > 0) return true;
|
||||
return /<(img|svg|canvas|video|audio|picture|input|button|select|textarea)\b/i.test(markup || '');
|
||||
}
|
||||
|
||||
function mergeOriginalTopLevelAttrs(markup, originalMarkup) {
|
||||
const variantOpen = matchOpeningTag(markup);
|
||||
const originalOpen = matchOpeningTag(originalMarkup);
|
||||
if (!variantOpen || !originalOpen) return markup;
|
||||
if (variantOpen.tag.toLowerCase() !== originalOpen.tag.toLowerCase()) return markup;
|
||||
|
||||
const variantAttrs = parseAttrSegments(variantOpen.attrs);
|
||||
const originalAttrs = parseAttrSegments(originalOpen.attrs);
|
||||
const additions = [];
|
||||
let attrs = variantOpen.attrs;
|
||||
|
||||
const originalClass = originalAttrs.get('class');
|
||||
const variantClass = variantAttrs.get('class');
|
||||
if (originalClass && variantClass) {
|
||||
const merged = mergeStaticClassAttr(originalClass, variantClass);
|
||||
if (merged) {
|
||||
attrs = attrs.slice(0, variantClass.start) + merged + attrs.slice(variantClass.end);
|
||||
variantAttrs.set('class', { ...variantClass, raw: merged });
|
||||
}
|
||||
} else if (originalClass && !variantClass) {
|
||||
additions.push(originalClass.raw);
|
||||
}
|
||||
|
||||
for (const [name, attr] of originalAttrs) {
|
||||
if (name === 'class') continue;
|
||||
if (!variantAttrs.has(name)) additions.push(attr.raw);
|
||||
}
|
||||
|
||||
if (additions.length === 0 && attrs === variantOpen.attrs) return markup;
|
||||
const nextOpen = variantOpen.prefix
|
||||
+ variantOpen.tag
|
||||
+ attrs
|
||||
+ additions.map((attr) => ' ' + attr.trim()).join('')
|
||||
+ variantOpen.close;
|
||||
return markup.slice(0, variantOpen.index) + nextOpen + markup.slice(variantOpen.index + variantOpen.raw.length);
|
||||
}
|
||||
|
||||
function matchOpeningTag(markup) {
|
||||
const match = String(markup || '').match(/^(\s*<)([A-Za-z][\w:-]*)([^>]*?)(\/?>)/);
|
||||
if (!match) return null;
|
||||
return {
|
||||
raw: match[0],
|
||||
prefix: match[1],
|
||||
tag: match[2],
|
||||
attrs: match[3] || '',
|
||||
close: match[4],
|
||||
index: match.index || 0,
|
||||
};
|
||||
}
|
||||
|
||||
function parseAttrSegments(attrs) {
|
||||
const out = new Map();
|
||||
const re = /([A-Za-z_:][\w:.-]*)(?:\s*=\s*(?:"[^"]*"|'[^']*'|\{[^}]*\}|[^\s"'>=]+))?/g;
|
||||
let match;
|
||||
while ((match = re.exec(attrs))) {
|
||||
const raw = match[0];
|
||||
const name = match[1];
|
||||
out.set(name, {
|
||||
name,
|
||||
raw,
|
||||
start: match.index,
|
||||
end: match.index + raw.length,
|
||||
});
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
function mergeStaticClassAttr(originalClass, variantClass) {
|
||||
const originalValue = originalClass.raw.match(/class\s*=\s*(["'])(.*?)\1/);
|
||||
const variantValue = variantClass.raw.match(/class\s*=\s*(["'])(.*?)\1/);
|
||||
if (!originalValue || !variantValue) return null;
|
||||
const quote = variantValue[1];
|
||||
const classes = [
|
||||
...variantValue[2].split(/\s+/),
|
||||
...originalValue[2].split(/\s+/),
|
||||
].filter(Boolean);
|
||||
return `class=${quote}${[...new Set(classes)].join(' ')}${quote}`;
|
||||
}
|
||||
|
||||
export function removeSvelteComponentSession(id, cwd = process.cwd()) {
|
||||
const dir = componentSessionDir(id, cwd);
|
||||
try {
|
||||
fs.rmSync(dir, { recursive: true, force: true });
|
||||
} catch { /* non-fatal */ }
|
||||
}
|
||||
|
||||
export function removeAllSvelteComponentSessions(cwd = process.cwd()) {
|
||||
const root = path.join(cwd, SVELTE_COMPONENT_ROOT);
|
||||
if (!fs.existsSync(root)) return;
|
||||
for (const entry of fs.readdirSync(root, { withFileTypes: true })) {
|
||||
if (!entry.isDirectory()) continue;
|
||||
if (entry.name.startsWith('__')) continue;
|
||||
try {
|
||||
fs.rmSync(path.join(root, entry.name), { recursive: true, force: true });
|
||||
} catch { /* non-fatal */ }
|
||||
}
|
||||
}
|
||||
|
||||
export function deferredAcceptsPath(cwd = process.cwd()) {
|
||||
const key = createHash('sha1').update(path.resolve(cwd)).digest('hex').slice(0, 16);
|
||||
return path.join(os.tmpdir(), 'impeccable-live', key, 'deferred-svelte-component-accepts.json');
|
||||
}
|
||||
|
||||
export function readDeferredAccepts(cwd = process.cwd()) {
|
||||
const file = deferredAcceptsPath(cwd);
|
||||
try {
|
||||
return JSON.parse(fs.readFileSync(file, 'utf-8'));
|
||||
} catch {
|
||||
return { accepts: [] };
|
||||
}
|
||||
}
|
||||
|
||||
export function writeDeferredAccept(entry, cwd = process.cwd()) {
|
||||
const file = deferredAcceptsPath(cwd);
|
||||
fs.mkdirSync(path.dirname(file), { recursive: true });
|
||||
const data = readDeferredAccepts(cwd);
|
||||
data.accepts = (data.accepts || []).filter((item) => item.id !== entry.id);
|
||||
data.accepts.push({ ...entry, createdAt: new Date().toISOString() });
|
||||
fs.writeFileSync(file, JSON.stringify(data, null, 2) + '\n', 'utf-8');
|
||||
}
|
||||
|
||||
export function applyDeferredSvelteComponentAccepts(cwd = process.cwd()) {
|
||||
const file = deferredAcceptsPath(cwd);
|
||||
const data = readDeferredAccepts(cwd);
|
||||
const pending = Array.isArray(data.accepts) ? data.accepts : [];
|
||||
const results = [];
|
||||
const remaining = [];
|
||||
for (const entry of pending) {
|
||||
try {
|
||||
const manifest = findSvelteComponentManifest(entry.id, cwd);
|
||||
if (!manifest) {
|
||||
results.push({ id: entry.id, ok: false, error: 'manifest not found' });
|
||||
remaining.push(entry);
|
||||
continue;
|
||||
}
|
||||
const result = inlineSvelteComponentAccept(
|
||||
manifest,
|
||||
entry.variantNum,
|
||||
entry.paramValues || null,
|
||||
cwd,
|
||||
);
|
||||
results.push({ id: entry.id, ok: result.handled !== false, result });
|
||||
if (result.handled === false) remaining.push(entry);
|
||||
} catch (err) {
|
||||
results.push({ id: entry.id, ok: false, error: err.message });
|
||||
remaining.push(entry);
|
||||
}
|
||||
}
|
||||
if (remaining.length > 0) {
|
||||
fs.writeFileSync(file, JSON.stringify({ accepts: remaining }, null, 2) + '\n', 'utf-8');
|
||||
} else {
|
||||
try { fs.rmSync(file, { force: true }); } catch {}
|
||||
}
|
||||
return { applied: results.filter((r) => r.ok).length, failed: results.filter((r) => !r.ok).length, results };
|
||||
}
|
||||
|
||||
export function buildSvelteComponentCssAuthoring(count) {
|
||||
const variantNumbers = Array.from({ length: count }, (_, i) => i + 1);
|
||||
return {
|
||||
mode: 'svelte-component',
|
||||
styleTag: null,
|
||||
strategy: 'component-style-block',
|
||||
rulePattern: '.semantic-class { ... }',
|
||||
selectorExamples: variantNumbers.map(() => '.expense-row { padding: 22px; }'),
|
||||
requirements: [
|
||||
'Write each variant as a real Svelte component file (v1.svelte, v2.svelte, ...).',
|
||||
'Keep the prop names from propContract; bind dynamic text with {propName}, not literal snapshot text.',
|
||||
'Put variant CSS in the component <style> block using semantic class selectors.',
|
||||
'Author param-driven CSS against var(--p-<id>, default) and [data-p-<id>] using :global(...) so the runtime knob values reach the mounted root.',
|
||||
'Declare params in componentDir/params.json keyed by variant number (e.g. {"1": [...], "2": [...]}), NOT as a data-impeccable-params attribute.',
|
||||
'Do not use @scope or data-impeccable-variant selectors in component files.',
|
||||
'Do not edit the route source file during generation; only edit files under componentDir.',
|
||||
],
|
||||
forbidden: [
|
||||
'Do not use @scope blocks in Svelte component variants.',
|
||||
'Do not copy live DOM snapshot text into markup when propContract provides bindings.',
|
||||
'Do not add data-impeccable-* attributes inside component files. Svelte parses { in attribute values as an expression, so data-impeccable-params with JSON breaks the build; use componentDir/params.json instead.',
|
||||
],
|
||||
paramsFile: 'params.json',
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,274 @@
|
||||
/**
|
||||
* SvelteKit live-mode adapter.
|
||||
*
|
||||
* SvelteKit must not be patched through src/app.html. That file is a document
|
||||
* template, not framework-owned component chrome. The adapter keeps SvelteKit
|
||||
* work limited to mounting a dev-only shadow host from +layout.svelte; the
|
||||
* actual live UI remains the shared plain-DOM browser chrome.
|
||||
*/
|
||||
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
|
||||
export const SVELTE_LIVE_ROOT_COMPONENT = 'src/lib/impeccable/ImpeccableLiveRoot.svelte';
|
||||
export const SVELTE_LAYOUT_MARKER_OPEN = '<!-- impeccable-live-svelte-start -->';
|
||||
export const SVELTE_LAYOUT_MARKER_CLOSE = '<!-- impeccable-live-svelte-end -->';
|
||||
export const SVELTE_ROOT_IMPORT = "import ImpeccableLiveRoot from '$lib/impeccable/ImpeccableLiveRoot.svelte';";
|
||||
|
||||
export function detectSvelteKitProject(cwd = process.cwd(), config = null) {
|
||||
const appHtml = findSvelteKitAppHtml(cwd, config);
|
||||
if (!appHtml) return null;
|
||||
const hasTemplateMarkers = fileIncludes(path.join(cwd, appHtml), '%sveltekit.body%')
|
||||
&& fileIncludes(path.join(cwd, appHtml), '%sveltekit.head%');
|
||||
if (!hasTemplateMarkers) return null;
|
||||
|
||||
const hasSvelteConfig = fs.existsSync(path.join(cwd, 'svelte.config.js'))
|
||||
|| fs.existsSync(path.join(cwd, 'svelte.config.mjs'))
|
||||
|| fs.existsSync(path.join(cwd, 'svelte.config.cjs'))
|
||||
|| fs.existsSync(path.join(cwd, 'svelte.config.ts'));
|
||||
const hasKitPackage = packageHasSvelteKit(cwd);
|
||||
if (!hasSvelteConfig && !hasKitPackage) return null;
|
||||
|
||||
return {
|
||||
appHtml,
|
||||
layoutFile: findSvelteKitLayout(cwd),
|
||||
rootComponent: SVELTE_LIVE_ROOT_COMPONENT,
|
||||
};
|
||||
}
|
||||
|
||||
export function applySvelteKitLiveAdapter({ cwd = process.cwd(), port, config = null } = {}) {
|
||||
if (!Number.isFinite(Number(port))) {
|
||||
throw new Error('SvelteKit live adapter requires a numeric port');
|
||||
}
|
||||
const detected = detectSvelteKitProject(cwd, config);
|
||||
if (!detected) return null;
|
||||
|
||||
ensureSvelteLiveRootComponent(cwd, Number(port));
|
||||
|
||||
const layoutRel = detected.layoutFile;
|
||||
const layoutAbs = path.join(cwd, layoutRel);
|
||||
fs.mkdirSync(path.dirname(layoutAbs), { recursive: true });
|
||||
const layoutExisted = fs.existsSync(layoutAbs);
|
||||
const before = layoutExisted ? fs.readFileSync(layoutAbs, 'utf-8') : defaultSvelteLayout();
|
||||
const after = patchSvelteLayout(before);
|
||||
fs.writeFileSync(layoutAbs, after, 'utf-8');
|
||||
|
||||
return {
|
||||
file: layoutRel,
|
||||
adapter: 'sveltekit',
|
||||
inserted: after !== before || !layoutExisted,
|
||||
appHtmlUntouched: true,
|
||||
rootComponent: SVELTE_LIVE_ROOT_COMPONENT,
|
||||
};
|
||||
}
|
||||
|
||||
export function removeSvelteKitLiveAdapter({ cwd = process.cwd(), config = null } = {}) {
|
||||
const detected = detectSvelteKitProject(cwd, config);
|
||||
if (!detected) return null;
|
||||
|
||||
const layoutAbs = path.join(cwd, detected.layoutFile);
|
||||
let removed = false;
|
||||
if (fs.existsSync(layoutAbs)) {
|
||||
const before = fs.readFileSync(layoutAbs, 'utf-8');
|
||||
const after = unpatchSvelteLayout(before);
|
||||
if (after !== before) {
|
||||
fs.writeFileSync(layoutAbs, after, 'utf-8');
|
||||
removed = true;
|
||||
}
|
||||
}
|
||||
|
||||
const rootAbs = path.join(cwd, SVELTE_LIVE_ROOT_COMPONENT);
|
||||
if (fs.existsSync(rootAbs)) {
|
||||
fs.rmSync(rootAbs, { force: true });
|
||||
removed = true;
|
||||
}
|
||||
|
||||
pruneEmptyDir(path.dirname(rootAbs), path.join(cwd, 'src'));
|
||||
|
||||
return {
|
||||
file: detected.layoutFile,
|
||||
adapter: 'sveltekit',
|
||||
removed,
|
||||
appHtmlUntouched: true,
|
||||
rootComponent: SVELTE_LIVE_ROOT_COMPONENT,
|
||||
};
|
||||
}
|
||||
|
||||
export function patchSvelteLayout(content) {
|
||||
let out = String(content || '');
|
||||
if (!out.includes(SVELTE_ROOT_IMPORT)) {
|
||||
const scriptMatch = out.match(/<script(?:\s[^>]*)?>/i);
|
||||
if (scriptMatch) {
|
||||
const insertAt = scriptMatch.index + scriptMatch[0].length;
|
||||
out = out.slice(0, insertAt) + '\n ' + SVELTE_ROOT_IMPORT + out.slice(insertAt);
|
||||
} else {
|
||||
out = `<script>\n ${SVELTE_ROOT_IMPORT}\n</script>\n\n` + out;
|
||||
}
|
||||
}
|
||||
|
||||
if (!out.includes(SVELTE_LAYOUT_MARKER_OPEN)) {
|
||||
const block = `${SVELTE_LAYOUT_MARKER_OPEN}\n<ImpeccableLiveRoot />\n${SVELTE_LAYOUT_MARKER_CLOSE}\n`;
|
||||
const renderMatch = out.match(/\{@render\s+children(?:\?\.)?\(\)\s*\}/);
|
||||
const slotMatch = out.match(/<slot\s*\/?>/);
|
||||
const match = renderMatch || slotMatch;
|
||||
if (match) {
|
||||
out = out.slice(0, match.index) + block + out.slice(match.index);
|
||||
} else {
|
||||
out = out.replace(/\s*$/, '\n\n' + block);
|
||||
}
|
||||
}
|
||||
|
||||
return out;
|
||||
}
|
||||
|
||||
export function unpatchSvelteLayout(content) {
|
||||
let out = String(content || '');
|
||||
const blockRe = new RegExp(
|
||||
'([ \\t]*)' + escapeRegExp(SVELTE_LAYOUT_MARKER_OPEN)
|
||||
+ '\\n<ImpeccableLiveRoot\\s*/>\\n'
|
||||
+ escapeRegExp(SVELTE_LAYOUT_MARKER_CLOSE)
|
||||
+ '\\n?',
|
||||
'g',
|
||||
);
|
||||
out = out.replace(blockRe, '$1');
|
||||
out = out.replace(new RegExp('^\\s*' + escapeRegExp(SVELTE_ROOT_IMPORT) + '\\s*\\n?', 'gm'), '');
|
||||
out = out.replace(/<script>\s*<\/script>\s*\n?/g, '');
|
||||
return out.replace(/\n{3,}/g, '\n\n');
|
||||
}
|
||||
|
||||
export function ensureSvelteLiveRootComponent(cwd, port) {
|
||||
const file = path.join(cwd, SVELTE_LIVE_ROOT_COMPONENT);
|
||||
fs.mkdirSync(path.dirname(file), { recursive: true });
|
||||
fs.writeFileSync(file, buildSvelteLiveRootComponent(port), 'utf-8');
|
||||
return file;
|
||||
}
|
||||
|
||||
export function buildSvelteLiveRootComponent(port) {
|
||||
return `<script>
|
||||
import { onMount } from 'svelte';
|
||||
|
||||
const LIVE_URL = 'http://localhost:${Number(port)}/live.js';
|
||||
const HOST_ID = 'impeccable-live-root';
|
||||
|
||||
onMount(() => {
|
||||
let host = document.querySelector('impeccable-live-root#' + HOST_ID) || document.getElementById(HOST_ID);
|
||||
if (!host) {
|
||||
host = document.createElement('impeccable-live-root');
|
||||
host.id = HOST_ID;
|
||||
document.body.appendChild(host);
|
||||
}
|
||||
|
||||
host.dataset.impeccableLiveAdapter = 'sveltekit';
|
||||
host.style.setProperty('all', 'initial', 'important');
|
||||
host.style.setProperty('display', 'block', 'important');
|
||||
host.style.setProperty('position', 'fixed', 'important');
|
||||
host.style.setProperty('top', '0', 'important');
|
||||
host.style.setProperty('left', '0', 'important');
|
||||
host.style.setProperty('width', '0', 'important');
|
||||
host.style.setProperty('height', '0', 'important');
|
||||
host.style.setProperty('overflow', 'visible', 'important');
|
||||
host.style.setProperty('z-index', '2147483000', 'important');
|
||||
host.style.setProperty('pointer-events', 'none', 'important');
|
||||
|
||||
const root = host.shadowRoot || host.attachShadow({ mode: 'open' });
|
||||
if (!root.querySelector('style[data-impeccable-live-reset]')) {
|
||||
const reset = document.createElement('style');
|
||||
reset.dataset.impeccableLiveReset = 'true';
|
||||
reset.textContent = ':host, :host *, * { box-sizing: border-box; }';
|
||||
root.appendChild(reset);
|
||||
}
|
||||
|
||||
window.__IMPECCABLE_LIVE_ADAPTER__ = 'sveltekit';
|
||||
window.__IMPECCABLE_LIVE_UI_ROOT__ = root;
|
||||
window.__IMPECCABLE_LIVE_CHROME_MOUNT__ = {
|
||||
adapter: 'sveltekit',
|
||||
version: 1,
|
||||
host,
|
||||
root,
|
||||
};
|
||||
|
||||
const script = document.createElement('script');
|
||||
script.src = LIVE_URL;
|
||||
script.async = true;
|
||||
script.dataset.impeccableLiveScript = 'true';
|
||||
document.head.appendChild(script);
|
||||
|
||||
return () => {
|
||||
script.remove();
|
||||
if (window.__IMPECCABLE_LIVE_UI_ROOT__ === root) delete window.__IMPECCABLE_LIVE_UI_ROOT__;
|
||||
if (window.__IMPECCABLE_LIVE_CHROME_MOUNT__?.root === root) delete window.__IMPECCABLE_LIVE_CHROME_MOUNT__;
|
||||
if (window.__IMPECCABLE_LIVE_ADAPTER__ === 'sveltekit') delete window.__IMPECCABLE_LIVE_ADAPTER__;
|
||||
};
|
||||
});
|
||||
</script>
|
||||
`;
|
||||
}
|
||||
|
||||
function findSvelteKitAppHtml(cwd, config) {
|
||||
const files = Array.isArray(config?.files) ? config.files : ['src/app.html'];
|
||||
for (const rel of files) {
|
||||
if (rel.includes('*')) continue;
|
||||
const normalized = rel.split(path.sep).join('/');
|
||||
if (!normalized.endsWith('app.html')) continue;
|
||||
const abs = path.join(cwd, normalized);
|
||||
if (fs.existsSync(abs)) return normalized;
|
||||
}
|
||||
const fallback = 'src/app.html';
|
||||
return fs.existsSync(path.join(cwd, fallback)) ? fallback : null;
|
||||
}
|
||||
|
||||
function findSvelteKitLayout(cwd) {
|
||||
const candidates = [
|
||||
'src/routes/+layout.svelte',
|
||||
'src/routes/(app)/+layout.svelte',
|
||||
];
|
||||
for (const rel of candidates) {
|
||||
if (fs.existsSync(path.join(cwd, rel))) return rel;
|
||||
}
|
||||
return 'src/routes/+layout.svelte';
|
||||
}
|
||||
|
||||
function defaultSvelteLayout() {
|
||||
return `<script>\n let { children } = $props();\n</script>\n\n{@render children?.()}\n`;
|
||||
}
|
||||
|
||||
function packageHasSvelteKit(cwd) {
|
||||
const file = path.join(cwd, 'package.json');
|
||||
if (!fs.existsSync(file)) return false;
|
||||
try {
|
||||
const pkg = JSON.parse(fs.readFileSync(file, 'utf-8'));
|
||||
const deps = {
|
||||
...(pkg.dependencies || {}),
|
||||
...(pkg.devDependencies || {}),
|
||||
...(pkg.peerDependencies || {}),
|
||||
};
|
||||
return Boolean(deps['@sveltejs/kit'] || deps['@sveltejs/vite-plugin-svelte'] || deps.svelte);
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
function fileIncludes(file, text) {
|
||||
try {
|
||||
return fs.readFileSync(file, 'utf-8').includes(text);
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
function pruneEmptyDir(dir, stopDir) {
|
||||
let current = dir;
|
||||
while (current.startsWith(stopDir) && current !== stopDir) {
|
||||
try {
|
||||
if (fs.readdirSync(current).length > 0) return;
|
||||
fs.rmdirSync(current);
|
||||
current = path.dirname(current);
|
||||
} catch {
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function escapeRegExp(value) {
|
||||
return String(value).replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
|
||||
}
|
||||
@@ -0,0 +1,180 @@
|
||||
/**
|
||||
* Framework-neutral Impeccable live chrome contract.
|
||||
*
|
||||
* The production browser bundle is intentionally plain DOM so Svelte, React,
|
||||
* Vue, and static adapters can all mount the same chrome. This module is the
|
||||
* testable contract/inventory for that bundle; live-browser.js mirrors these
|
||||
* values at runtime because it is served as a standalone script.
|
||||
*/
|
||||
|
||||
export const LIVE_CHROME_MOUNT_CONTRACT = Object.freeze([
|
||||
'root',
|
||||
'transport',
|
||||
'state',
|
||||
'actions',
|
||||
]);
|
||||
|
||||
export const LIVE_UI_SURFACES = Object.freeze([
|
||||
{
|
||||
key: 'global-bottom-bar',
|
||||
ids: [
|
||||
'impeccable-live-global-bar',
|
||||
'impeccable-live-global-bar-brand',
|
||||
'impeccable-live-pick-toggle',
|
||||
'impeccable-live-insert-toggle',
|
||||
'impeccable-live-detect-toggle',
|
||||
'impeccable-live-detect-badge',
|
||||
'impeccable-live-design-toggle',
|
||||
'impeccable-live-page-chat',
|
||||
'impeccable-live-page-chat-input',
|
||||
'impeccable-live-page-chat-voice',
|
||||
],
|
||||
states: ['rest', 'hover', 'focus-visible', 'pressed', 'active', 'tooltip'],
|
||||
},
|
||||
{
|
||||
key: 'pending-copy-edit-dock',
|
||||
ids: ['impeccable-live-pending-dock'],
|
||||
states: ['closed', 'open', 'hover', 'pressed', 'loading', 'rollback', 'keep-fixing'],
|
||||
},
|
||||
{
|
||||
key: 'element-selection-chrome',
|
||||
ids: [
|
||||
'impeccable-live-highlight',
|
||||
'impeccable-live-tooltip',
|
||||
'impeccable-live-bar',
|
||||
'impeccable-live-selection-pill',
|
||||
'impeccable-live-input',
|
||||
'impeccable-live-configure-voice',
|
||||
'impeccable-live-configure-bar-tooltip',
|
||||
],
|
||||
states: ['rest', 'hover', 'focus-visible', 'pressed', 'disabled'],
|
||||
},
|
||||
{
|
||||
key: 'action-picker',
|
||||
ids: ['impeccable-live-picker'],
|
||||
states: ['closed', 'open', 'option-hover', 'option-focus'],
|
||||
},
|
||||
{
|
||||
key: 'edit-chrome',
|
||||
ids: ['impeccable-live-edit-badge'],
|
||||
states: ['enabled', 'disabled', 'editing', 'cancel', 'save', 'edited-content'],
|
||||
},
|
||||
{
|
||||
key: 'generating-row',
|
||||
ids: ['impeccable-live-bar', 'impeccable-live-shader'],
|
||||
states: ['action-label', 'animated-dots', 'generating', 'done'],
|
||||
},
|
||||
{
|
||||
key: 'variant-cycling-row',
|
||||
ids: ['impeccable-live-bar', 'impeccable-live-params-panel'],
|
||||
states: ['variant-1', 'variant-2', 'variant-3', 'left-disabled', 'right-disabled', 'dot-click', 'accept', 'discard'],
|
||||
},
|
||||
{
|
||||
key: 'variant-params-panel',
|
||||
ids: ['impeccable-live-params-panel'],
|
||||
states: ['closed', 'open-above', 'open-below', 'range', 'steps', 'toggle'],
|
||||
},
|
||||
{
|
||||
key: 'saving-confirmed-rows',
|
||||
ids: ['impeccable-live-bar'],
|
||||
states: ['saving', 'applying-variant', 'confirmed'],
|
||||
},
|
||||
{
|
||||
key: 'insert-mode-chrome',
|
||||
ids: [
|
||||
'impeccable-live-insert-line',
|
||||
'impeccable-live-insert-placeholder',
|
||||
'impeccable-live-placeholder-resize',
|
||||
'impeccable-live-insert-input',
|
||||
'impeccable-live-insert-voice',
|
||||
'impeccable-live-insert-create',
|
||||
'impeccable-live-insert-create-tooltip',
|
||||
],
|
||||
states: ['toggle-active', 'line', 'placeholder', 'resize', 'enabled', 'disabled', 'tooltip'],
|
||||
},
|
||||
{
|
||||
key: 'annotation-chrome',
|
||||
ids: [
|
||||
'impeccable-live-annot',
|
||||
'impeccable-live-annot-svg',
|
||||
'impeccable-live-annot-pins',
|
||||
'impeccable-live-annot-clear',
|
||||
],
|
||||
states: ['overlay', 'drawing', 'pin', 'pin-edit', 'clear'],
|
||||
},
|
||||
{
|
||||
key: 'design-system-panel',
|
||||
ids: ['impeccable-live-design-host'],
|
||||
states: ['closed', 'open', 'tabs', 'token-tiles', 'copy'],
|
||||
},
|
||||
{
|
||||
key: 'toasts-and-errors',
|
||||
ids: ['impeccable-live-toast'],
|
||||
states: ['normal', 'error', 'no-variants-mounted'],
|
||||
},
|
||||
{
|
||||
key: 'css-isolation-boundary',
|
||||
ids: ['impeccable-live-root'],
|
||||
states: ['shadow-root', 'style-tags', 'hostile-css'],
|
||||
},
|
||||
]);
|
||||
|
||||
export const LIVE_UI_COMPONENT_IDS = Object.freeze([
|
||||
...new Set(LIVE_UI_SURFACES.flatMap((surface) => surface.ids)),
|
||||
]);
|
||||
|
||||
export function resolveLiveUiRoot(env = globalThis) {
|
||||
const doc = env?.document;
|
||||
const explicit = env?.__IMPECCABLE_LIVE_UI_ROOT__
|
||||
|| env?.window?.__IMPECCABLE_LIVE_UI_ROOT__;
|
||||
if (explicit && typeof explicit.appendChild === 'function') return explicit;
|
||||
return doc?.body || null;
|
||||
}
|
||||
|
||||
export function getLiveUiElementById(id, env = globalThis) {
|
||||
const doc = env?.document;
|
||||
const root = resolveLiveUiRoot(env);
|
||||
if (!id) return null;
|
||||
if (root?.getElementById) {
|
||||
const found = root.getElementById(id);
|
||||
if (found) return found;
|
||||
}
|
||||
if (root?.querySelector) {
|
||||
const found = root.querySelector('#' + escapeCssIdent(id));
|
||||
if (found) return found;
|
||||
}
|
||||
return doc?.getElementById?.(id) || null;
|
||||
}
|
||||
|
||||
export function appendToLiveUiRoot(el, env = globalThis) {
|
||||
const root = resolveLiveUiRoot(env);
|
||||
if (!root) throw new Error('Impeccable live UI root is not available');
|
||||
root.appendChild(el);
|
||||
return el;
|
||||
}
|
||||
|
||||
export function appendStyleToLiveUiRoot(styleEl, env = globalThis) {
|
||||
const doc = env?.document;
|
||||
const root = resolveLiveUiRoot(env);
|
||||
if (root && root !== doc?.body) {
|
||||
root.appendChild(styleEl);
|
||||
} else {
|
||||
(doc?.head || doc?.body || root).appendChild(styleEl);
|
||||
}
|
||||
return styleEl;
|
||||
}
|
||||
|
||||
export function activeElementDeep(doc = globalThis.document) {
|
||||
let active = doc?.activeElement || null;
|
||||
while (active?.shadowRoot?.activeElement) {
|
||||
active = active.shadowRoot.activeElement;
|
||||
}
|
||||
return active;
|
||||
}
|
||||
|
||||
function escapeCssIdent(value) {
|
||||
if (typeof CSS !== 'undefined' && typeof CSS.escape === 'function') {
|
||||
return CSS.escape(String(value));
|
||||
}
|
||||
return String(value).replace(/([ !"#$%&'()*+,./:;<=>?@[\\\]^`{|}~])/g, '\\$1');
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
/**
|
||||
* Canonical design-command vocabulary for Live Mode: each command's value, human
|
||||
* label, and SVG icon. Icons stack above the chip label; strokes use currentColor
|
||||
* so the icon recolors when its chip is selected.
|
||||
*
|
||||
* Single source of truth, consumed by:
|
||||
* - skill/scripts/live/event-validation.mjs — re-exports VISUAL_ACTIONS.
|
||||
* - skill/scripts/live-browser.js — the real picker. It is served raw and
|
||||
* injected as an IIFE, so it cannot import this at runtime; live-server.mjs
|
||||
* serializes LIVE_COMMANDS into window.__IMPECCABLE_VOCAB__ alongside the
|
||||
* token/port, and live-browser.js builds its ICONS + ACTIONS from that.
|
||||
* - site/components/LiveDemoPalette.astro — the marketing demo palette (imported
|
||||
* at build time).
|
||||
*
|
||||
* Add, rename, or reorder a verb here and all three follow.
|
||||
*/
|
||||
|
||||
const ICON_ATTRS = 'width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" style="display:block"';
|
||||
|
||||
export const LIVE_COMMANDS = [
|
||||
{ value: 'impeccable', label: 'Freeform', icon: `<svg ${ICON_ATTRS}><path d="M4 20l4-1L18 9l-3-3L5 16z"/><path d="M14 7l3 3"/></svg>` },
|
||||
{ value: 'bolder', label: 'Bolder', icon: `<svg ${ICON_ATTRS}><rect x="6" y="12" width="4" height="7" rx="0.5"/><rect x="14" y="5" width="4" height="14" rx="0.5"/></svg>` },
|
||||
{ value: 'quieter', label: 'Quieter', icon: `<svg ${ICON_ATTRS}><rect x="6" y="5" width="4" height="14" rx="0.5"/><rect x="14" y="12" width="4" height="7" rx="0.5"/></svg>` },
|
||||
{ value: 'distill', label: 'Distill', icon: `<svg ${ICON_ATTRS}><path d="M4 5h16l-6 8v7l-4-2v-5z"/></svg>` },
|
||||
{ value: 'polish', label: 'Polish', icon: `<svg ${ICON_ATTRS}><path d="M15 3l1 3 3 1-3 1-1 3-1-3-3-1 3-1z"/><path d="M7 13l0.6 1.8 1.8 0.6-1.8 0.6-0.6 1.8-0.6-1.8-1.8-0.6 1.8-0.6z"/></svg>` },
|
||||
{ value: 'typeset', label: 'Typeset', icon: `<svg ${ICON_ATTRS}><path d="M5 6h14" stroke-width="2.6"/><path d="M5 12h9" stroke-width="1.9"/><path d="M5 18h5" stroke-width="1.3"/></svg>` },
|
||||
{ value: 'colorize', label: 'Colorize', icon: `<svg ${ICON_ATTRS}><circle cx="9" cy="10" r="5"/><circle cx="15" cy="10" r="5"/><circle cx="12" cy="15" r="5"/></svg>` },
|
||||
{ value: 'layout', label: 'Layout', icon: `<svg ${ICON_ATTRS}><rect x="3" y="4" width="8" height="16" rx="0.5"/><rect x="13" y="4" width="8" height="7" rx="0.5"/><rect x="13" y="13" width="8" height="7" rx="0.5"/></svg>` },
|
||||
{ value: 'adapt', label: 'Adapt', icon: `<svg ${ICON_ATTRS}><rect x="2.5" y="5" width="12" height="11" rx="1"/><line x1="2.5" y1="19" x2="14.5" y2="19"/><rect x="16.5" y="8" width="5" height="11" rx="1"/></svg>` },
|
||||
{ value: 'animate', label: 'Animate', icon: `<svg ${ICON_ATTRS}><path d="M3 18c4-4 6-10 10-10"/><path d="M13 8c3 0 5 5 8 10"/><circle cx="13" cy="8" r="1.6" fill="currentColor" stroke="none"/></svg>` },
|
||||
{ value: 'delight', label: 'Delight', icon: `<svg ${ICON_ATTRS}><path d="M12 3l2 6 6 2-6 2-2 6-2-6-6-2 6-2z"/></svg>` },
|
||||
{ value: 'overdrive', label: 'Overdrive', icon: `<svg ${ICON_ATTRS}><path d="M13 3L5 13h5l-1 8 9-12h-6z"/></svg>` },
|
||||
];
|
||||
|
||||
// Action values accepted by the live event protocol, in palette order.
|
||||
export const VISUAL_ACTIONS = LIVE_COMMANDS.map((c) => c.value);
|
||||
Reference in New Issue
Block a user