@monoes/monomindcli 2.15.5 → 2.15.7

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 (226) hide show
  1. package/dist/src/commands/cleanup-plan.d.ts +57 -0
  2. package/dist/src/commands/cleanup-plan.d.ts.map +1 -0
  3. package/dist/src/commands/cleanup-plan.js +379 -0
  4. package/dist/src/commands/cleanup-plan.js.map +1 -0
  5. package/dist/src/commands/cleanup.d.ts.map +1 -1
  6. package/dist/src/commands/cleanup.js +87 -160
  7. package/dist/src/commands/cleanup.js.map +1 -1
  8. package/dist/src/commands/search-universal.d.ts +8 -0
  9. package/dist/src/commands/search-universal.d.ts.map +1 -1
  10. package/dist/src/commands/search-universal.js +14 -0
  11. package/dist/src/commands/search-universal.js.map +1 -1
  12. package/dist/src/index.d.ts.map +1 -1
  13. package/dist/src/index.js +11 -2
  14. package/dist/src/index.js.map +1 -1
  15. package/dist/src/orgrt/completion-gate.d.ts +40 -0
  16. package/dist/src/orgrt/completion-gate.d.ts.map +1 -1
  17. package/dist/src/orgrt/completion-gate.js +90 -9
  18. package/dist/src/orgrt/completion-gate.js.map +1 -1
  19. package/dist/src/orgrt/daemon.d.ts +4 -0
  20. package/dist/src/orgrt/daemon.d.ts.map +1 -1
  21. package/dist/src/orgrt/daemon.js +15 -2
  22. package/dist/src/orgrt/daemon.js.map +1 -1
  23. package/dist/src/orgrt/decisions.d.ts +24 -1
  24. package/dist/src/orgrt/decisions.d.ts.map +1 -1
  25. package/dist/src/orgrt/decisions.js +171 -11
  26. package/dist/src/orgrt/decisions.js.map +1 -1
  27. package/dist/src/orgrt/idle-deadline.d.ts +10 -0
  28. package/dist/src/orgrt/idle-deadline.d.ts.map +1 -1
  29. package/dist/src/orgrt/idle-deadline.js +8 -0
  30. package/dist/src/orgrt/idle-deadline.js.map +1 -1
  31. package/dist/src/orgrt/mailbox.d.ts +7 -0
  32. package/dist/src/orgrt/mailbox.d.ts.map +1 -1
  33. package/dist/src/orgrt/mailbox.js +14 -0
  34. package/dist/src/orgrt/mailbox.js.map +1 -1
  35. package/dist/src/orgrt/review-packet.d.ts +1 -1
  36. package/dist/src/orgrt/review-packet.d.ts.map +1 -1
  37. package/dist/src/orgrt/review-packet.js +2 -1
  38. package/dist/src/orgrt/review-packet.js.map +1 -1
  39. package/dist/src/orgrt/role-sandbox.d.ts +1 -0
  40. package/dist/src/orgrt/role-sandbox.d.ts.map +1 -1
  41. package/dist/src/orgrt/role-sandbox.js +6 -1
  42. package/dist/src/orgrt/role-sandbox.js.map +1 -1
  43. package/dist/src/orgrt/session.d.ts +3 -0
  44. package/dist/src/orgrt/session.d.ts.map +1 -1
  45. package/dist/src/orgrt/session.js +8 -1
  46. package/dist/src/orgrt/session.js.map +1 -1
  47. package/dist/src/orgrt/task-dag.d.ts +3 -0
  48. package/dist/src/orgrt/task-dag.d.ts.map +1 -1
  49. package/dist/src/orgrt/task-dag.js +7 -0
  50. package/dist/src/orgrt/task-dag.js.map +1 -1
  51. package/dist/src/orgrt/types.d.ts +3 -0
  52. package/dist/src/orgrt/types.d.ts.map +1 -1
  53. package/dist/src/orgrt/types.js +6 -2
  54. package/dist/src/orgrt/types.js.map +1 -1
  55. package/dist/src/update/checker.d.ts +3 -1
  56. package/dist/src/update/checker.d.ts.map +1 -1
  57. package/dist/src/update/checker.js +7 -3
  58. package/dist/src/update/checker.js.map +1 -1
  59. package/dist/src/update/index.d.ts +16 -0
  60. package/dist/src/update/index.d.ts.map +1 -1
  61. package/dist/src/update/index.js +37 -1
  62. package/dist/src/update/index.js.map +1 -1
  63. package/dist/src/update/refresh-worker.d.ts +9 -0
  64. package/dist/src/update/refresh-worker.d.ts.map +1 -0
  65. package/dist/src/update/refresh-worker.js +17 -0
  66. package/dist/src/update/refresh-worker.js.map +1 -0
  67. package/dist/src/utils/resource-governor.d.ts +44 -2
  68. package/dist/src/utils/resource-governor.d.ts.map +1 -1
  69. package/dist/src/utils/resource-governor.js +157 -40
  70. package/dist/src/utils/resource-governor.js.map +1 -1
  71. package/dist/tsconfig.tsbuildinfo +1 -1
  72. package/package.json +4 -4
  73. package/.claude/skills/monodesign/SKILL.md +0 -257
  74. package/.claude/skills/monodesign/adapt.md +0 -53
  75. package/.claude/skills/monodesign/agents/monodesign-asset-producer.md +0 -100
  76. package/.claude/skills/monodesign/agents/monodesign-manual-edit-applier.md +0 -103
  77. package/.claude/skills/monodesign/animate.md +0 -65
  78. package/.claude/skills/monodesign/audit.md +0 -89
  79. package/.claude/skills/monodesign/bolder.md +0 -50
  80. package/.claude/skills/monodesign/clarify.md +0 -64
  81. package/.claude/skills/monodesign/colorize.md +0 -68
  82. package/.claude/skills/monodesign/craft.md +0 -51
  83. package/.claude/skills/monodesign/critique.md +0 -66
  84. package/.claude/skills/monodesign/delight.md +0 -47
  85. package/.claude/skills/monodesign/distill.md +0 -56
  86. package/.claude/skills/monodesign/document.md +0 -83
  87. package/.claude/skills/monodesign/extract.md +0 -74
  88. package/.claude/skills/monodesign/harden.md +0 -65
  89. package/.claude/skills/monodesign/init.md +0 -30
  90. package/.claude/skills/monodesign/layout.md +0 -36
  91. package/.claude/skills/monodesign/live.md +0 -34
  92. package/.claude/skills/monodesign/onboard.md +0 -50
  93. package/.claude/skills/monodesign/optimize.md +0 -64
  94. package/.claude/skills/monodesign/overdrive.md +0 -56
  95. package/.claude/skills/monodesign/polish.md +0 -68
  96. package/.claude/skills/monodesign/quieter.md +0 -57
  97. package/.claude/skills/monodesign/reference/adapt.md +0 -312
  98. package/.claude/skills/monodesign/reference/adapt.native.md +0 -58
  99. package/.claude/skills/monodesign/reference/android.md +0 -40
  100. package/.claude/skills/monodesign/reference/animate.md +0 -203
  101. package/.claude/skills/monodesign/reference/antipatterns-catalog.md +0 -410
  102. package/.claude/skills/monodesign/reference/audit.md +0 -135
  103. package/.claude/skills/monodesign/reference/audit.native.md +0 -139
  104. package/.claude/skills/monodesign/reference/bolder.md +0 -120
  105. package/.claude/skills/monodesign/reference/brand-workflow.md +0 -180
  106. package/.claude/skills/monodesign/reference/brand.md +0 -108
  107. package/.claude/skills/monodesign/reference/clarify.md +0 -288
  108. package/.claude/skills/monodesign/reference/codex.md +0 -105
  109. package/.claude/skills/monodesign/reference/cognitive-load.md +0 -106
  110. package/.claude/skills/monodesign/reference/color-and-contrast.md +0 -105
  111. package/.claude/skills/monodesign/reference/colorize.md +0 -257
  112. package/.claude/skills/monodesign/reference/component-specs.md +0 -260
  113. package/.claude/skills/monodesign/reference/component-states.md +0 -274
  114. package/.claude/skills/monodesign/reference/component-system.md +0 -358
  115. package/.claude/skills/monodesign/reference/copy-formulas.md +0 -160
  116. package/.claude/skills/monodesign/reference/craft.md +0 -123
  117. package/.claude/skills/monodesign/reference/critique.md +0 -780
  118. package/.claude/skills/monodesign/reference/delight.md +0 -302
  119. package/.claude/skills/monodesign/reference/design-principles.md +0 -246
  120. package/.claude/skills/monodesign/reference/distill.md +0 -111
  121. package/.claude/skills/monodesign/reference/document.md +0 -429
  122. package/.claude/skills/monodesign/reference/extract.md +0 -69
  123. package/.claude/skills/monodesign/reference/harden.md +0 -347
  124. package/.claude/skills/monodesign/reference/heuristics-scoring.md +0 -234
  125. package/.claude/skills/monodesign/reference/hooks.md +0 -92
  126. package/.claude/skills/monodesign/reference/image-prompts.md +0 -130
  127. package/.claude/skills/monodesign/reference/init.md +0 -221
  128. package/.claude/skills/monodesign/reference/interaction-design.md +0 -189
  129. package/.claude/skills/monodesign/reference/ios.md +0 -45
  130. package/.claude/skills/monodesign/reference/layout.md +0 -185
  131. package/.claude/skills/monodesign/reference/live.md +0 -710
  132. package/.claude/skills/monodesign/reference/motion-design.md +0 -109
  133. package/.claude/skills/monodesign/reference/onboard.md +0 -234
  134. package/.claude/skills/monodesign/reference/optimize.md +0 -258
  135. package/.claude/skills/monodesign/reference/overdrive.md +0 -130
  136. package/.claude/skills/monodesign/reference/personas.md +0 -179
  137. package/.claude/skills/monodesign/reference/polish.md +0 -241
  138. package/.claude/skills/monodesign/reference/pre-delivery-checklist.md +0 -108
  139. package/.claude/skills/monodesign/reference/product.md +0 -60
  140. package/.claude/skills/monodesign/reference/quieter.md +0 -99
  141. package/.claude/skills/monodesign/reference/responsive-design.md +0 -114
  142. package/.claude/skills/monodesign/reference/shape.md +0 -165
  143. package/.claude/skills/monodesign/reference/spatial-design.md +0 -100
  144. package/.claude/skills/monodesign/reference/teach.md +0 -10
  145. package/.claude/skills/monodesign/reference/token-architecture.md +0 -222
  146. package/.claude/skills/monodesign/reference/typeset.md +0 -301
  147. package/.claude/skills/monodesign/reference/typography.md +0 -159
  148. package/.claude/skills/monodesign/reference/ux-research.md +0 -143
  149. package/.claude/skills/monodesign/reference/ux-rules.md +0 -211
  150. package/.claude/skills/monodesign/reference/ux-writing.md +0 -107
  151. package/.claude/skills/monodesign/scripts/command-metadata.json +0 -94
  152. package/.claude/skills/monodesign/scripts/context-signals.mjs +0 -260
  153. package/.claude/skills/monodesign/scripts/context.mjs +0 -1065
  154. package/.claude/skills/monodesign/scripts/critique-storage.mjs +0 -416
  155. package/.claude/skills/monodesign/scripts/detect-csp.mjs +0 -193
  156. package/.claude/skills/monodesign/scripts/detect.mjs +0 -33
  157. package/.claude/skills/monodesign/scripts/detector/browser/injected/index.mjs +0 -1960
  158. package/.claude/skills/monodesign/scripts/detector/cli/main.mjs +0 -321
  159. package/.claude/skills/monodesign/scripts/detector/design-system.mjs +0 -814
  160. package/.claude/skills/monodesign/scripts/detector/detect-antipatterns-browser.js +0 -5628
  161. package/.claude/skills/monodesign/scripts/detector/detect-antipatterns.mjs +0 -50
  162. package/.claude/skills/monodesign/scripts/detector/engines/browser/detect-url.mjs +0 -259
  163. package/.claude/skills/monodesign/scripts/detector/engines/browser/drivers.mjs +0 -349
  164. package/.claude/skills/monodesign/scripts/detector/engines/regex/detect-text.mjs +0 -636
  165. package/.claude/skills/monodesign/scripts/detector/engines/static-html/css-cascade.mjs +0 -1016
  166. package/.claude/skills/monodesign/scripts/detector/engines/static-html/detect-html.mjs +0 -253
  167. package/.claude/skills/monodesign/scripts/detector/engines/visual/screenshot-contrast.mjs +0 -198
  168. package/.claude/skills/monodesign/scripts/detector/findings.mjs +0 -12
  169. package/.claude/skills/monodesign/scripts/detector/fix/css-regions.mjs +0 -181
  170. package/.claude/skills/monodesign/scripts/detector/fix/fixers.mjs +0 -373
  171. package/.claude/skills/monodesign/scripts/detector/fix/index.mjs +0 -426
  172. package/.claude/skills/monodesign/scripts/detector/node/file-system.mjs +0 -198
  173. package/.claude/skills/monodesign/scripts/detector/profile/profiler.mjs +0 -166
  174. package/.claude/skills/monodesign/scripts/detector/registry/antipatterns.mjs +0 -563
  175. package/.claude/skills/monodesign/scripts/detector/rules/checks.mjs +0 -3024
  176. package/.claude/skills/monodesign/scripts/detector/shared/color.mjs +0 -124
  177. package/.claude/skills/monodesign/scripts/detector/shared/constants.mjs +0 -101
  178. package/.claude/skills/monodesign/scripts/detector/shared/fonts.mjs +0 -30
  179. package/.claude/skills/monodesign/scripts/detector/shared/inline-ignores.mjs +0 -148
  180. package/.claude/skills/monodesign/scripts/detector/shared/page.mjs +0 -7
  181. package/.claude/skills/monodesign/scripts/hook-admin.mjs +0 -694
  182. package/.claude/skills/monodesign/scripts/hook-before-edit.mjs +0 -516
  183. package/.claude/skills/monodesign/scripts/hook-lib.mjs +0 -1785
  184. package/.claude/skills/monodesign/scripts/hook.mjs +0 -61
  185. package/.claude/skills/monodesign/scripts/lib/design-parser.mjs +0 -809
  186. package/.claude/skills/monodesign/scripts/lib/is-generated.mjs +0 -69
  187. package/.claude/skills/monodesign/scripts/lib/monodesign-config.mjs +0 -640
  188. package/.claude/skills/monodesign/scripts/lib/monodesign-paths.mjs +0 -129
  189. package/.claude/skills/monodesign/scripts/lib/provider.mjs +0 -4
  190. package/.claude/skills/monodesign/scripts/lib/target-args.mjs +0 -42
  191. package/.claude/skills/monodesign/scripts/live/browser-script-parts.mjs +0 -50
  192. package/.claude/skills/monodesign/scripts/live/completion.mjs +0 -19
  193. package/.claude/skills/monodesign/scripts/live/event-validation.mjs +0 -137
  194. package/.claude/skills/monodesign/scripts/live/insert-ui.mjs +0 -458
  195. package/.claude/skills/monodesign/scripts/live/manual-apply.mjs +0 -939
  196. package/.claude/skills/monodesign/scripts/live/manual-edit-routes.mjs +0 -357
  197. package/.claude/skills/monodesign/scripts/live/manual-edits-buffer.mjs +0 -152
  198. package/.claude/skills/monodesign/scripts/live/session-store.mjs +0 -293
  199. package/.claude/skills/monodesign/scripts/live/svelte-component.mjs +0 -826
  200. package/.claude/skills/monodesign/scripts/live/sveltekit-adapter.mjs +0 -279
  201. package/.claude/skills/monodesign/scripts/live/ui-core.mjs +0 -180
  202. package/.claude/skills/monodesign/scripts/live/vocabulary.mjs +0 -36
  203. package/.claude/skills/monodesign/scripts/live-accept.mjs +0 -812
  204. package/.claude/skills/monodesign/scripts/live-browser-dom.js +0 -147
  205. package/.claude/skills/monodesign/scripts/live-browser-session.js +0 -124
  206. package/.claude/skills/monodesign/scripts/live-browser.js +0 -11213
  207. package/.claude/skills/monodesign/scripts/live-commit-manual-edits.mjs +0 -1241
  208. package/.claude/skills/monodesign/scripts/live-complete.mjs +0 -75
  209. package/.claude/skills/monodesign/scripts/live-copy-edit-agent.mjs +0 -683
  210. package/.claude/skills/monodesign/scripts/live-discard-manual-edits.mjs +0 -51
  211. package/.claude/skills/monodesign/scripts/live-inject.mjs +0 -596
  212. package/.claude/skills/monodesign/scripts/live-insert.mjs +0 -272
  213. package/.claude/skills/monodesign/scripts/live-manual-edit-evidence.mjs +0 -363
  214. package/.claude/skills/monodesign/scripts/live-poll.mjs +0 -384
  215. package/.claude/skills/monodesign/scripts/live-resume.mjs +0 -94
  216. package/.claude/skills/monodesign/scripts/live-server.mjs +0 -1210
  217. package/.claude/skills/monodesign/scripts/live-status.mjs +0 -61
  218. package/.claude/skills/monodesign/scripts/live-target.mjs +0 -30
  219. package/.claude/skills/monodesign/scripts/live-wrap.mjs +0 -884
  220. package/.claude/skills/monodesign/scripts/live.mjs +0 -297
  221. package/.claude/skills/monodesign/scripts/modern-screenshot.umd.js +0 -14
  222. package/.claude/skills/monodesign/scripts/palette.mjs +0 -635
  223. package/.claude/skills/monodesign/scripts/pin.mjs +0 -221
  224. package/.claude/skills/monodesign/shape.md +0 -71
  225. package/.claude/skills/monodesign/teach.md +0 -18
  226. package/.claude/skills/monodesign/typeset.md +0 -59
