@monoes/monodesign 1.2.20 → 1.2.23

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (95) hide show
  1. package/README.md +2 -2
  2. package/cli/engine/cli/main.mjs +21 -1
  3. package/cli/engine/design-system-checks.mjs +381 -0
  4. package/cli/engine/design-system-parse.mjs +433 -0
  5. package/cli/engine/design-system.mjs +20 -736
  6. package/cli/engine/detect-antipatterns-browser.js +28 -5
  7. package/cli/engine/detect-antipatterns.mjs +1 -0
  8. package/cli/engine/engines/regex/detect-text-matchers.mjs +371 -0
  9. package/cli/engine/engines/regex/detect-text-run.mjs +186 -0
  10. package/cli/engine/engines/regex/detect-text.mjs +11 -523
  11. package/cli/engine/engines/static-html/css-cascade-color.mjs +219 -0
  12. package/cli/engine/engines/static-html/css-cascade-static-data.mjs +138 -0
  13. package/cli/engine/engines/static-html/css-cascade-static-dom.mjs +132 -0
  14. package/cli/engine/engines/static-html/css-cascade-static-parse.mjs +393 -0
  15. package/cli/engine/engines/static-html/css-cascade.mjs +24 -837
  16. package/cli/engine/engines/static-html/detect-html.mjs +6 -1
  17. package/cli/engine/findings-group.mjs +94 -0
  18. package/cli/engine/fix/index.mjs +1 -26
  19. package/cli/engine/fix/unified-diff.mjs +107 -0
  20. package/cli/engine/rules/checks-background.mjs +17 -3
  21. package/cli/engine/rules/checks-element.mjs +2 -0
  22. package/cli/engine/rules/checks-pure.mjs +9 -2
  23. package/cli/lib/monodesign-config-consent.mjs +93 -0
  24. package/cli/lib/monodesign-config-core.mjs +37 -0
  25. package/cli/lib/monodesign-config-detection.mjs +133 -0
  26. package/cli/lib/monodesign-config-filter.mjs +198 -0
  27. package/cli/lib/monodesign-config-ignore-value.mjs +212 -0
  28. package/cli/lib/monodesign-config.mjs +21 -623
  29. package/package.json +2 -2
  30. package/skill/scripts/context-fields.mjs +65 -0
  31. package/skill/scripts/context-resolve.mjs +425 -0
  32. package/skill/scripts/context-update.mjs +151 -0
  33. package/skill/scripts/context-utils.mjs +68 -0
  34. package/skill/scripts/context-workspace.mjs +245 -0
  35. package/skill/scripts/context.mjs +17 -891
  36. package/skill/scripts/hook-admin-config.mjs +152 -0
  37. package/skill/scripts/hook-admin-ignore.mjs +131 -0
  38. package/skill/scripts/hook-admin-manifest.mjs +292 -0
  39. package/skill/scripts/hook-admin.mjs +8 -541
  40. package/skill/scripts/hook-lib-cache.mjs +145 -0
  41. package/skill/scripts/hook-lib-config.mjs +292 -0
  42. package/skill/scripts/hook-lib-detector.mjs +72 -0
  43. package/skill/scripts/hook-lib-events.mjs +182 -0
  44. package/skill/scripts/hook-lib-findings.mjs +201 -0
  45. package/skill/scripts/hook-lib-ignore.mjs +205 -0
  46. package/skill/scripts/hook-lib-render.mjs +273 -0
  47. package/skill/scripts/hook-lib-run.mjs +281 -0
  48. package/skill/scripts/hook-lib-scan-targets.mjs +128 -0
  49. package/skill/scripts/hook-lib.mjs +71 -1747
  50. package/skill/scripts/lib/design-parser-colors.mjs +182 -0
  51. package/skill/scripts/lib/design-parser-extract.mjs +333 -0
  52. package/skill/scripts/lib/design-parser-sections.mjs +214 -0
  53. package/skill/scripts/lib/design-parser-yaml.mjs +135 -0
  54. package/skill/scripts/lib/design-parser.mjs +10 -783
  55. package/skill/scripts/live/manual-apply-chunk.mjs +151 -0
  56. package/skill/scripts/live/manual-apply-compact.mjs +122 -0
  57. package/skill/scripts/live/manual-apply-evidence.mjs +115 -0
  58. package/skill/scripts/live/manual-apply-log.mjs +179 -0
  59. package/skill/scripts/live/manual-apply-transaction.mjs +122 -0
  60. package/skill/scripts/live/manual-apply.mjs +65 -640
  61. package/skill/scripts/live/svelte-component-accept.mjs +248 -0
  62. package/skill/scripts/live/svelte-component-css.mjs +230 -0
  63. package/skill/scripts/live/svelte-component-markup.mjs +104 -0
  64. package/skill/scripts/live/svelte-component-scaffold.mjs +118 -0
  65. package/skill/scripts/live/svelte-component-session.mjs +158 -0
  66. package/skill/scripts/live/svelte-component.mjs +32 -792
  67. package/skill/scripts/live-accept-mutate.mjs +152 -0
  68. package/skill/scripts/live-accept-parse.mjs +370 -0
  69. package/skill/scripts/live-accept-scrub.mjs +59 -0
  70. package/skill/scripts/live-accept-search.mjs +58 -0
  71. package/skill/scripts/live-accept.mjs +15 -631
  72. package/skill/scripts/live-commit-manual-edits-paths.mjs +27 -0
  73. package/skill/scripts/live-commit-manual-edits-repair.mjs +166 -0
  74. package/skill/scripts/live-commit-manual-edits-rollback.mjs +231 -0
  75. package/skill/scripts/live-commit-manual-edits-utils.mjs +167 -0
  76. package/skill/scripts/live-commit-manual-edits-verify.mjs +356 -0
  77. package/skill/scripts/live-commit-manual-edits.mjs +24 -881
  78. package/skill/scripts/live-copy-edit-agent.mjs +16 -551
  79. package/skill/scripts/live-copy-edit-compact.mjs +137 -0
  80. package/skill/scripts/live-copy-edit-post-apply.mjs +175 -0
  81. package/skill/scripts/live-copy-edit-runners.mjs +297 -0
  82. package/skill/scripts/live-inject-csp.mjs +132 -0
  83. package/skill/scripts/live-inject-files.mjs +229 -0
  84. package/skill/scripts/live-inject-tag.mjs +114 -0
  85. package/skill/scripts/live-inject.mjs +13 -440
  86. package/skill/scripts/live-server-poll.mjs +232 -0
  87. package/skill/scripts/live-server-routes.mjs +449 -0
  88. package/skill/scripts/live-server-state.mjs +361 -0
  89. package/skill/scripts/live-server.mjs +10 -946
  90. package/skill/scripts/live-wrap-css.mjs +132 -0
  91. package/skill/scripts/live-wrap-manual-edit.mjs +153 -0
  92. package/skill/scripts/live-wrap-search.mjs +247 -0
  93. package/skill/scripts/live-wrap.mjs +21 -484
  94. package/skill/scripts/palette-seeds.mjs +401 -0
  95. package/skill/scripts/palette.mjs +1 -395
