@monoes/monodesign 1.2.20 → 1.2.22
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +2 -2
- package/cli/engine/design-system-checks.mjs +381 -0
- package/cli/engine/design-system-parse.mjs +433 -0
- package/cli/engine/design-system.mjs +20 -736
- package/cli/engine/engines/regex/detect-text-matchers.mjs +371 -0
- package/cli/engine/engines/regex/detect-text-run.mjs +186 -0
- package/cli/engine/engines/regex/detect-text.mjs +11 -523
- package/cli/engine/engines/static-html/css-cascade-color.mjs +219 -0
- package/cli/engine/engines/static-html/css-cascade-static-data.mjs +138 -0
- package/cli/engine/engines/static-html/css-cascade-static-dom.mjs +132 -0
- package/cli/engine/engines/static-html/css-cascade-static-parse.mjs +393 -0
- package/cli/engine/engines/static-html/css-cascade.mjs +24 -837
- package/cli/lib/monodesign-config-consent.mjs +93 -0
- package/cli/lib/monodesign-config-core.mjs +37 -0
- package/cli/lib/monodesign-config-detection.mjs +133 -0
- package/cli/lib/monodesign-config-filter.mjs +198 -0
- package/cli/lib/monodesign-config-ignore-value.mjs +212 -0
- package/cli/lib/monodesign-config.mjs +21 -623
- package/package.json +2 -2
- package/skill/scripts/context-fields.mjs +65 -0
- package/skill/scripts/context-resolve.mjs +425 -0
- package/skill/scripts/context-update.mjs +151 -0
- package/skill/scripts/context-utils.mjs +68 -0
- package/skill/scripts/context-workspace.mjs +245 -0
- package/skill/scripts/context.mjs +17 -891
- package/skill/scripts/hook-admin-config.mjs +152 -0
- package/skill/scripts/hook-admin-ignore.mjs +131 -0
- package/skill/scripts/hook-admin-manifest.mjs +292 -0
- package/skill/scripts/hook-admin.mjs +8 -541
- package/skill/scripts/hook-lib-cache.mjs +145 -0
- package/skill/scripts/hook-lib-config.mjs +292 -0
- package/skill/scripts/hook-lib-detector.mjs +72 -0
- package/skill/scripts/hook-lib-events.mjs +182 -0
- package/skill/scripts/hook-lib-findings.mjs +201 -0
- package/skill/scripts/hook-lib-ignore.mjs +205 -0
- package/skill/scripts/hook-lib-render.mjs +273 -0
- package/skill/scripts/hook-lib-run.mjs +281 -0
- package/skill/scripts/hook-lib-scan-targets.mjs +128 -0
- package/skill/scripts/hook-lib.mjs +71 -1747
- package/skill/scripts/lib/design-parser-colors.mjs +182 -0
- package/skill/scripts/lib/design-parser-extract.mjs +333 -0
- package/skill/scripts/lib/design-parser-sections.mjs +214 -0
- package/skill/scripts/lib/design-parser-yaml.mjs +135 -0
- package/skill/scripts/lib/design-parser.mjs +10 -783
- package/skill/scripts/live/manual-apply-chunk.mjs +151 -0
- package/skill/scripts/live/manual-apply-compact.mjs +122 -0
- package/skill/scripts/live/manual-apply-evidence.mjs +115 -0
- package/skill/scripts/live/manual-apply-log.mjs +179 -0
- package/skill/scripts/live/manual-apply-transaction.mjs +122 -0
- package/skill/scripts/live/manual-apply.mjs +65 -640
- package/skill/scripts/live/svelte-component-accept.mjs +248 -0
- package/skill/scripts/live/svelte-component-css.mjs +230 -0
- package/skill/scripts/live/svelte-component-markup.mjs +104 -0
- package/skill/scripts/live/svelte-component-scaffold.mjs +118 -0
- package/skill/scripts/live/svelte-component-session.mjs +158 -0
- package/skill/scripts/live/svelte-component.mjs +32 -792
- package/skill/scripts/live-accept-mutate.mjs +152 -0
- package/skill/scripts/live-accept-parse.mjs +370 -0
- package/skill/scripts/live-accept-scrub.mjs +59 -0
- package/skill/scripts/live-accept-search.mjs +58 -0
- package/skill/scripts/live-accept.mjs +15 -631
- package/skill/scripts/live-commit-manual-edits-paths.mjs +27 -0
- package/skill/scripts/live-commit-manual-edits-repair.mjs +166 -0
- package/skill/scripts/live-commit-manual-edits-rollback.mjs +231 -0
- package/skill/scripts/live-commit-manual-edits-utils.mjs +167 -0
- package/skill/scripts/live-commit-manual-edits-verify.mjs +356 -0
- package/skill/scripts/live-commit-manual-edits.mjs +24 -881
- package/skill/scripts/live-copy-edit-agent.mjs +16 -551
- package/skill/scripts/live-copy-edit-compact.mjs +137 -0
- package/skill/scripts/live-copy-edit-post-apply.mjs +175 -0
- package/skill/scripts/live-copy-edit-runners.mjs +297 -0
- package/skill/scripts/live-inject-csp.mjs +132 -0
- package/skill/scripts/live-inject-files.mjs +229 -0
- package/skill/scripts/live-inject-tag.mjs +114 -0
- package/skill/scripts/live-inject.mjs +13 -440
- package/skill/scripts/live-server-poll.mjs +232 -0
- package/skill/scripts/live-server-routes.mjs +449 -0
- package/skill/scripts/live-server-state.mjs +361 -0
- package/skill/scripts/live-server.mjs +10 -946
- package/skill/scripts/live-wrap-css.mjs +132 -0
- package/skill/scripts/live-wrap-manual-edit.mjs +153 -0
- package/skill/scripts/live-wrap-search.mjs +247 -0
- package/skill/scripts/live-wrap.mjs +21 -484
- package/skill/scripts/palette-seeds.mjs +401 -0
- package/skill/scripts/palette.mjs +1 -395
|
@@ -0,0 +1,232 @@
|
|
|
1
|
+
// Live server agent-poll endpoints: long-poll GET (agent waits for the next
|
|
2
|
+
// browser event) and POST (agent replies with a result). Split out of
|
|
3
|
+
// live-server.mjs (file-size sweep — pure move, no behaviour change).
|
|
4
|
+
|
|
5
|
+
import fs from 'node:fs';
|
|
6
|
+
import path from 'node:path';
|
|
7
|
+
import { summarizeManualApplyFailures } from './live/manual-apply.mjs';
|
|
8
|
+
import {
|
|
9
|
+
state,
|
|
10
|
+
DEFAULT_POLL_TIMEOUT,
|
|
11
|
+
manualApply,
|
|
12
|
+
findAvailablePendingEvent,
|
|
13
|
+
leaseEvent,
|
|
14
|
+
acknowledgePendingEvent,
|
|
15
|
+
findPendingEventById,
|
|
16
|
+
scheduleLeaseFlush,
|
|
17
|
+
flushPendingPolls,
|
|
18
|
+
broadcastAgentPollingIfChanged,
|
|
19
|
+
broadcast,
|
|
20
|
+
recordManualEditActivity,
|
|
21
|
+
} from './live-server-state.mjs';
|
|
22
|
+
|
|
23
|
+
// ---------------------------------------------------------------------------
|
|
24
|
+
// Agent poll endpoints (unchanged from WS version)
|
|
25
|
+
// ---------------------------------------------------------------------------
|
|
26
|
+
|
|
27
|
+
function handlePollGet(req, res, url) {
|
|
28
|
+
const token = url.searchParams.get('token');
|
|
29
|
+
if (token !== state.token) {
|
|
30
|
+
res.writeHead(401, { 'Content-Type': 'application/json' });
|
|
31
|
+
res.end(JSON.stringify({ error: 'Unauthorized' }));
|
|
32
|
+
return;
|
|
33
|
+
}
|
|
34
|
+
state.lastPollAt = Date.now();
|
|
35
|
+
const timeout = parseInt(url.searchParams.get('timeout') || DEFAULT_POLL_TIMEOUT, 10);
|
|
36
|
+
const leaseMs = parseInt(url.searchParams.get('leaseMs') || '30000', 10);
|
|
37
|
+
const available = findAvailablePendingEvent();
|
|
38
|
+
if (available) {
|
|
39
|
+
res.writeHead(200, { 'Content-Type': 'application/json' });
|
|
40
|
+
res.end(JSON.stringify(leaseEvent(available, leaseMs)));
|
|
41
|
+
return;
|
|
42
|
+
}
|
|
43
|
+
const poll = { resolve, leaseMs };
|
|
44
|
+
const timer = setTimeout(() => {
|
|
45
|
+
const idx = state.pendingPolls.indexOf(poll);
|
|
46
|
+
if (idx !== -1) state.pendingPolls.splice(idx, 1);
|
|
47
|
+
broadcastAgentPollingIfChanged();
|
|
48
|
+
res.writeHead(200, { 'Content-Type': 'application/json' });
|
|
49
|
+
res.end(JSON.stringify({ type: 'timeout' }));
|
|
50
|
+
}, timeout);
|
|
51
|
+
function resolve(event) {
|
|
52
|
+
clearTimeout(timer);
|
|
53
|
+
state.lastPollAt = Date.now();
|
|
54
|
+
res.writeHead(200, { 'Content-Type': 'application/json' });
|
|
55
|
+
res.end(JSON.stringify(event));
|
|
56
|
+
}
|
|
57
|
+
state.pendingPolls.push(poll);
|
|
58
|
+
broadcastAgentPollingIfChanged();
|
|
59
|
+
scheduleLeaseFlush();
|
|
60
|
+
req.on('close', () => {
|
|
61
|
+
clearTimeout(timer);
|
|
62
|
+
const idx = state.pendingPolls.indexOf(poll);
|
|
63
|
+
if (idx !== -1) state.pendingPolls.splice(idx, 1);
|
|
64
|
+
broadcastAgentPollingIfChanged();
|
|
65
|
+
});
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
function sessionFileMetadataFromPollReply(file) {
|
|
69
|
+
if (!file || typeof file !== 'string') return { file };
|
|
70
|
+
const normalized = file.split(path.sep).join('/');
|
|
71
|
+
const base = { file: normalized };
|
|
72
|
+
if (!normalized.endsWith('/manifest.json') && normalized !== 'manifest.json') return base;
|
|
73
|
+
if (!normalized.includes('node_modules/.monodesign-live/') && !normalized.includes('src/lib/monodesign/')) return base;
|
|
74
|
+
|
|
75
|
+
let full;
|
|
76
|
+
try {
|
|
77
|
+
full = path.resolve(process.cwd(), normalized);
|
|
78
|
+
const rel = path.relative(process.cwd(), full).split(path.sep).join('/');
|
|
79
|
+
if (!rel || rel.startsWith('..') || path.isAbsolute(rel)) return base;
|
|
80
|
+
} catch {
|
|
81
|
+
return base;
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
try {
|
|
85
|
+
const manifest = JSON.parse(fs.readFileSync(full, 'utf-8'));
|
|
86
|
+
if (manifest?.previewMode !== 'svelte-component' || !manifest.sourceFile) return base;
|
|
87
|
+
return {
|
|
88
|
+
file: String(manifest.sourceFile).split(path.sep).join('/'),
|
|
89
|
+
sourceFile: String(manifest.sourceFile).split(path.sep).join('/'),
|
|
90
|
+
previewFile: normalized,
|
|
91
|
+
previewMode: 'svelte-component',
|
|
92
|
+
};
|
|
93
|
+
} catch {
|
|
94
|
+
return base;
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
function handlePollPost(req, res) {
|
|
99
|
+
let body = '';
|
|
100
|
+
req.on('data', (c) => { body += c; });
|
|
101
|
+
req.on('end', () => {
|
|
102
|
+
let msg;
|
|
103
|
+
try { msg = JSON.parse(body); } catch {
|
|
104
|
+
res.writeHead(400, { 'Content-Type': 'application/json' });
|
|
105
|
+
res.end(JSON.stringify({ error: 'Invalid JSON' }));
|
|
106
|
+
return;
|
|
107
|
+
}
|
|
108
|
+
if (msg.token !== state.token) {
|
|
109
|
+
res.writeHead(401, { 'Content-Type': 'application/json' });
|
|
110
|
+
res.end(JSON.stringify({ error: 'Unauthorized' }));
|
|
111
|
+
return;
|
|
112
|
+
}
|
|
113
|
+
const pendingApplyDeferred = manualApply.getDeferred(msg.id);
|
|
114
|
+
if (pendingApplyDeferred) {
|
|
115
|
+
const validation = manualApply.validateResultMessage(msg, pendingApplyDeferred);
|
|
116
|
+
if (!validation.ok) {
|
|
117
|
+
recordManualEditActivity('manual_edit_apply_reply_invalid', {
|
|
118
|
+
id: msg.id,
|
|
119
|
+
pageUrl: pendingApplyDeferred.pageUrl,
|
|
120
|
+
chunk: pendingApplyDeferred.event?.chunk || null,
|
|
121
|
+
repair: pendingApplyDeferred.event?.repair || null,
|
|
122
|
+
reason: validation.body?.reason || validation.body?.error || 'invalid_manual_apply_result',
|
|
123
|
+
status: msg.data?.status || null,
|
|
124
|
+
});
|
|
125
|
+
res.writeHead(400, { 'Content-Type': 'application/json' });
|
|
126
|
+
res.end(JSON.stringify(validation.body));
|
|
127
|
+
return;
|
|
128
|
+
}
|
|
129
|
+
recordManualEditActivity('manual_edit_apply_reply_received', {
|
|
130
|
+
id: msg.id,
|
|
131
|
+
pageUrl: pendingApplyDeferred.pageUrl,
|
|
132
|
+
chunk: pendingApplyDeferred.event?.chunk || null,
|
|
133
|
+
repair: pendingApplyDeferred.event?.repair || null,
|
|
134
|
+
status: validation.result.status,
|
|
135
|
+
appliedCount: validation.result.appliedEntryIds.length,
|
|
136
|
+
failed: summarizeManualApplyFailures(validation.result.failed),
|
|
137
|
+
fileCount: validation.result.files.length,
|
|
138
|
+
noteCount: validation.result.notes.length,
|
|
139
|
+
});
|
|
140
|
+
manualApply.resolveDeferred(msg.id, validation.result);
|
|
141
|
+
acknowledgePendingEvent(msg.id);
|
|
142
|
+
flushPendingPolls();
|
|
143
|
+
res.writeHead(200, { 'Content-Type': 'application/json' });
|
|
144
|
+
res.end(JSON.stringify({ ok: true }));
|
|
145
|
+
return;
|
|
146
|
+
}
|
|
147
|
+
if (manualApply.hasTimedOutId(msg.id)) {
|
|
148
|
+
const rollback = manualApply.rollbackTimedOutReply(msg);
|
|
149
|
+
recordManualEditActivity('manual_edit_apply_stale_reply_rejected', {
|
|
150
|
+
id: msg.id,
|
|
151
|
+
rolledBackFileCount: rollback.rolledBackFiles?.length || 0,
|
|
152
|
+
rollbackFailureCount: rollback.rollbackFailures?.length || 0,
|
|
153
|
+
});
|
|
154
|
+
res.writeHead(409, { 'Content-Type': 'application/json' });
|
|
155
|
+
res.end(JSON.stringify({ error: 'stale_manual_edit_apply_reply', ...rollback }));
|
|
156
|
+
return;
|
|
157
|
+
}
|
|
158
|
+
const pendingEventBeforeAck = findPendingEventById(msg.id);
|
|
159
|
+
if (pendingEventBeforeAck?.type === 'steer' && msg.type === 'steer_done'
|
|
160
|
+
&& !msg.file && !(typeof msg.message === 'string' && msg.message.trim())) {
|
|
161
|
+
res.writeHead(400, { 'Content-Type': 'application/json' });
|
|
162
|
+
res.end(JSON.stringify({
|
|
163
|
+
error: 'steer_done_requires_file_or_message',
|
|
164
|
+
hint: 'Reply with --file after writing source, or include a message explaining an intentional no-op.',
|
|
165
|
+
}));
|
|
166
|
+
return;
|
|
167
|
+
}
|
|
168
|
+
const acknowledgedEvent = acknowledgePendingEvent(msg.id);
|
|
169
|
+
let skipJournalReply = false;
|
|
170
|
+
let existingSession = null;
|
|
171
|
+
if (!acknowledgedEvent && state.sessionStore && msg.id) {
|
|
172
|
+
try {
|
|
173
|
+
existingSession = state.sessionStore.getSnapshot(msg.id, { includeCompleted: true });
|
|
174
|
+
if (!existingSession?.updatedAt) existingSession = null;
|
|
175
|
+
skipJournalReply = existingSession?.phase === 'completed' || existingSession?.phase === 'discarded';
|
|
176
|
+
} catch { /* fall through and record the reply normally */ }
|
|
177
|
+
}
|
|
178
|
+
if (!acknowledgedEvent && !existingSession) {
|
|
179
|
+
recordManualEditActivity('manual_edit_poll_reply_unknown', {
|
|
180
|
+
id: msg.id || null,
|
|
181
|
+
type: msg.type || null,
|
|
182
|
+
});
|
|
183
|
+
res.writeHead(msg.id ? 404 : 400, { 'Content-Type': 'application/json' });
|
|
184
|
+
res.end(JSON.stringify({
|
|
185
|
+
error: msg.id ? 'unknown_poll_reply_id' : 'missing_poll_reply_id',
|
|
186
|
+
id: msg.id,
|
|
187
|
+
}));
|
|
188
|
+
return;
|
|
189
|
+
}
|
|
190
|
+
const replyFileMeta = sessionFileMetadataFromPollReply(msg.file);
|
|
191
|
+
if (state.sessionStore && msg.id && !skipJournalReply) {
|
|
192
|
+
try {
|
|
193
|
+
const eventType = msg.type === 'steer_done'
|
|
194
|
+
? 'steer_done'
|
|
195
|
+
: msg.type === 'discard' || msg.type === 'discarded'
|
|
196
|
+
? 'discarded'
|
|
197
|
+
: msg.type === 'complete'
|
|
198
|
+
? 'complete'
|
|
199
|
+
: msg.type === 'error'
|
|
200
|
+
? 'agent_error'
|
|
201
|
+
: 'agent_done';
|
|
202
|
+
state.sessionStore.appendEvent({
|
|
203
|
+
type: eventType,
|
|
204
|
+
id: msg.id,
|
|
205
|
+
file: replyFileMeta.file,
|
|
206
|
+
sourceFile: replyFileMeta.sourceFile,
|
|
207
|
+
previewFile: replyFileMeta.previewFile,
|
|
208
|
+
previewMode: replyFileMeta.previewMode,
|
|
209
|
+
message: msg.message,
|
|
210
|
+
sourceEventType: acknowledgedEvent?.type,
|
|
211
|
+
carbonize: msg.data?.carbonize === true,
|
|
212
|
+
});
|
|
213
|
+
} catch { /* keep reply path best-effort; browser still needs SSE */ }
|
|
214
|
+
}
|
|
215
|
+
flushPendingPolls();
|
|
216
|
+
// Forward the reply to the browser via SSE
|
|
217
|
+
broadcast({
|
|
218
|
+
type: msg.type || 'done',
|
|
219
|
+
id: msg.id,
|
|
220
|
+
message: msg.message,
|
|
221
|
+
file: msg.file,
|
|
222
|
+
sourceFile: replyFileMeta.sourceFile,
|
|
223
|
+
previewFile: replyFileMeta.previewFile,
|
|
224
|
+
previewMode: replyFileMeta.previewMode,
|
|
225
|
+
data: msg.data,
|
|
226
|
+
});
|
|
227
|
+
res.writeHead(200, { 'Content-Type': 'application/json' });
|
|
228
|
+
res.end(JSON.stringify({ ok: true }));
|
|
229
|
+
});
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
export { handlePollGet, handlePollPost };
|
|
@@ -0,0 +1,449 @@
|
|
|
1
|
+
// Live server HTTP routing: loading the browser/detect scripts and the
|
|
2
|
+
// request handler that dispatches every route. Split out of live-server.mjs
|
|
3
|
+
// (file-size sweep — pure move, no behaviour change).
|
|
4
|
+
|
|
5
|
+
import fs from 'node:fs';
|
|
6
|
+
import path from 'node:path';
|
|
7
|
+
import { fileURLToPath } from 'node:url';
|
|
8
|
+
import { parseDesignMd } from './lib/design-parser.mjs';
|
|
9
|
+
import {
|
|
10
|
+
assembleLiveBrowserScript,
|
|
11
|
+
assertLiveBrowserScriptParts,
|
|
12
|
+
readLiveBrowserScriptParts,
|
|
13
|
+
resolveLiveBrowserScriptParts,
|
|
14
|
+
} from './live/browser-script-parts.mjs';
|
|
15
|
+
import { validateEvent } from './live/event-validation.mjs';
|
|
16
|
+
import { LIVE_COMMANDS } from './live/vocabulary.mjs';
|
|
17
|
+
import {
|
|
18
|
+
getDesignSidecarPath,
|
|
19
|
+
MONODESIGN_COMMAND_PREFIX,
|
|
20
|
+
resolveDesignSidecarPath,
|
|
21
|
+
} from './lib/monodesign-paths.mjs';
|
|
22
|
+
import {
|
|
23
|
+
state,
|
|
24
|
+
PROJECT_CONTEXT,
|
|
25
|
+
CONTEXT_DIR,
|
|
26
|
+
DESIGN_MD_PATH,
|
|
27
|
+
SSE_HEARTBEAT_INTERVAL,
|
|
28
|
+
MAX_ANNOTATION_BYTES,
|
|
29
|
+
activeSessionSummaries,
|
|
30
|
+
summarizePendingEventForStatus,
|
|
31
|
+
agentPollingConnected,
|
|
32
|
+
getManualEditStatus,
|
|
33
|
+
enqueueEvent,
|
|
34
|
+
cancelQueuedAnonymousExitEvents,
|
|
35
|
+
manualEditRoutes,
|
|
36
|
+
hasProjectContext,
|
|
37
|
+
statOrNull,
|
|
38
|
+
requireAuthQueryCred,
|
|
39
|
+
} from './live-server-state.mjs';
|
|
40
|
+
import { handlePollGet, handlePollPost } from './live-server-poll.mjs';
|
|
41
|
+
import { shutdown, cleanupSvelteComponentSessionsBeforeExit } from './live-server.mjs';
|
|
42
|
+
|
|
43
|
+
const __dirname = path.dirname(fileURLToPath(import.meta.url));
|
|
44
|
+
|
|
45
|
+
// ---------------------------------------------------------------------------
|
|
46
|
+
// Load scripts
|
|
47
|
+
// ---------------------------------------------------------------------------
|
|
48
|
+
|
|
49
|
+
function loadBrowserScripts() {
|
|
50
|
+
// Detection script: prefer the skill-bundled detector, then fall back to
|
|
51
|
+
// source/npm package locations for local development and older installs.
|
|
52
|
+
// This one IS cached — detect.js rarely changes during a session.
|
|
53
|
+
const detectPaths = [
|
|
54
|
+
path.join(__dirname, 'detector', 'detect-antipatterns-browser.js'),
|
|
55
|
+
path.join(__dirname, '..', '..', 'cli', 'engine', 'detect-antipatterns-browser.js'),
|
|
56
|
+
path.join(__dirname, '..', '..', '..', '..', 'cli', 'engine', 'detect-antipatterns-browser.js'),
|
|
57
|
+
path.join(process.cwd(), 'node_modules', 'monodesign', 'cli', 'engine', 'detect-antipatterns-browser.js'),
|
|
58
|
+
];
|
|
59
|
+
let detectScript = '';
|
|
60
|
+
for (const p of detectPaths) {
|
|
61
|
+
try { detectScript = fs.readFileSync(p, 'utf-8'); break; } catch { /* try next */ }
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
// Browser script parts: DO NOT cache. Return paths so the /live.js handler
|
|
65
|
+
// can re-read every part on each request. Editing browser code during
|
|
66
|
+
// iteration should land on the next tab reload, not require a server restart.
|
|
67
|
+
const liveScriptParts = resolveLiveBrowserScriptParts(__dirname);
|
|
68
|
+
try {
|
|
69
|
+
assertLiveBrowserScriptParts(liveScriptParts);
|
|
70
|
+
} catch (err) {
|
|
71
|
+
process.stderr.write(`Error: ${err.message}\n`);
|
|
72
|
+
process.exit(1);
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
return { detectScript, liveScriptParts };
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
// HTTP request handler
|
|
79
|
+
// ---------------------------------------------------------------------------
|
|
80
|
+
|
|
81
|
+
function createRequestHandler({ detectScript, liveScriptParts }) {
|
|
82
|
+
return (req, res) => {
|
|
83
|
+
const url = new URL(req.url, `http://localhost:${state.port}`);
|
|
84
|
+
res.setHeader('Access-Control-Allow-Origin', '*');
|
|
85
|
+
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS');
|
|
86
|
+
res.setHeader('Access-Control-Allow-Headers', 'Content-Type');
|
|
87
|
+
if (req.method === 'OPTIONS') { res.writeHead(204); res.end(); return; }
|
|
88
|
+
|
|
89
|
+
const p = url.pathname;
|
|
90
|
+
|
|
91
|
+
// --- Scripts ---
|
|
92
|
+
if (p === '/live.js') {
|
|
93
|
+
// This response embeds the shared bearer credential (below) — unlike
|
|
94
|
+
// /detect.js and the vendored scripts, it must be gated the same way
|
|
95
|
+
// every OTHER protected route already is. Without this, requesting this
|
|
96
|
+
// one route defeats every other route's check: whoever fetches it walks
|
|
97
|
+
// away with the value that's supposed to distinguish the legitimate
|
|
98
|
+
// preview tab from any other page. See requireAuthQueryCred() below —
|
|
99
|
+
// callers must supply the credential the running server printed at
|
|
100
|
+
// startup (also mirrored into the live-server info file for tooling).
|
|
101
|
+
if (!requireAuthQueryCred(url, res)) return;
|
|
102
|
+
// Re-read from disk each request so edits to live-browser.js land on
|
|
103
|
+
// the next tab reload. No-store headers prevent browser caching across
|
|
104
|
+
// sessions — during iteration, a cached old script silently breaks
|
|
105
|
+
// every subsequent session.
|
|
106
|
+
let parts;
|
|
107
|
+
try {
|
|
108
|
+
parts = readLiveBrowserScriptParts(liveScriptParts);
|
|
109
|
+
} catch (err) {
|
|
110
|
+
res.writeHead(500, { 'Content-Type': 'text/plain' });
|
|
111
|
+
res.end(`Error reading live browser scripts: ${err.message}`);
|
|
112
|
+
return;
|
|
113
|
+
}
|
|
114
|
+
const body = assembleLiveBrowserScript({
|
|
115
|
+
token: state.token,
|
|
116
|
+
port: state.port,
|
|
117
|
+
vocabulary: LIVE_COMMANDS,
|
|
118
|
+
commandPrefix: MONODESIGN_COMMAND_PREFIX,
|
|
119
|
+
parts,
|
|
120
|
+
});
|
|
121
|
+
res.writeHead(200, {
|
|
122
|
+
'Content-Type': 'application/javascript',
|
|
123
|
+
'Cache-Control': 'no-store, no-cache, must-revalidate, max-age=0',
|
|
124
|
+
'Pragma': 'no-cache',
|
|
125
|
+
});
|
|
126
|
+
res.end(body);
|
|
127
|
+
return;
|
|
128
|
+
}
|
|
129
|
+
if (p === '/detect.js' || p === '/') {
|
|
130
|
+
if (!detectScript) { res.writeHead(404); res.end('Not available'); return; }
|
|
131
|
+
res.writeHead(200, { 'Content-Type': 'application/javascript' });
|
|
132
|
+
res.end(detectScript);
|
|
133
|
+
return;
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
// --- Vendored modern-screenshot (UMD build) ---
|
|
137
|
+
// Lazy-loaded by live.js when the user clicks Go; exposes
|
|
138
|
+
// window.modernScreenshot.domToBlob(...) for capture.
|
|
139
|
+
if (p === '/modern-screenshot.js') {
|
|
140
|
+
const vendorPath = path.join(__dirname, 'modern-screenshot.umd.js');
|
|
141
|
+
try {
|
|
142
|
+
res.writeHead(200, {
|
|
143
|
+
'Content-Type': 'application/javascript',
|
|
144
|
+
'Cache-Control': 'public, max-age=31536000, immutable',
|
|
145
|
+
});
|
|
146
|
+
res.end(fs.readFileSync(vendorPath));
|
|
147
|
+
} catch {
|
|
148
|
+
res.writeHead(404); res.end('Vendor script not found');
|
|
149
|
+
}
|
|
150
|
+
return;
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
// --- Annotation upload (browser → server, raw PNG body) ---
|
|
154
|
+
// Client generates the eventId, POSTs the PNG, then POSTs the generate
|
|
155
|
+
// event with screenshotPath already set. Keeps bytes out of the SSE/poll
|
|
156
|
+
// bridge and preserves the "one shot from the user's POV" UX.
|
|
157
|
+
if (p === '/annotation' && req.method === 'POST') {
|
|
158
|
+
const token = url.searchParams.get('token');
|
|
159
|
+
if (token !== state.token) { res.writeHead(401); res.end('Unauthorized'); return; }
|
|
160
|
+
const eventId = url.searchParams.get('eventId');
|
|
161
|
+
if (!eventId || !/^[A-Za-z0-9_-]{1,64}$/.test(eventId)) {
|
|
162
|
+
res.writeHead(400, { 'Content-Type': 'application/json' });
|
|
163
|
+
res.end(JSON.stringify({ error: 'Invalid eventId' }));
|
|
164
|
+
return;
|
|
165
|
+
}
|
|
166
|
+
if ((req.headers['content-type'] || '').toLowerCase() !== 'image/png') {
|
|
167
|
+
res.writeHead(415, { 'Content-Type': 'application/json' });
|
|
168
|
+
res.end(JSON.stringify({ error: 'Content-Type must be image/png' }));
|
|
169
|
+
return;
|
|
170
|
+
}
|
|
171
|
+
if (!state.sessionDir) {
|
|
172
|
+
res.writeHead(500, { 'Content-Type': 'application/json' });
|
|
173
|
+
res.end(JSON.stringify({ error: 'Session dir unavailable' }));
|
|
174
|
+
return;
|
|
175
|
+
}
|
|
176
|
+
const chunks = [];
|
|
177
|
+
let total = 0;
|
|
178
|
+
let aborted = false;
|
|
179
|
+
req.on('data', (c) => {
|
|
180
|
+
if (aborted) return;
|
|
181
|
+
total += c.length;
|
|
182
|
+
if (total > MAX_ANNOTATION_BYTES) {
|
|
183
|
+
aborted = true;
|
|
184
|
+
res.writeHead(413, { 'Content-Type': 'application/json' });
|
|
185
|
+
res.end(JSON.stringify({ error: 'Payload too large' }));
|
|
186
|
+
req.destroy();
|
|
187
|
+
return;
|
|
188
|
+
}
|
|
189
|
+
chunks.push(c);
|
|
190
|
+
});
|
|
191
|
+
req.on('end', () => {
|
|
192
|
+
if (aborted) return;
|
|
193
|
+
const absPath = path.join(state.sessionDir, `${eventId}.png`);
|
|
194
|
+
try {
|
|
195
|
+
fs.writeFileSync(absPath, Buffer.concat(chunks));
|
|
196
|
+
} catch (err) {
|
|
197
|
+
res.writeHead(500, { 'Content-Type': 'application/json' });
|
|
198
|
+
res.end(JSON.stringify({ error: `Write failed: ${err.message}` }));
|
|
199
|
+
return;
|
|
200
|
+
}
|
|
201
|
+
res.writeHead(200, { 'Content-Type': 'application/json' });
|
|
202
|
+
res.end(JSON.stringify({ ok: true, path: absPath }));
|
|
203
|
+
});
|
|
204
|
+
req.on('error', () => {
|
|
205
|
+
if (!aborted) {
|
|
206
|
+
res.writeHead(500, { 'Content-Type': 'application/json' });
|
|
207
|
+
res.end(JSON.stringify({ error: 'Upload failed' }));
|
|
208
|
+
}
|
|
209
|
+
});
|
|
210
|
+
return;
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
// --- Health ---
|
|
214
|
+
if (p === '/status') {
|
|
215
|
+
const token = url.searchParams.get('token');
|
|
216
|
+
if (token !== state.token) { res.writeHead(401, { 'Content-Type': 'application/json' }); res.end(JSON.stringify({ error: 'Unauthorized' })); return; }
|
|
217
|
+
const sessions = activeSessionSummaries();
|
|
218
|
+
res.writeHead(200, { 'Content-Type': 'application/json' });
|
|
219
|
+
res.end(JSON.stringify({
|
|
220
|
+
status: 'ok',
|
|
221
|
+
port: state.port,
|
|
222
|
+
connectedClients: state.sseClients.size,
|
|
223
|
+
pendingEvents: state.pendingEvents.map((entry) => summarizePendingEventForStatus(entry)),
|
|
224
|
+
agentPolling: agentPollingConnected(),
|
|
225
|
+
activeSessions: sessions,
|
|
226
|
+
manualEdits: getManualEditStatus(),
|
|
227
|
+
}));
|
|
228
|
+
return;
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
if (p === '/health') {
|
|
232
|
+
res.writeHead(200, { 'Content-Type': 'application/json' });
|
|
233
|
+
res.end(JSON.stringify({
|
|
234
|
+
status: 'ok', port: state.port, mode: 'variant',
|
|
235
|
+
hasProjectContext: hasProjectContext(),
|
|
236
|
+
connectedClients: state.sseClients.size,
|
|
237
|
+
}));
|
|
238
|
+
return;
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
// --- Design system (unified v2 response) + raw ---
|
|
242
|
+
// /design-system.json returns both parsed DESIGN.md and .monodesign/design.json
|
|
243
|
+
// sidecar when present. Panel merges them:
|
|
244
|
+
// { present, parsed, sidecar, hasMd, hasSidecar,
|
|
245
|
+
// mdNewerThanJson, parseError?, sidecarError? }
|
|
246
|
+
// - parsed: output of parseDesignMd (frontmatter
|
|
247
|
+
// + six canonical sections) when DESIGN.md exists.
|
|
248
|
+
// - sidecar: .monodesign/design.json contents when present.
|
|
249
|
+
// Expected shape: schemaVersion 2, carrying
|
|
250
|
+
// extensions + components + narrative.
|
|
251
|
+
// /design-system/raw returns DESIGN.md markdown verbatim
|
|
252
|
+
if (p === '/design-system.json' || p === '/design-system/raw') {
|
|
253
|
+
const token = url.searchParams.get('token');
|
|
254
|
+
if (token !== state.token) { res.writeHead(401); res.end('Unauthorized'); return; }
|
|
255
|
+
|
|
256
|
+
const mdPath = DESIGN_MD_PATH;
|
|
257
|
+
const jsonPath = resolveDesignSidecarPath(process.cwd(), PROJECT_CONTEXT.designContextDir || CONTEXT_DIR) || getDesignSidecarPath(process.cwd());
|
|
258
|
+
const mdStat = statOrNull(mdPath);
|
|
259
|
+
const jsonStat = statOrNull(jsonPath);
|
|
260
|
+
|
|
261
|
+
if (p === '/design-system/raw') {
|
|
262
|
+
if (!mdStat) { res.writeHead(404); res.end('Not found'); return; }
|
|
263
|
+
res.writeHead(200, { 'Content-Type': 'text/markdown; charset=utf-8' });
|
|
264
|
+
res.end(fs.readFileSync(mdPath, 'utf-8'));
|
|
265
|
+
return;
|
|
266
|
+
}
|
|
267
|
+
|
|
268
|
+
if (!mdStat && !jsonStat) {
|
|
269
|
+
res.writeHead(404, { 'Content-Type': 'application/json' });
|
|
270
|
+
res.end(JSON.stringify({ present: false }));
|
|
271
|
+
return;
|
|
272
|
+
}
|
|
273
|
+
|
|
274
|
+
const response = {
|
|
275
|
+
present: true,
|
|
276
|
+
hasMd: !!mdStat,
|
|
277
|
+
hasSidecar: !!jsonStat,
|
|
278
|
+
mdNewerThanJson: !!(mdStat && jsonStat && mdStat.mtimeMs > jsonStat.mtimeMs + 1000),
|
|
279
|
+
};
|
|
280
|
+
|
|
281
|
+
if (mdStat) {
|
|
282
|
+
try {
|
|
283
|
+
response.parsed = parseDesignMd(fs.readFileSync(mdPath, 'utf-8'));
|
|
284
|
+
} catch (err) {
|
|
285
|
+
response.parseError = err.message;
|
|
286
|
+
}
|
|
287
|
+
}
|
|
288
|
+
|
|
289
|
+
if (jsonStat) {
|
|
290
|
+
try {
|
|
291
|
+
response.sidecar = JSON.parse(fs.readFileSync(jsonPath, 'utf-8'));
|
|
292
|
+
} catch (err) {
|
|
293
|
+
response.sidecarError = `Failed to parse .monodesign/design.json: ${err.message}`;
|
|
294
|
+
}
|
|
295
|
+
}
|
|
296
|
+
|
|
297
|
+
res.writeHead(200, { 'Content-Type': 'application/json' });
|
|
298
|
+
res.end(JSON.stringify(response));
|
|
299
|
+
return;
|
|
300
|
+
}
|
|
301
|
+
|
|
302
|
+
// --- Source file (no-HMR fallback) ---
|
|
303
|
+
if (p === '/source') {
|
|
304
|
+
const token = url.searchParams.get('token');
|
|
305
|
+
if (token !== state.token) { res.writeHead(401); res.end('Unauthorized'); return; }
|
|
306
|
+
const filePath = url.searchParams.get('path');
|
|
307
|
+
if (!filePath || filePath.includes('..')) { res.writeHead(400); res.end('Bad path'); return; }
|
|
308
|
+
// Resolve symlinks on BOTH sides before comparing: a lexical prefix check
|
|
309
|
+
// (path.resolve + startsWith) can't tell a symlink that lexically resolves
|
|
310
|
+
// inside cwd from one that physically points outside it, and startsWith on
|
|
311
|
+
// its own also has no path-boundary — "/proj-evil" lexically "starts with"
|
|
312
|
+
// "/proj". realpath + path.relative closes both gaps (the same pattern
|
|
313
|
+
// already used correctly elsewhere in this package).
|
|
314
|
+
let root, absPath;
|
|
315
|
+
try {
|
|
316
|
+
root = fs.realpathSync(process.cwd());
|
|
317
|
+
absPath = fs.realpathSync(path.resolve(process.cwd(), filePath));
|
|
318
|
+
} catch { res.writeHead(404); res.end('File not found'); return; }
|
|
319
|
+
const rel = path.relative(root, absPath);
|
|
320
|
+
if (rel.startsWith('..') || path.isAbsolute(rel)) { res.writeHead(403); res.end('Forbidden'); return; }
|
|
321
|
+
let content;
|
|
322
|
+
try { content = fs.readFileSync(absPath, 'utf-8'); }
|
|
323
|
+
catch { res.writeHead(404); res.end('File not found'); return; }
|
|
324
|
+
res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' });
|
|
325
|
+
res.end(content);
|
|
326
|
+
return;
|
|
327
|
+
}
|
|
328
|
+
|
|
329
|
+
// --- SSE: server→browser push (replaces WebSocket) ---
|
|
330
|
+
if (p === '/events' && req.method === 'GET') {
|
|
331
|
+
const token = url.searchParams.get('token');
|
|
332
|
+
if (token !== state.token) { res.writeHead(401); res.end('Unauthorized'); return; }
|
|
333
|
+
clearTimeout(state.exitTimer);
|
|
334
|
+
state.exitTimer = null;
|
|
335
|
+
cancelQueuedAnonymousExitEvents();
|
|
336
|
+
res.writeHead(200, {
|
|
337
|
+
'Content-Type': 'text/event-stream',
|
|
338
|
+
'Cache-Control': 'no-cache',
|
|
339
|
+
'Connection': 'keep-alive',
|
|
340
|
+
});
|
|
341
|
+
res.write(`data: ${JSON.stringify({
|
|
342
|
+
type: 'connected',
|
|
343
|
+
hasProjectContext: hasProjectContext(),
|
|
344
|
+
agentPolling: agentPollingConnected(),
|
|
345
|
+
activeSessions: activeSessionSummaries(),
|
|
346
|
+
})}\n\n`);
|
|
347
|
+
|
|
348
|
+
state.sseClients.add(res);
|
|
349
|
+
|
|
350
|
+
// Keepalive: SSE comment every 30s prevents silent connection drops.
|
|
351
|
+
const heartbeat = setInterval(() => {
|
|
352
|
+
try { res.write(': keepalive\n\n'); } catch { clearInterval(heartbeat); }
|
|
353
|
+
}, SSE_HEARTBEAT_INTERVAL);
|
|
354
|
+
|
|
355
|
+
req.on('close', () => {
|
|
356
|
+
clearInterval(heartbeat);
|
|
357
|
+
state.sseClients.delete(res);
|
|
358
|
+
if (state.sseClients.size === 0) {
|
|
359
|
+
clearTimeout(state.exitTimer);
|
|
360
|
+
state.exitTimer = setTimeout(() => {
|
|
361
|
+
if (state.sseClients.size === 0) enqueueEvent({ type: 'exit' });
|
|
362
|
+
}, 8000);
|
|
363
|
+
}
|
|
364
|
+
});
|
|
365
|
+
return;
|
|
366
|
+
}
|
|
367
|
+
|
|
368
|
+
if (manualEditRoutes(req, res, url)) return;
|
|
369
|
+
|
|
370
|
+
// --- Browser→server events (replaces WebSocket messages) ---
|
|
371
|
+
if (p === '/events' && req.method === 'POST') {
|
|
372
|
+
let body = '';
|
|
373
|
+
req.on('data', (c) => { body += c; });
|
|
374
|
+
req.on('end', () => {
|
|
375
|
+
let msg;
|
|
376
|
+
try { msg = JSON.parse(body); } catch {
|
|
377
|
+
res.writeHead(400, { 'Content-Type': 'application/json' });
|
|
378
|
+
res.end(JSON.stringify({ error: 'Invalid JSON' }));
|
|
379
|
+
return;
|
|
380
|
+
}
|
|
381
|
+
if (msg.token !== state.token) {
|
|
382
|
+
res.writeHead(401, { 'Content-Type': 'application/json' });
|
|
383
|
+
res.end(JSON.stringify({ error: 'Unauthorized' }));
|
|
384
|
+
return;
|
|
385
|
+
}
|
|
386
|
+
// Defense in depth: manual copy edits must use the staged stash/apply
|
|
387
|
+
// endpoints. The direct Save event path is disabled in the browser.
|
|
388
|
+
if (msg.type === 'manual_edits') {
|
|
389
|
+
res.writeHead(400, { 'Content-Type': 'application/json' });
|
|
390
|
+
res.end(JSON.stringify({ error: 'manual_edits must POST to /manual-edit-stash, not /events' }));
|
|
391
|
+
return;
|
|
392
|
+
}
|
|
393
|
+
if (msg.type === 'manual_edit_apply') {
|
|
394
|
+
res.writeHead(400, { 'Content-Type': 'application/json' });
|
|
395
|
+
res.end(JSON.stringify({ error: 'manual_edit_apply is disabled; use /manual-edit-stash then /manual-edit-commit' }));
|
|
396
|
+
return;
|
|
397
|
+
}
|
|
398
|
+
const error = validateEvent(msg);
|
|
399
|
+
if (error) {
|
|
400
|
+
res.writeHead(400, { 'Content-Type': 'application/json' });
|
|
401
|
+
res.end(JSON.stringify({ error }));
|
|
402
|
+
return;
|
|
403
|
+
}
|
|
404
|
+
if (state.sessionStore && msg.id) {
|
|
405
|
+
try {
|
|
406
|
+
state.sessionStore.appendEvent(msg);
|
|
407
|
+
} catch (err) {
|
|
408
|
+
res.writeHead(500, { 'Content-Type': 'application/json' });
|
|
409
|
+
res.end(JSON.stringify({ error: 'session_store_append_failed', message: err.message }));
|
|
410
|
+
return;
|
|
411
|
+
}
|
|
412
|
+
}
|
|
413
|
+
if (msg.type === 'exit') {
|
|
414
|
+
cleanupSvelteComponentSessionsBeforeExit();
|
|
415
|
+
}
|
|
416
|
+
if (msg.type !== 'checkpoint') {
|
|
417
|
+
enqueueEvent(msg);
|
|
418
|
+
}
|
|
419
|
+
res.writeHead(200, { 'Content-Type': 'application/json' });
|
|
420
|
+
res.end(JSON.stringify({ ok: true }));
|
|
421
|
+
});
|
|
422
|
+
return;
|
|
423
|
+
}
|
|
424
|
+
|
|
425
|
+
// --- Stop ---
|
|
426
|
+
if (p === '/stop') {
|
|
427
|
+
const token = url.searchParams.get('token');
|
|
428
|
+
if (token !== state.token) { res.writeHead(401); res.end('Unauthorized'); return; }
|
|
429
|
+
res.writeHead(200, { 'Content-Type': 'text/plain' });
|
|
430
|
+
res.end('stopping');
|
|
431
|
+
shutdown();
|
|
432
|
+
return;
|
|
433
|
+
}
|
|
434
|
+
|
|
435
|
+
// --- Agent poll ---
|
|
436
|
+
if (p === '/poll' && req.method === 'GET') {
|
|
437
|
+
handlePollGet(req, res, url);
|
|
438
|
+
return;
|
|
439
|
+
}
|
|
440
|
+
if (p === '/poll' && req.method === 'POST') {
|
|
441
|
+
handlePollPost(req, res);
|
|
442
|
+
return;
|
|
443
|
+
}
|
|
444
|
+
|
|
445
|
+
res.writeHead(404); res.end('Not found');
|
|
446
|
+
};
|
|
447
|
+
}
|
|
448
|
+
|
|
449
|
+
export { loadBrowserScripts, createRequestHandler };
|