@@ -1,51 +0,0 @@
1
- #!/usr/bin/env node
2
- /**
3
- * CLI helper: discard pending manual edits from the buffer without applying.
4
- *
5
- * Reads .monodesign/live/pending-manual-edits.json, drops entries, writes back.
6
- * No source-file writes. Use this when the user wants to throw away unsaved
7
- * manual edits.
8
- *
9
- * Trigger: only when the user explicitly asks the AI to discard / throw away /
10
- * clear pending manual edits.
11
- *
12
- * Usage:
13
- * node live-discard-manual-edits.mjs # discard all pending
14
- * node live-discard-manual-edits.mjs --page-url=/ # discard only entries for "/"
15
- *
16
- * Output JSON: { discarded: N, entries: [...discardedEntries], totalCount: N }
17
- */
18
-
19
- import { readBuffer, removeEntries, truncateBuffer } from './live/manual-edits-buffer.mjs';
20
-
21
- function argVal(args, name) {
22
- const prefix = `${name}=`;
23
- for (const a of args) {
24
- if (a === name) return true;
25
- if (a.startsWith(prefix)) return a.slice(prefix.length);
26
- }
27
- return null;
28
- }
29
-
30
- const args = process.argv.slice(2);
31
- if (args.includes('--help') || args.includes('-h')) {
32
- console.log('Usage: node live-discard-manual-edits.mjs [--page-url=<url>]');
33
- process.exit(0);
34
- }
35
-
36
- const pageUrlFilter = argVal(args, '--page-url');
37
- const cwd = process.cwd();
38
-
39
- let discarded;
40
- let entries;
41
- const buffer = readBuffer(cwd);
42
- if (pageUrlFilter) {
43
- entries = buffer.entries.filter((entry) => entry.pageUrl === pageUrlFilter);
44
- discarded = removeEntries(cwd, (entry) => entry.pageUrl === pageUrlFilter);
45
- } else {
46
- entries = buffer.entries;
47
- discarded = truncateBuffer(cwd);
48
- }
49
-
50
- const remaining = readBuffer(cwd).entries.reduce((n, e) => n + e.ops.length, 0);
51
- console.log(JSON.stringify({ discarded, entries, totalCount: remaining }));
@@ -1,596 +0,0 @@
1
- /**
2
- * CLI helper: insert/remove the live variant mode script tag in the project's
3
- * main HTML entry point.
4
- *
5
- * On first live run, the agent generates `.monodesign/live/config.json`
6
- * with the project's insertion target (framework-specific). On
7
- * every subsequent run, this script handles insert/remove deterministically
8
- * with zero LLM involvement.
9
- *
10
- * Usage:
11
- * node live-inject.mjs --port PORT # Insert the live script tag
12
- * node live-inject.mjs --remove # Remove the live script tag
13
- * node live-inject.mjs --check # Check whether live config exists
14
- */
15
-
16
- import fs from 'node:fs';
17
- import path from 'node:path';
18
- import { fileURLToPath } from 'node:url';
19
- import { resolveLiveConfigPath, readLiveServerInfo } from './lib/monodesign-paths.mjs';
20
- import {
21
- applySvelteKitLiveAdapter,
22
- detectSvelteKitProject,
23
- removeSvelteKitLiveAdapter,
24
- } from './live/sveltekit-adapter.mjs';
25
-
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
- ]);
56
-
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
- ];
66
-
67
- export async function injectCli() {
68
- const args = process.argv.slice(2);
69
-
70
- if (args.includes('--help') || args.includes('-h')) {
71
- console.log(`Usage: node live-inject.mjs [options]
72
-
73
- Insert or remove the live mode script tag in the project's HTML entry point.
74
- Reads configuration from .monodesign/live/config.json.
75
-
76
- Modes:
77
- --port PORT Insert script tag pointing at http://localhost:PORT/live.js
78
- --remove Remove the script tag (if present)
79
- --check Print whether .monodesign/live/config.json exists and its content
80
-
81
- Output (JSON):
82
- { ok, file, inserted|removed, config? }`);
83
- process.exit(0);
84
- }
85
-
86
- if (args.includes('--check')) {
87
- if (!fs.existsSync(CONFIG_PATH)) {
88
- console.log(JSON.stringify({ ok: false, error: 'config_missing', path: CONFIG_PATH }));
89
- process.exit(0);
90
- }
91
- let cfg;
92
- try {
93
- cfg = JSON.parse(fs.readFileSync(CONFIG_PATH, 'utf-8'));
94
- } catch (err) {
95
- console.log(JSON.stringify({ ok: false, error: 'config_invalid', message: err.message, path: CONFIG_PATH }));
96
- return;
97
- }
98
- try {
99
- validateConfig(cfg);
100
- } catch (err) {
101
- console.log(JSON.stringify({ ok: false, error: 'config_invalid', message: err.message, path: CONFIG_PATH }));
102
- return;
103
- }
104
- console.log(JSON.stringify({ ok: true, config: cfg, path: CONFIG_PATH }));
105
- return;
106
- }
107
-
108
- // Load config
109
- if (!fs.existsSync(CONFIG_PATH)) {
110
- console.error(JSON.stringify({ ok: false, error: 'config_missing', path: CONFIG_PATH }));
111
- process.exit(1);
112
- }
113
- const config = JSON.parse(fs.readFileSync(CONFIG_PATH, 'utf-8'));
114
- validateConfig(config);
115
-
116
- const resolvedFiles = resolveFiles(process.cwd(), config);
117
- const svelteKit = detectSvelteKitProject(process.cwd(), config);
118
-
119
- if (args.includes('--remove')) {
120
- if (svelteKit) {
121
- const adapterResult = removeSvelteKitLiveAdapter({ cwd: process.cwd(), config });
122
- console.log(JSON.stringify({ ok: true, adapter: 'sveltekit', results: [adapterResult] }));
123
- return;
124
- }
125
- const results = resolvedFiles.map((relFile) => {
126
- const absFile = path.resolve(process.cwd(), relFile);
127
- if (!fs.existsSync(absFile)) return { file: relFile, error: 'file_not_found' };
128
- const content = fs.readFileSync(absFile, 'utf-8');
129
- const detagged = removeTag(content, config.commentSyntax);
130
- const updated = revertCspMeta(detagged);
131
- if (updated === content) return { file: relFile, removed: false, note: 'no tag present' };
132
- fs.writeFileSync(absFile, updated, 'utf-8');
133
- return {
134
- file: relFile,
135
- removed: detagged !== content,
136
- cspReverted: updated !== detagged,
137
- };
138
- });
139
- console.log(JSON.stringify({ ok: true, results }));
140
- return;
141
- }
142
-
143
- // Insert mode — need --port
144
- const portIdx = args.indexOf('--port');
145
- const port = portIdx !== -1 ? parseInt(args[portIdx + 1], 10) : NaN;
146
- if (!Number.isFinite(port)) {
147
- console.error(JSON.stringify({ ok: false, error: 'missing_port' }));
148
- process.exit(1);
149
- }
150
- // The injected tag must authenticate like every other server route does —
151
- // read the per-process credential live-server.mjs persisted at startup.
152
- const liveInfo = readLiveServerInfo(process.cwd());
153
- const credentialFields = liveInfo?.info ?? {};
154
- const authCred = credentialFields.token;
155
- if (!authCred) {
156
- console.error(JSON.stringify({ ok: false, error: 'missing_auth_credential', detail: 'no running live server info found for this project — start it before injecting' }));
157
- process.exit(1);
158
- }
159
- const gitIgnore = ensureLiveGitIgnores(process.cwd());
160
-
161
- if (svelteKit) {
162
- const adapterResult = applySvelteKitLiveAdapter({ cwd: process.cwd(), port, authCred, config });
163
- console.log(JSON.stringify({ ok: true, port, adapter: 'sveltekit', gitIgnore, results: [adapterResult] }));
164
- return;
165
- }
166
-
167
- const results = resolvedFiles.map((relFile) => {
168
- const absFile = path.resolve(process.cwd(), relFile);
169
- if (!fs.existsSync(absFile)) return { file: relFile, error: 'file_not_found' };
170
- const content = fs.readFileSync(absFile, 'utf-8');
171
- const withoutOld = revertCspMeta(removeTag(content, config.commentSyntax));
172
- const withTag = insertTag(withoutOld, config, port, authCred, relFile);
173
- if (withTag === withoutOld) {
174
- return { file: relFile, error: 'insertion_point_not_found', anchor: config.insertBefore || config.insertAfter };
175
- }
176
- const updated = patchCspMeta(withTag, port);
177
- fs.writeFileSync(absFile, updated, 'utf-8');
178
- return {
179
- file: relFile,
180
- inserted: true,
181
- cspPatched: updated !== withTag,
182
- };
183
- });
184
- const anyInserted = results.some((r) => r.inserted);
185
- console.log(JSON.stringify({ ok: anyInserted, port, gitIgnore, results }));
186
- if (!anyInserted) process.exit(1);
187
- }
188
-
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
- const _running = process.argv[1];
591
- if (_running?.endsWith('live-inject.mjs') || _running?.endsWith('live-inject.mjs/')) {
592
- injectCli();
593
- }
594
-
595
- export { insertTag, removeTag, validateConfig, buildTagBlock };
596
- // patchCspMeta + revertCspMeta are exported above where they're defined.