@@ -24,45 +24,16 @@ import {
24
24
  } from './live/sveltekit-adapter.mjs';
25
25
 
26
26
  const __dirname = path.dirname(fileURLToPath(import.meta.url));
27
- const CONFIG_PATH = resolveLiveConfigPath({ cwd: process.cwd(), scriptsDir: __dirname });
28
- const MARKER_OPEN_TEXT = 'monodesign-live-start';
29
- const MARKER_CLOSE_TEXT = 'monodesign-live-end';
30
- // Query param name live-server.mjs checks on every protected route.
31
- const AUTH_QUERY_KEY = 'token';
32
- const IGNORE_MARKER_OPEN = '# monodesign-live-ignore-start';
33
- const IGNORE_MARKER_CLOSE = '# monodesign-live-ignore-end';
34
-
35
- export const LIVE_IGNORE_PATTERNS = Object.freeze([
36
- '.monodesign/hook.cache.json',
37
- '.monodesign/hook.pending.json',
38
- '.monodesign/config.local.json',
39
- '.monodesign/live/server.json',
40
- '.monodesign/live/sessions/',
41
- '.monodesign/live/previews/',
42
- '.monodesign/live/annotations/',
43
- '.monodesign/live/cache/',
44
- '.monodesign/live/manual-edit-apply-transaction.json',
45
- '.monodesign/live/manual-edit-events.jsonl',
46
- '.monodesign/live/manual-edit-evidence/',
47
- '.monodesign/live/pending-manual-edits.json',
48
- '.monodesign/live/deferred-svelte-component-accepts.json',
49
- '.monodesign-live.json',
50
- '.monodesign-live/',
51
- 'node_modules/.monodesign-live/',
52
- 'src/lib/monodesign/MonodesignLiveRoot.svelte',
53
- 'src/lib/monodesign/__runtime.js',
54
- 'src/lib/monodesign/[0-9a-f]*/',
55
- ]);
27
+ import {
28
+ ensureLiveGitIgnores,
29
+ resolveFiles,
30
+ validateConfig,
31
+ LIVE_IGNORE_PATTERNS,
32
+ } from './live-inject-files.mjs';
33
+ import { insertTag, removeTag, buildTagBlock } from './live-inject-tag.mjs';
34
+ import { patchCspMeta, revertCspMeta } from './live-inject-csp.mjs';
56
35
 
57
- /**
58
- * Hard-excluded directory patterns. These are NEVER user-facing pages and
59
- * matching them would silently inject tracking scripts into third-party
60
- * code. The user cannot turn these off via config — they are the floor.
61
- */
62
- const HARD_EXCLUDES = [
63
- '**/node_modules/**',
64
- '**/.git/**',
65
- ];
36
+ const CONFIG_PATH = resolveLiveConfigPath({ cwd: process.cwd(), scriptsDir: __dirname });
66
37
 
67
38
  export async function injectCli() {
68
39
  const args = process.argv.slice(2);
@@ -186,411 +157,13 @@ Output (JSON):
186
157
  if (!anyInserted) process.exit(1);
187
158
  }
188
159
 
189
- export function ensureLiveGitIgnores(cwd = process.cwd()) {
190
- const target = resolveIgnoreTarget(cwd);
191
- const existing = fs.existsSync(target.path) ? fs.readFileSync(target.path, 'utf-8') : '';
192
- const block = [
193
- IGNORE_MARKER_OPEN,
194
- ...LIVE_IGNORE_PATTERNS,
195
- IGNORE_MARKER_CLOSE,
196
- ].join('\n');
197
- const markerRe = new RegExp(`${escapeRegExp(IGNORE_MARKER_OPEN)}[\\s\\S]*?${escapeRegExp(IGNORE_MARKER_CLOSE)}`);
198
-
199
- let updated;
200
- if (markerRe.test(existing)) {
201
- updated = existing.replace(markerRe, block);
202
- } else {
203
- const prefix = existing.length === 0 ? '' : existing.endsWith('\n') ? existing : `${existing}\n`;
204
- updated = `${prefix}${prefix.endsWith('\n\n') || prefix === '' ? '' : '\n'}${block}\n`;
205
- }
206
-
207
- if (updated !== existing) {
208
- fs.mkdirSync(path.dirname(target.path), { recursive: true });
209
- fs.writeFileSync(target.path, updated, 'utf-8');
210
- }
211
-
212
- return {
213
- file: path.relative(cwd, target.path).split(path.sep).join('/'),
214
- mode: target.mode,
215
- changed: updated !== existing,
216
- patterns: [...LIVE_IGNORE_PATTERNS],
217
- };
218
- }
219
-
220
- function resolveIgnoreTarget(cwd) {
221
- const gitExcludePath = resolveGitInfoExcludePath(cwd);
222
- if (gitExcludePath) {
223
- return { path: gitExcludePath, mode: 'git-info-exclude' };
224
- }
225
- return { path: path.join(cwd, '.gitignore'), mode: 'gitignore' };
226
- }
227
-
228
- function resolveGitInfoExcludePath(cwd) {
229
- const dotGit = path.join(cwd, '.git');
230
- if (!fs.existsSync(dotGit)) return null;
231
-
232
- const stat = fs.statSync(dotGit);
233
- if (stat.isDirectory()) return path.join(dotGit, 'info', 'exclude');
234
- if (!stat.isFile()) return null;
235
-
236
- const body = fs.readFileSync(dotGit, 'utf-8').trim();
237
- const match = body.match(/^gitdir:\s*(.+)$/i);
238
- if (!match) return null;
239
- const gitDir = path.isAbsolute(match[1]) ? match[1] : path.resolve(cwd, match[1]);
240
- return path.join(gitDir, 'info', 'exclude');
241
- }
242
-
243
- function escapeRegExp(value) {
244
- return String(value).replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
245
- }
246
-
247
- /**
248
- * Expand config.files (which may contain glob patterns) into a literal list
249
- * of existing file paths relative to rootDir. Literal entries pass through;
250
- * glob patterns are expanded via fs.globSync. HARD_EXCLUDES and config.exclude
251
- * are applied as filters. Duplicates are removed. Order is preserved by
252
- * first appearance.
253
- */
254
- export function resolveFiles(rootDir, config) {
255
- const patterns = config.files;
256
- const userExcludes = Array.isArray(config.exclude) ? config.exclude : [];
257
- const allExcludes = [...HARD_EXCLUDES, ...userExcludes];
258
- const excludeRegexes = allExcludes.map(globToRegex);
259
-
260
- const isExcluded = (relPath) => excludeRegexes.some((re) => re.test(relPath));
261
- const isGlob = (s) => /[*?[]/.test(s);
262
-
263
- const seen = new Set();
264
- const out = [];
265
- for (const pat of patterns) {
266
- if (!isGlob(pat)) {
267
- // Literal path — include even if it doesn't exist yet; the caller
268
- // reports file_not_found per-entry. Exclude list doesn't apply to
269
- // explicit literal entries (user named it on purpose).
270
- if (!seen.has(pat)) {
271
- seen.add(pat);
272
- out.push(pat);
273
- }
274
- continue;
275
- }
276
- let matches;
277
- try {
278
- matches = fs.globSync(pat, { cwd: rootDir, withFileTypes: true });
279
- } catch {
280
- continue;
281
- }
282
- for (const ent of matches) {
283
- if (!ent.isFile?.()) continue;
284
- const abs = path.join(ent.parentPath || ent.path || rootDir, ent.name);
285
- const rel = path.relative(rootDir, abs).split(path.sep).join('/');
286
- if (isExcluded(rel)) continue;
287
- if (seen.has(rel)) continue;
288
- seen.add(rel);
289
- out.push(rel);
290
- }
291
- }
292
- return out;
293
- }
294
-
295
- /**
296
- * Convert a glob pattern to a RegExp. Supports:
297
- * ** → any number of path segments (including zero)
298
- * * → any chars except `/`
299
- * ? → any single char except `/`
300
- * Paths are normalized to forward slashes before matching.
301
- */
302
- function globToRegex(pattern) {
303
- let re = '';
304
- let i = 0;
305
- while (i < pattern.length) {
306
- const c = pattern[i];
307
- if (c === '*') {
308
- if (pattern[i + 1] === '*') {
309
- // ** — any number of segments, including zero. Handle the common
310
- // **/ and /** forms so `a/**/b` matches `a/b` as well as `a/x/y/b`.
311
- if (pattern[i + 2] === '/') {
312
- re += '(?:.*/)?';
313
- i += 3;
314
- } else {
315
- re += '.*';
316
- i += 2;
317
- }
318
- } else {
319
- re += '[^/]*';
320
- i += 1;
321
- }
322
- } else if (c === '?') {
323
- re += '[^/]';
324
- i += 1;
325
- } else if (/[.+^${}()|[\]\\]/.test(c)) {
326
- re += `\\${c}`;
327
- i += 1;
328
- } else {
329
- re += c;
330
- i += 1;
331
- }
332
- }
333
- return new RegExp(`^${re}$`);
334
- }
335
-
336
- // ---------------------------------------------------------------------------
337
- // Core operations
338
- // ---------------------------------------------------------------------------
339
-
340
- function validateConfig(cfg) {
341
- if (!cfg || typeof cfg !== 'object') throw new Error('config.json must be an object');
342
- if (!Array.isArray(cfg.files) || cfg.files.length === 0) {
343
- throw new Error('config.files (non-empty string array) required');
344
- }
345
- if (!cfg.files.every((f) => typeof f === 'string' && f.length > 0)) {
346
- throw new Error('config.files must contain only non-empty strings');
347
- }
348
- if (cfg.exclude !== undefined) {
349
- if (!Array.isArray(cfg.exclude)) {
350
- throw new Error('config.exclude, if present, must be a string array');
351
- }
352
- if (!cfg.exclude.every((f) => typeof f === 'string' && f.length > 0)) {
353
- throw new Error('config.exclude must contain only non-empty strings');
354
- }
355
- }
356
- if (typeof cfg.insertBefore !== 'string' && typeof cfg.insertAfter !== 'string') {
357
- throw new Error('config.insertBefore or config.insertAfter (string) required');
358
- }
359
- if (cfg.commentSyntax !== 'html' && cfg.commentSyntax !== 'jsx') {
360
- throw new Error("config.commentSyntax must be 'html' or 'jsx'");
361
- }
362
- if (cfg.cspChecked !== undefined && typeof cfg.cspChecked !== 'boolean') {
363
- throw new Error("config.cspChecked, if present, must be a boolean");
364
- }
365
- }
366
-
367
- function commentOpen(syntax) { return syntax === 'jsx' ? '{/*' : '<!--'; }
368
- function commentClose(syntax) { return syntax === 'jsx' ? '*/}' : '-->'; }
369
-
370
- function buildTagBlock(syntax, port, authCred, filePath) {
371
- const open = commentOpen(syntax);
372
- const close = commentClose(syntax);
373
- // Astro processes <script> tags by default and rewrites src to its own
374
- // bundled URL. is:inline opts out so the literal external src survives.
375
- const isAstro = typeof filePath === 'string' && filePath.endsWith('.astro');
376
- const scriptAttrs = isAstro ? 'is:inline ' : '';
377
- const authQuery = new URLSearchParams();
378
- authQuery.set(AUTH_QUERY_KEY, authCred);
379
- return (
380
- open + ' ' + MARKER_OPEN_TEXT + ' ' + close + '\n' +
381
- '<script ' + scriptAttrs + 'src="http://localhost:' + port + '/live.js?' + authQuery.toString() + '"></script>\n' +
382
- open + ' ' + MARKER_CLOSE_TEXT + ' ' + close + '\n'
383
- );
384
- }
385
-
386
- function detectLineEnding(content) {
387
- if (content.includes('\r\n')) return '\r\n';
388
- if (content.includes('\r')) return '\r';
389
- return '\n';
390
- }
391
-
392
- function normalizeLineEndings(content, lineEnding) {
393
- return lineEnding === '\n' ? content : content.replace(/\n/g, lineEnding);
394
- }
395
-
396
- function readLineEndingAt(content, index) {
397
- if (content[index] === '\r' && content[index + 1] === '\n') return '\r\n';
398
- if (content[index] === '\n') return '\n';
399
- if (content[index] === '\r') return '\r';
400
- return '';
401
- }
402
-
403
- function insertTag(content, config, port, authCred, filePath) {
404
- const lineEnding = detectLineEnding(content);
405
- const block = normalizeLineEndings(buildTagBlock(config.commentSyntax, port, authCred, filePath), lineEnding);
406
- // insertBefore: match the LAST occurrence. Anchors like `</body>` naturally
407
- // belong at the end, and the same literal can appear earlier in code blocks
408
- // within rendered documentation pages.
409
- if (config.insertBefore) {
410
- const idx = content.lastIndexOf(config.insertBefore);
411
- if (idx === -1) return content;
412
- return content.slice(0, idx) + block + content.slice(idx);
413
- }
414
- // insertAfter: match the FIRST occurrence — typical anchors like `<head>` or
415
- // `<body>` open near the top of the document.
416
- const idx = content.indexOf(config.insertAfter);
417
- if (idx === -1) return content;
418
- const after = idx + config.insertAfter.length;
419
- // Preserve an existing trailing newline if the anchor already has one.
420
- // Slice the remainder from the original anchor offset, not prefix.length:
421
- // in the no-newline case prefix is one char longer than the anchor (the
422
- // appended '\n'), so slicing by prefix.length would drop the first real
423
- // character after the anchor (#227).
424
- const existingNewline = readLineEndingAt(content, after);
425
- const prefix = content.slice(0, after) + (existingNewline || lineEnding);
426
- const rest = content.slice(after + existingNewline.length);
427
- return prefix + block + rest;
428
- }
429
-
430
- /**
431
- * Remove the live script block. Matches either HTML or JSX comment markers
432
- * regardless of config (so stale tags from a wrong config can still be cleaned).
433
- *
434
- * Indent-preserving: captures any whitespace immediately preceding the opener
435
- * marker and re-emits it in place of the removed block. `insertTag` inserted
436
- * the block *after* the original line's indent and *before* the anchor (e.g.
437
- * `</body>`), which moved the indent onto the opener line and left the anchor
438
- * unindented. Replacing the whole block (plus its trailing newline) with just
439
- * the captured indent hands the indent back to the anchor that follows.
440
- */
441
- function removeTag(content, _syntax) {
442
- const patterns = [
443
- /([ \t]*)<!--\s*monodesign-live-start\s*-->[\s\S]*?<!--\s*monodesign-live-end\s*-->([ \t]*(?:\r\n|\n|\r|$)?)/,
444
- /([ \t]*)\{\/\*\s*monodesign-live-start\s*\*\/\}[\s\S]*?\{\/\*\s*monodesign-live-end\s*\*\/\}([ \t]*(?:\r\n|\n|\r|$)?)/,
445
- ];
446
- for (const pat of patterns) {
447
- let changed = false;
448
- let next = content;
449
- do {
450
- content = next;
451
- next = content.replace(pat, (_match, leadingIndent, trailing = '') => {
452
- if (/[\r\n]/.test(trailing)) return leadingIndent;
453
- return leadingIndent || trailing || '';
454
- });
455
- if (next !== content) changed = true;
456
- } while (next !== content);
457
- if (changed) return next;
458
- }
459
- return content;
460
- }
461
-
462
- // ---------------------------------------------------------------------------
463
- // Content-Security-Policy meta-tag patcher
464
- //
465
- // When the user's HTML carries `<meta http-equiv="Content-Security-Policy">`,
466
- // the cross-origin load of /live.js (and the SSE/POST connection back to
467
- // localhost:PORT) is blocked unless the CSP explicitly allows that origin.
468
- //
469
- // On insert: append `http://localhost:PORT` to `script-src` and `connect-src`,
470
- // and stash the original `content` value in a `data-monodesign-csp-original`
471
- // attribute (base64) so revert is exact.
472
- //
473
- // On remove: detect the marker attribute, decode it, restore the original
474
- // content value verbatim, drop the marker.
475
- //
476
- // Header-based CSP (Next.js headers, Nuxt routeRules, SvelteKit kit.csp,
477
- // shared helpers) is NOT patched here — those need framework-specific config
478
- // edits and are handled via the existing detect-csp.mjs reference output.
479
- // Only the in-source meta-tag form gets the auto-patch.
480
- // ---------------------------------------------------------------------------
481
-
482
- const CSP_MARKER_ATTR = 'data-monodesign-csp-original';
483
-
484
- function findCspMetaTags(content) {
485
- const out = [];
486
- const tagRe = /<meta\s+([^>]*?)\/?>/gis;
487
- let m;
488
- while ((m = tagRe.exec(content)) !== null) {
489
- const attrs = m[1];
490
- if (!/(http-equiv|httpEquiv)\s*=\s*(['"])Content-Security-Policy\2/i.test(attrs)) continue;
491
- out.push({ start: m.index, end: m.index + m[0].length, full: m[0], attrs });
492
- }
493
- return out;
494
- }
495
-
496
- function getAttr(attrs, name) {
497
- const re = new RegExp(`\\b${name}\\s*=\\s*(['"])([\\s\\S]*?)\\1`, 'i');
498
- const m = attrs.match(re);
499
- return m ? { quote: m[1], value: m[2], full: m[0] } : null;
500
- }
501
-
502
- function appendOriginToDirective(csp, directive, origin) {
503
- const re = new RegExp(`(^|;)(\\s*)(${directive})\\s+([^;]*)`, 'i');
504
- const m = csp.match(re);
505
- if (m) {
506
- const tokens = m[4].trim().split(/\s+/);
507
- if (tokens.includes(origin)) return csp;
508
- return csp.replace(re, `${m[1]}${m[2]}${m[3]} ${[...tokens, origin].join(' ')}`);
509
- }
510
- // Directive missing — add it. Use 'self' + origin so we don't inadvertently
511
- // narrow the policy compared to the default-src fallback (most users with
512
- // an explicit CSP have 'self' there).
513
- return `${csp.trim().replace(/;?\s*$/, '')}; ${directive} 'self' ${origin}`;
514
- }
515
-
516
- export function patchCspMeta(content, port) {
517
- const tags = findCspMetaTags(content);
518
- if (tags.length === 0) return content;
519
- const origin = `http://localhost:${port}`;
520
-
521
- // Walk last-to-first so prior splices don't invalidate later indices.
522
- let result = content;
523
- for (let i = tags.length - 1; i >= 0; i--) {
524
- const tag = tags[i];
525
- const attrs = tag.attrs;
526
- if (getAttr(attrs, CSP_MARKER_ATTR)) continue; // already patched
527
- const contentAttr = getAttr(attrs, 'content');
528
- if (!contentAttr) continue;
529
-
530
- const original = contentAttr.value;
531
- let patched = original;
532
- patched = appendOriginToDirective(patched, 'script-src', origin);
533
- patched = appendOriginToDirective(patched, 'connect-src', origin);
534
- // The shader overlay during 'generating' creates a screenshot via
535
- // URL.createObjectURL, producing a `blob:` URL — img-src 'self' rejects
536
- // those. Add `blob:` so the overlay doesn't throw a CSP violation.
537
- patched = appendOriginToDirective(patched, 'img-src', 'blob:');
538
- if (patched === original) continue;
539
-
540
- const newContentAttr = `content=${contentAttr.quote}${patched}${contentAttr.quote}`;
541
- const marker = `${CSP_MARKER_ATTR}="${Buffer.from(original, 'utf-8').toString('base64')}"`;
542
- // The tagRe captures any whitespace between the last attribute and the
543
- // closing `/>` as part of `attrs`. Naively appending ` ${marker}` after
544
- // a replace would land it BEFORE that trailing space, leaving a double
545
- // space inside attrs and clobbering the space before `/>`. Split off
546
- // the trailing whitespace, splice the marker into the attribute body,
547
- // and re-append the original trailing whitespace so a self-closing
548
- // `<meta … />` round-trips byte-for-byte.
549
- const trailingWs = (attrs.match(/[ \t]*$/) || [''])[0];
550
- const attrsBody = attrs.slice(0, attrs.length - trailingWs.length);
551
- const newAttrs = `${attrsBody.replace(contentAttr.full, newContentAttr)} ${marker}${trailingWs}`;
552
- const newTag = tag.full.replace(attrs, newAttrs);
553
-
554
- result = result.slice(0, tag.start) + newTag + result.slice(tag.end);
555
- }
556
- return result;
557
- }
558
-
559
- export function revertCspMeta(content) {
560
- const tags = findCspMetaTags(content);
561
- if (tags.length === 0) return content;
562
-
563
- let result = content;
564
- for (let i = tags.length - 1; i >= 0; i--) {
565
- const tag = tags[i];
566
- const origAttr = getAttr(tag.attrs, CSP_MARKER_ATTR);
567
- if (!origAttr) continue;
568
- const contentAttr = getAttr(tag.attrs, 'content');
569
- if (!contentAttr) continue;
570
-
571
- let originalValue;
572
- try { originalValue = Buffer.from(origAttr.value, 'base64').toString('utf-8'); }
573
- catch { continue; }
574
-
575
- const newContentAttr = `content=${contentAttr.quote}${originalValue}${contentAttr.quote}`;
576
- let newAttrs = tag.attrs.replace(contentAttr.full, newContentAttr);
577
- // Drop the marker attribute and any single space immediately preceding it.
578
- newAttrs = newAttrs.replace(new RegExp(`\\s*${origAttr.full}`), '');
579
- const newTag = tag.full.replace(tag.attrs, newAttrs);
580
-
581
- result = result.slice(0, tag.start) + newTag + result.slice(tag.end);
582
- }
583
- return result;
584
- }
585
-
586
- // ---------------------------------------------------------------------------
587
- // Auto-execute
588
- // ---------------------------------------------------------------------------
589
-
590
160
  const _running = process.argv[1];
591
161
  if (_running?.endsWith('live-inject.mjs') || _running?.endsWith('live-inject.mjs/')) {
592
162
  injectCli();
593
163
  }
594
164
 
595
165
  export { insertTag, removeTag, validateConfig, buildTagBlock };
596
- // patchCspMeta + revertCspMeta are exported above where they're defined.
166
+ export { LIVE_IGNORE_PATTERNS, ensureLiveGitIgnores, resolveFiles };
167
+ export { patchCspMeta, revertCspMeta };
168
+ // patchCspMeta + revertCspMeta are re-exported from live-inject-csp.mjs,
169
+ // where they're defined.