@bastani/atomic 0.9.20-alpha.4 → 0.9.20-alpha.5

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 (245) hide show
  1. package/CHANGELOG.md +19 -0
  2. package/dist/builtin/intercom/CHANGELOG.md +6 -0
  3. package/dist/builtin/intercom/package.json +1 -1
  4. package/dist/builtin/intercom/skills/intercom/SKILL.md +32 -1
  5. package/dist/builtin/mcp/package.json +1 -1
  6. package/dist/builtin/subagents/CHANGELOG.md +12 -0
  7. package/dist/builtin/subagents/README.md +2 -0
  8. package/dist/builtin/subagents/agents/code-simplifier.md +1 -1
  9. package/dist/builtin/subagents/agents/codebase-analyzer.md +1 -1
  10. package/dist/builtin/subagents/agents/codebase-online-researcher.md +3 -3
  11. package/dist/builtin/subagents/agents/debugger.md +7 -5
  12. package/dist/builtin/subagents/agents/worker.md +4 -2
  13. package/dist/builtin/subagents/package.json +1 -1
  14. package/dist/builtin/subagents/skills/agent-browser/SKILL.md +56 -0
  15. package/dist/builtin/subagents/skills/subagent/SKILL.md +32 -8
  16. package/dist/builtin/subagents/src/extension/index.bundle.mjs +7 -4
  17. package/dist/builtin/web-access/package.json +1 -1
  18. package/dist/builtin/workflows/CHANGELOG.md +30 -0
  19. package/dist/builtin/workflows/README.md +4 -2
  20. package/dist/builtin/workflows/builtin/adversarial-verification.js +3 -3
  21. package/dist/builtin/workflows/builtin/{chunk-n8g2da69.js → chunk-00ywx588.js} +1 -1
  22. package/dist/builtin/workflows/builtin/{chunk-d1xqh1rd.js → chunk-55p5dxjk.js} +1 -1
  23. package/dist/builtin/workflows/builtin/{chunk-1dydq7w3.js → chunk-7f381xnq.js} +62 -24
  24. package/dist/builtin/workflows/builtin/{chunk-k18g9me8.js → chunk-7h7s5xdj.js} +1 -1
  25. package/dist/builtin/workflows/builtin/{chunk-n4yxrsm9.js → chunk-e83tc6nr.js} +1 -1
  26. package/dist/builtin/workflows/builtin/{chunk-sn5mchnx.js → chunk-evfb0312.js} +1 -1
  27. package/dist/builtin/workflows/builtin/{chunk-scgprmdj.js → chunk-ne6vh5ct.js} +1 -1
  28. package/dist/builtin/workflows/builtin/{chunk-119kxb28.js → chunk-pfm1kgqz.js} +62 -43
  29. package/dist/builtin/workflows/builtin/{chunk-hnbbb5r0.js → chunk-tdqvdrg1.js} +4 -4
  30. package/dist/builtin/workflows/builtin/{chunk-kf5xpbkz.js → chunk-tvcydq13.js} +1 -1
  31. package/dist/builtin/workflows/builtin/{chunk-9y0f90rd.js → chunk-x2nftpgj.js} +1 -1
  32. package/dist/builtin/workflows/builtin/{chunk-vt9zgr9d.js → chunk-zj5162bh.js} +4 -4
  33. package/dist/builtin/workflows/builtin/classify-and-act.js +3 -3
  34. package/dist/builtin/workflows/builtin/fan-out-and-synthesize.js +3 -3
  35. package/dist/builtin/workflows/builtin/generate-and-filter.js +3 -3
  36. package/dist/builtin/workflows/builtin/goal.js +4 -4
  37. package/dist/builtin/workflows/builtin/index.d.ts +1 -1
  38. package/dist/builtin/workflows/builtin/index.js +12 -12
  39. package/dist/builtin/workflows/builtin/loop-until-done.js +3 -3
  40. package/dist/builtin/workflows/builtin/open-claude-design.d.ts +1 -1
  41. package/dist/builtin/workflows/builtin/open-claude-design.js +3 -3
  42. package/dist/builtin/workflows/builtin/ralph.js +4 -4
  43. package/dist/builtin/workflows/builtin/steering-context.js +1 -1
  44. package/dist/builtin/workflows/builtin/tournament.js +3 -3
  45. package/dist/builtin/workflows/package.json +1 -1
  46. package/dist/builtin/workflows/skills/impeccable/SKILL.md +18 -11
  47. package/dist/builtin/workflows/skills/impeccable/reference/adapt.md +1 -1
  48. package/dist/builtin/workflows/skills/impeccable/reference/adapt.native.md +1 -1
  49. package/dist/builtin/workflows/skills/impeccable/reference/animate.md +1 -1
  50. package/dist/builtin/workflows/skills/impeccable/reference/audit.md +5 -5
  51. package/dist/builtin/workflows/skills/impeccable/reference/audit.native.md +6 -6
  52. package/dist/builtin/workflows/skills/impeccable/reference/bolder.md +2 -2
  53. package/dist/builtin/workflows/skills/impeccable/reference/clarify.md +1 -1
  54. package/dist/builtin/workflows/skills/impeccable/reference/colorize.md +1 -1
  55. package/dist/builtin/workflows/skills/impeccable/reference/craft-floor.md +0 -6
  56. package/dist/builtin/workflows/skills/impeccable/reference/critique.md +19 -41
  57. package/dist/builtin/workflows/skills/impeccable/reference/degraded/asset-producer.md +11 -65
  58. package/dist/builtin/workflows/skills/impeccable/reference/degraded/documenter.md +3 -3
  59. package/dist/builtin/workflows/skills/impeccable/reference/degraded/finish-reviewer.md +4 -4
  60. package/dist/builtin/workflows/skills/impeccable/reference/degraded/manual-edit-applier.md +1 -1
  61. package/dist/builtin/workflows/skills/impeccable/reference/delight.md +1 -1
  62. package/dist/builtin/workflows/skills/impeccable/reference/distill.md +2 -2
  63. package/dist/builtin/workflows/skills/impeccable/reference/doctor.md +4 -4
  64. package/dist/builtin/workflows/skills/impeccable/reference/document.md +4 -4
  65. package/dist/builtin/workflows/skills/impeccable/reference/extract.md +1 -1
  66. package/dist/builtin/workflows/skills/impeccable/reference/harden.md +1 -1
  67. package/dist/builtin/workflows/skills/impeccable/reference/hooks.md +21 -21
  68. package/dist/builtin/workflows/skills/impeccable/reference/init.md +8 -8
  69. package/dist/builtin/workflows/skills/impeccable/reference/layout.md +2 -2
  70. package/dist/builtin/workflows/skills/impeccable/reference/live-setup.md +10 -8
  71. package/dist/builtin/workflows/skills/impeccable/reference/live.md +39 -38
  72. package/dist/builtin/workflows/skills/impeccable/reference/new-work.md +48 -21
  73. package/dist/builtin/workflows/skills/impeccable/reference/onboard.md +1 -1
  74. package/dist/builtin/workflows/skills/impeccable/reference/optimize.md +1 -1
  75. package/dist/builtin/workflows/skills/impeccable/reference/overdrive.md +1 -1
  76. package/dist/builtin/workflows/skills/impeccable/reference/polish.md +11 -3
  77. package/dist/builtin/workflows/skills/impeccable/reference/quieter.md +2 -2
  78. package/dist/builtin/workflows/skills/impeccable/reference/routing.md +13 -7
  79. package/dist/builtin/workflows/skills/impeccable/reference/typeset.md +2 -2
  80. package/dist/builtin/workflows/skills/impeccable/reference/visualize.md +13 -19
  81. package/dist/builtin/workflows/skills/impeccable/scripts/VERSION +1 -0
  82. package/dist/builtin/workflows/skills/impeccable/scripts/data/font-index-failures.json +121 -0
  83. package/dist/builtin/workflows/skills/impeccable/scripts/data/font-index.json +1 -0
  84. package/dist/builtin/workflows/skills/impeccable/scripts/impeccable +212 -0
  85. package/dist/builtin/workflows/skills/impeccable/scripts/impeccable.cmd +218 -0
  86. package/dist/builtin/workflows/skills/impeccable/scripts/live-browser-dom.js +21 -0
  87. package/dist/builtin/workflows/skills/impeccable/scripts/live-browser-ignores.js +242 -0
  88. package/dist/builtin/workflows/skills/impeccable/scripts/live-browser-session.js +25 -4
  89. package/dist/builtin/workflows/skills/impeccable/scripts/live-browser.js +666 -197
  90. package/dist/builtin/workflows/skills/research-codebase/SKILL.md +1 -1
  91. package/dist/builtin/workflows/src/extension/index.bundle.mjs +156 -84
  92. package/dist/builtin/workflows/src/index.js +62 -24
  93. package/dist/core/execution-model-router.d.ts +2 -0
  94. package/dist/core/execution-model-router.d.ts.map +1 -1
  95. package/dist/core/execution-model-router.js +30 -4
  96. package/dist/core/execution-model-router.js.map +1 -1
  97. package/dist/core/model-routing-task.d.ts +1 -1
  98. package/dist/core/model-routing-task.d.ts.map +1 -1
  99. package/dist/core/model-routing-task.js +4 -3
  100. package/dist/core/model-routing-task.js.map +1 -1
  101. package/dist/core/system-prompt.d.ts.map +1 -1
  102. package/dist/core/system-prompt.js +2 -1
  103. package/dist/core/system-prompt.js.map +1 -1
  104. package/dist/index.d.ts +1 -1
  105. package/dist/index.d.ts.map +1 -1
  106. package/dist/index.js +1 -1
  107. package/dist/index.js.map +1 -1
  108. package/dist/modes/interactive/components/chat-message-renderer.d.ts.map +1 -1
  109. package/dist/modes/interactive/components/chat-message-renderer.js +4 -0
  110. package/dist/modes/interactive/components/chat-message-renderer.js.map +1 -1
  111. package/docs/computer-use.md +22 -21
  112. package/docs/getting-started/first-session.md +2 -2
  113. package/docs/getting-started/installation.md +6 -2
  114. package/docs/intercom.md +6 -1
  115. package/docs/models/model-selection.md +11 -7
  116. package/docs/quickstart.md +1 -1
  117. package/docs/skills.md +1 -1
  118. package/docs/subagents/reference.md +2 -2
  119. package/docs/subagents.md +7 -1
  120. package/docs/usage.md +2 -0
  121. package/docs/windows.md +1 -1
  122. package/docs/workflows/api-reference.md +3 -4
  123. package/docs/workflows/builtins.md +2 -2
  124. package/docs/workflows/operations.md +1 -1
  125. package/docs/workflows/reliable-design.md +12 -1
  126. package/docs/workflows/verification.md +8 -8
  127. package/npm-shrinkwrap.json +32 -32
  128. package/package.json +3 -3
  129. package/dist/builtin/subagents/skills/playwright-cli/SKILL.md +0 -420
  130. package/dist/builtin/subagents/skills/playwright-cli/references/element-attributes.md +0 -23
  131. package/dist/builtin/subagents/skills/playwright-cli/references/playwright-tests.md +0 -39
  132. package/dist/builtin/subagents/skills/playwright-cli/references/request-mocking.md +0 -87
  133. package/dist/builtin/subagents/skills/playwright-cli/references/running-code.md +0 -241
  134. package/dist/builtin/subagents/skills/playwright-cli/references/session-management.md +0 -225
  135. package/dist/builtin/subagents/skills/playwright-cli/references/storage-state.md +0 -275
  136. package/dist/builtin/subagents/skills/playwright-cli/references/test-generation.md +0 -433
  137. package/dist/builtin/subagents/skills/playwright-cli/references/tracing.md +0 -139
  138. package/dist/builtin/subagents/skills/playwright-cli/references/video-recording.md +0 -143
  139. package/dist/builtin/workflows/skills/impeccable/agents/impeccable_asset_producer.toml +0 -94
  140. package/dist/builtin/workflows/skills/impeccable/agents/impeccable_documenter.toml +0 -27
  141. package/dist/builtin/workflows/skills/impeccable/agents/impeccable_finish_reviewer.toml +0 -41
  142. package/dist/builtin/workflows/skills/impeccable/agents/impeccable_manual_edit_applier.toml +0 -95
  143. package/dist/builtin/workflows/skills/impeccable/agents/openai.yaml +0 -4
  144. package/dist/builtin/workflows/skills/impeccable/scripts/concept-seed.mjs +0 -695
  145. package/dist/builtin/workflows/skills/impeccable/scripts/context-signals.mjs +0 -325
  146. package/dist/builtin/workflows/skills/impeccable/scripts/context.mjs +0 -1503
  147. package/dist/builtin/workflows/skills/impeccable/scripts/critique-storage.mjs +0 -222
  148. package/dist/builtin/workflows/skills/impeccable/scripts/detect-csp.mjs +0 -198
  149. package/dist/builtin/workflows/skills/impeccable/scripts/detect.mjs +0 -21
  150. package/dist/builtin/workflows/skills/impeccable/scripts/detector/browser/injected/index.mjs +0 -2073
  151. package/dist/builtin/workflows/skills/impeccable/scripts/detector/cli/main.mjs +0 -432
  152. package/dist/builtin/workflows/skills/impeccable/scripts/detector/design-system.mjs +0 -1121
  153. package/dist/builtin/workflows/skills/impeccable/scripts/detector/detect-antipatterns-browser.js +0 -8746
  154. package/dist/builtin/workflows/skills/impeccable/scripts/detector/detect-antipatterns.mjs +0 -51
  155. package/dist/builtin/workflows/skills/impeccable/scripts/detector/engines/browser/detect-url.mjs +0 -376
  156. package/dist/builtin/workflows/skills/impeccable/scripts/detector/engines/regex/detect-text.mjs +0 -1168
  157. package/dist/builtin/workflows/skills/impeccable/scripts/detector/engines/static-html/css-cascade.mjs +0 -1192
  158. package/dist/builtin/workflows/skills/impeccable/scripts/detector/engines/static-html/detect-html.mjs +0 -290
  159. package/dist/builtin/workflows/skills/impeccable/scripts/detector/engines/visual/screenshot-contrast.mjs +0 -189
  160. package/dist/builtin/workflows/skills/impeccable/scripts/detector/findings.mjs +0 -18
  161. package/dist/builtin/workflows/skills/impeccable/scripts/detector/node/file-system.mjs +0 -213
  162. package/dist/builtin/workflows/skills/impeccable/scripts/detector/profile/profiler.mjs +0 -166
  163. package/dist/builtin/workflows/skills/impeccable/scripts/detector/registry/antipatterns.mjs +0 -617
  164. package/dist/builtin/workflows/skills/impeccable/scripts/detector/rules/checks.mjs +0 -5534
  165. package/dist/builtin/workflows/skills/impeccable/scripts/detector/shared/color.mjs +0 -588
  166. package/dist/builtin/workflows/skills/impeccable/scripts/detector/shared/constants.mjs +0 -112
  167. package/dist/builtin/workflows/skills/impeccable/scripts/detector/shared/fonts.mjs +0 -30
  168. package/dist/builtin/workflows/skills/impeccable/scripts/detector/shared/inline-ignores.mjs +0 -148
  169. package/dist/builtin/workflows/skills/impeccable/scripts/detector/shared/page.mjs +0 -35
  170. package/dist/builtin/workflows/skills/impeccable/scripts/doctor.mjs +0 -338
  171. package/dist/builtin/workflows/skills/impeccable/scripts/embed-prompt.mjs +0 -270
  172. package/dist/builtin/workflows/skills/impeccable/scripts/generate-image.mjs +0 -277
  173. package/dist/builtin/workflows/skills/impeccable/scripts/hook-admin.mjs +0 -783
  174. package/dist/builtin/workflows/skills/impeccable/scripts/hook-lib.mjs +0 -2305
  175. package/dist/builtin/workflows/skills/impeccable/scripts/hook.mjs +0 -78
  176. package/dist/builtin/workflows/skills/impeccable/scripts/lib/artifact-schema.mjs +0 -93
  177. package/dist/builtin/workflows/skills/impeccable/scripts/lib/composition-catalog.mjs +0 -200
  178. package/dist/builtin/workflows/skills/impeccable/scripts/lib/concept-catalog.mjs +0 -395
  179. package/dist/builtin/workflows/skills/impeccable/scripts/lib/design-parser.mjs +0 -925
  180. package/dist/builtin/workflows/skills/impeccable/scripts/lib/impeccable-config.mjs +0 -640
  181. package/dist/builtin/workflows/skills/impeccable/scripts/lib/impeccable-paths.mjs +0 -137
  182. package/dist/builtin/workflows/skills/impeccable/scripts/lib/is-generated.mjs +0 -72
  183. package/dist/builtin/workflows/skills/impeccable/scripts/lib/open-system-browser.mjs +0 -57
  184. package/dist/builtin/workflows/skills/impeccable/scripts/lib/provider.mjs +0 -5
  185. package/dist/builtin/workflows/skills/impeccable/scripts/lib/roll-selection.mjs +0 -369
  186. package/dist/builtin/workflows/skills/impeccable/scripts/lib/staleness-deep.mjs +0 -483
  187. package/dist/builtin/workflows/skills/impeccable/scripts/lib/staleness-notice.mjs +0 -169
  188. package/dist/builtin/workflows/skills/impeccable/scripts/lib/staleness.mjs +0 -528
  189. package/dist/builtin/workflows/skills/impeccable/scripts/lib/surface-briefs.mjs +0 -151
  190. package/dist/builtin/workflows/skills/impeccable/scripts/lib/target-args.mjs +0 -42
  191. package/dist/builtin/workflows/skills/impeccable/scripts/lib/target-slug.mjs +0 -33
  192. package/dist/builtin/workflows/skills/impeccable/scripts/lib/template-extensions.mjs +0 -146
  193. package/dist/builtin/workflows/skills/impeccable/scripts/live/accept-css.mjs +0 -617
  194. package/dist/builtin/workflows/skills/impeccable/scripts/live/accept-verify.mjs +0 -71
  195. package/dist/builtin/workflows/skills/impeccable/scripts/live/browser-script-parts.mjs +0 -77
  196. package/dist/builtin/workflows/skills/impeccable/scripts/live/completion.mjs +0 -28
  197. package/dist/builtin/workflows/skills/impeccable/scripts/live/event-validation.mjs +0 -199
  198. package/dist/builtin/workflows/skills/impeccable/scripts/live/frameworks/astro.mjs +0 -47
  199. package/dist/builtin/workflows/skills/impeccable/scripts/live/frameworks/detect-utils.mjs +0 -157
  200. package/dist/builtin/workflows/skills/impeccable/scripts/live/frameworks/index.mjs +0 -143
  201. package/dist/builtin/workflows/skills/impeccable/scripts/live/frameworks/journal.mjs +0 -205
  202. package/dist/builtin/workflows/skills/impeccable/scripts/live/frameworks/nextjs.mjs +0 -49
  203. package/dist/builtin/workflows/skills/impeccable/scripts/live/frameworks/nuxt.mjs +0 -170
  204. package/dist/builtin/workflows/skills/impeccable/scripts/live/frameworks/script-src.mjs +0 -26
  205. package/dist/builtin/workflows/skills/impeccable/scripts/live/frameworks/static-html.mjs +0 -26
  206. package/dist/builtin/workflows/skills/impeccable/scripts/live/frameworks/sveltekit.mjs +0 -71
  207. package/dist/builtin/workflows/skills/impeccable/scripts/live/frameworks/tag-strategy.mjs +0 -247
  208. package/dist/builtin/workflows/skills/impeccable/scripts/live/frameworks/tanstack-start.mjs +0 -70
  209. package/dist/builtin/workflows/skills/impeccable/scripts/live/frameworks/vite-generic.mjs +0 -42
  210. package/dist/builtin/workflows/skills/impeccable/scripts/live/generation-preflight.mjs +0 -149
  211. package/dist/builtin/workflows/skills/impeccable/scripts/live/insert-ui.mjs +0 -458
  212. package/dist/builtin/workflows/skills/impeccable/scripts/live/instructions.mjs +0 -169
  213. package/dist/builtin/workflows/skills/impeccable/scripts/live/manual-apply.mjs +0 -939
  214. package/dist/builtin/workflows/skills/impeccable/scripts/live/manual-edit-routes.mjs +0 -357
  215. package/dist/builtin/workflows/skills/impeccable/scripts/live/manual-edits-buffer.mjs +0 -152
  216. package/dist/builtin/workflows/skills/impeccable/scripts/live/poll-lanes.mjs +0 -14
  217. package/dist/builtin/workflows/skills/impeccable/scripts/live/roots.mjs +0 -670
  218. package/dist/builtin/workflows/skills/impeccable/scripts/live/session-store.mjs +0 -563
  219. package/dist/builtin/workflows/skills/impeccable/scripts/live/source-lock.mjs +0 -105
  220. package/dist/builtin/workflows/skills/impeccable/scripts/live/source-search.mjs +0 -105
  221. package/dist/builtin/workflows/skills/impeccable/scripts/live/svelte-ast.mjs +0 -969
  222. package/dist/builtin/workflows/skills/impeccable/scripts/live/svelte-component.mjs +0 -1401
  223. package/dist/builtin/workflows/skills/impeccable/scripts/live/sveltekit-adapter.mjs +0 -314
  224. package/dist/builtin/workflows/skills/impeccable/scripts/live/tanstack-adapter.mjs +0 -280
  225. package/dist/builtin/workflows/skills/impeccable/scripts/live/ui-surfaces.mjs +0 -75
  226. package/dist/builtin/workflows/skills/impeccable/scripts/live/vocabulary.mjs +0 -171
  227. package/dist/builtin/workflows/skills/impeccable/scripts/live-accept.mjs +0 -961
  228. package/dist/builtin/workflows/skills/impeccable/scripts/live-commit-manual-edits.mjs +0 -1244
  229. package/dist/builtin/workflows/skills/impeccable/scripts/live-complete.mjs +0 -107
  230. package/dist/builtin/workflows/skills/impeccable/scripts/live-copy-edit-agent.mjs +0 -800
  231. package/dist/builtin/workflows/skills/impeccable/scripts/live-discard-manual-edits.mjs +0 -51
  232. package/dist/builtin/workflows/skills/impeccable/scripts/live-inject.mjs +0 -515
  233. package/dist/builtin/workflows/skills/impeccable/scripts/live-insert.mjs +0 -292
  234. package/dist/builtin/workflows/skills/impeccable/scripts/live-manual-edit-evidence.mjs +0 -371
  235. package/dist/builtin/workflows/skills/impeccable/scripts/live-poll.mjs +0 -427
  236. package/dist/builtin/workflows/skills/impeccable/scripts/live-resume.mjs +0 -123
  237. package/dist/builtin/workflows/skills/impeccable/scripts/live-server.mjs +0 -1675
  238. package/dist/builtin/workflows/skills/impeccable/scripts/live-status.mjs +0 -71
  239. package/dist/builtin/workflows/skills/impeccable/scripts/live-target.mjs +0 -30
  240. package/dist/builtin/workflows/skills/impeccable/scripts/live-wrap.mjs +0 -927
  241. package/dist/builtin/workflows/skills/impeccable/scripts/live.mjs +0 -365
  242. package/dist/builtin/workflows/skills/impeccable/scripts/palette.mjs +0 -628
  243. package/dist/builtin/workflows/skills/impeccable/scripts/pin.mjs +0 -224
  244. package/dist/builtin/workflows/skills/impeccable/scripts/serve-question.mjs +0 -1540
  245. package/dist/builtin/workflows/skills/impeccable/scripts/surface-brief.mjs +0 -74
@@ -1,961 +0,0 @@
1
- /**
2
- * CLI helper: deterministic accept/discard of variant sessions.
3
- *
4
- * Usage:
5
- * node live-accept.mjs --id SESSION_ID --discard
6
- * node live-accept.mjs --id SESSION_ID --variant N
7
- *
8
- * For discard: removes the entire variant wrapper and restores the original.
9
- * For accept: replaces the wrapper with the chosen variant's content. If the
10
- * session had a colocated <style> block, it's preserved with carbonize markers
11
- * for a background agent to integrate into the project's CSS.
12
- *
13
- * Output: JSON to stdout.
14
- */
15
-
16
- import fs from 'node:fs';
17
- import path from 'node:path';
18
- import { isGeneratedFile } from './lib/is-generated.mjs';
19
- import { getLiveDir, safeSessionId } from './lib/impeccable-paths.mjs';
20
- import { resolveLiveTemplateExtensions } from './lib/template-extensions.mjs';
21
- import { readBuffer as readManualEditsBuffer, writeBuffer as writeManualEditsBuffer } from './live/manual-edits-buffer.mjs';
22
- import { NEVER_SOURCE_DIRS, findSourceFile } from './live/source-search.mjs';
23
- import { withSourceLockSync } from './live/source-lock.mjs';
24
- import {
25
- applyDeferredSvelteComponentAccepts,
26
- findSvelteComponentManifest,
27
- inlineSvelteComponentAccept,
28
- removeSvelteComponentSession,
29
- } from './live/svelte-component.mjs';
30
- import { enterLiveRoot } from './live/roots.mjs';
31
-
32
- const ACCEPT_LOCK_WAIT_MS = 1_000;
33
- // Mirrors VARIANT_ID_PATTERN in live/event-validation.mjs, which gates the same
34
- // value arriving over HTTP.
35
- const VARIANT_NUM_PATTERN = /^[0-9]{1,3}$/;
36
-
37
- /**
38
- * A thrown accept/discard is a real failure, not a manual handoff.
39
- *
40
- * live/completion.mjs only classifies a result as `error` when it carries
41
- * `mode: 'error'`; anything else unhandled falls through to `agent_done` with a
42
- * successful ack, and reference/live.md then tells the agent to finish the edit
43
- * by hand. That is right for the documented fallback paths and wrong here: a
44
- * `source_locked` contention needs a retry (hand-editing races the publisher
45
- * holding the lock), and a crash needs surfacing, not a hand-applied guess.
46
- */
47
- function operationFailure(err, extra = {}) {
48
- return { handled: false, mode: 'error', error: err.message, ...extra };
49
- }
50
-
51
- /**
52
- * Mark an unhandled preview-path result as a real failure.
53
- *
54
- * operationFailure only covers results built from a *thrown* error. The accept
55
- * implementations also return `{handled: false, error}` for their own checks
56
- * (variant missing, template empty, original text ambiguous), and those arrived
57
- * without `mode`, so completion.mjs classified them as agent_done and
58
- * reference/live.md routed the agent to "read file, find markers, edit".
59
- *
60
- * That handoff only makes sense for a plain wrapper session, which is the one
61
- * shape with markers in the user's source to edit. Component and isolated
62
- * artifact previews keep the source clean until Accept, so there is nothing to
63
- * hand-edit and an unhandled result is always a failure. `previewMode` is
64
- * exactly that discriminator: only the preview branches set it.
65
- */
66
- function markPreviewFailure(result) {
67
- if (result?.handled === false && !result.mode && result.previewMode) {
68
- return { ...result, mode: 'error' };
69
- }
70
- return result;
71
- }
72
-
73
- // ---------------------------------------------------------------------------
74
- // CLI
75
- // ---------------------------------------------------------------------------
76
-
77
- export async function acceptCli() {
78
- const args = process.argv.slice(2);
79
-
80
- if (args.includes('--help') || args.includes('-h')) {
81
- console.log(`Usage: node live-accept.mjs [options]
82
-
83
- Deterministic accept/discard for live variant sessions.
84
-
85
- Modes:
86
- --discard Remove variants, restore original
87
- --variant N Accept variant N, discard the rest
88
-
89
- Required:
90
- --id SESSION_ID Session ID of the variant wrapper
91
-
92
- Options:
93
- --page-url URL Current browser page URL; scopes staged copy-edit cleanup
94
- --defer-source-write
95
- Deprecated compatibility flag. Svelte component accepts
96
- now write the real source immediately.
97
-
98
- Output (JSON):
99
- { handled, file, carbonize }`);
100
- process.exit(0);
101
- }
102
-
103
- const id = argVal(args, '--id');
104
- const variantNum = argVal(args, '--variant');
105
- const paramValuesRaw = argVal(args, '--param-values');
106
- const pageUrl = argVal(args, '--page-url');
107
- const isDiscard = args.includes('--discard');
108
-
109
- if (!id) { console.error('Missing --id'); process.exit(1); }
110
- // `id` becomes a path segment (accept receipts, preview manifests, generated
111
- // component dirs). Reject separators and traversal here so one check covers
112
- // every downstream sink.
113
- try { safeSessionId(id); } catch { console.error('Invalid --id'); process.exit(1); }
114
- if (!isDiscard && !variantNum) { console.error('Need --discard or --variant N'); process.exit(1); }
115
- // `variantNum` is interpolated into a RegExp and into the markup written back
116
- // to source. The browser and the /events schema both constrain it to digits;
117
- // enforce the same here, or `--variant '.*'` matches the `original` block
118
- // first and silently accepts the original while reporting success.
119
- if (!isDiscard && !VARIANT_NUM_PATTERN.test(variantNum)) {
120
- console.error('Invalid --variant');
121
- process.exit(1);
122
- }
123
-
124
- const requestedOperation = isDiscard ? 'discard' : 'accept';
125
- const priorReceipt = readAcceptReceipt(process.cwd(), id);
126
- if (priorReceipt) {
127
- const sameOperation = priorReceipt.operation === requestedOperation
128
- && (isDiscard || String(priorReceipt.variantId) === String(variantNum));
129
- console.log(JSON.stringify(sameOperation
130
- ? { ...priorReceipt.result, handled: true, alreadyApplied: true }
131
- : {
132
- // mode: 'error' is what marks this a real failure rather than a manual
133
- // handoff. Without it, live/completion.mjs classifies the reply as
134
- // agent_done and reference/live.md tells the agent to "read file, find
135
- // markers, edit" by hand — which would apply a second, conflicting
136
- // accept on top of the one the receipt already recorded.
137
- handled: false,
138
- mode: 'error',
139
- error: 'accept_receipt_conflict',
140
- priorOperation: priorReceipt.operation,
141
- priorVariantId: priorReceipt.variantId ?? null,
142
- }));
143
- return;
144
- }
145
- const emitResult = (rawResult) => {
146
- const result = markPreviewFailure(rawResult);
147
- if (result?.handled !== false) {
148
- writeAcceptReceipt(process.cwd(), id, {
149
- operation: requestedOperation,
150
- variantId: isDiscard ? null : String(variantNum),
151
- result,
152
- });
153
- }
154
- console.log(JSON.stringify(result));
155
- };
156
-
157
- let paramValues = null;
158
- if (paramValuesRaw) {
159
- try { paramValues = JSON.parse(paramValuesRaw); }
160
- catch { paramValues = null; } // malformed blob: skip the comment rather than failing the accept
161
- }
162
-
163
- // Find the file containing this session's markers
164
- const found = findSessionFile(id, process.cwd());
165
- const svelteComponentManifest = found ? null : findSvelteComponentManifest(id, process.cwd());
166
-
167
- if (!found && !svelteComponentManifest) {
168
- console.log(JSON.stringify({ handled: false, error: 'Session markers not found for id: ' + id }));
169
- process.exit(0);
170
- }
171
-
172
- if (svelteComponentManifest) {
173
- const { sourceFile, componentDir } = svelteComponentManifest;
174
- const resultContext = {
175
- file: sourceFile,
176
- ...(isDiscard ? { carbonize: false } : { sourceFile }),
177
- previewMode: 'svelte-component',
178
- componentDir,
179
- };
180
- const runOperation = isDiscard
181
- ? () => {
182
- removeSvelteComponentSession(id, process.cwd());
183
- return { handled: true, ...resultContext };
184
- }
185
- : () => inlineSvelteComponentAccept(
186
- svelteComponentManifest,
187
- variantNum,
188
- paramValues,
189
- process.cwd(),
190
- );
191
-
192
- let result;
193
- try {
194
- result = withSourceLockSync(
195
- path.resolve(process.cwd(), sourceFile),
196
- requestedOperation + ':' + id,
197
- runOperation,
198
- { waitMs: ACCEPT_LOCK_WAIT_MS },
199
- );
200
- } catch (err) {
201
- result = operationFailure(err, resultContext);
202
- }
203
- if (result.carbonize) {
204
- result.todo = 'REQUIRED before next poll: carbonize cleanup in ' + result.file + '. See reference/live.md "Required after accept".';
205
- }
206
- emitResult({ handled: result.handled !== false, ...result });
207
- return;
208
- }
209
-
210
- const { file: targetFile, content, lines } = found;
211
- const relFile = path.relative(process.cwd(), targetFile);
212
- const previewBlock = findMarkerBlock(id, lines);
213
- const sourceShadowPreview = previewBlock
214
- ? readSourceShadowPreviewMeta(content, id)
215
- : null;
216
-
217
- if (sourceShadowPreview) {
218
- console.log(JSON.stringify({
219
- handled: false,
220
- error: 'source_shadow_preview_deprecated',
221
- hint: 'Svelte live mode now uses svelte-component injection. Re-wrap the element and regenerate variants.',
222
- }));
223
- process.exit(0);
224
- }
225
-
226
- if (isGeneratedFile(targetFile, { cwd: process.cwd() })) {
227
- console.log(JSON.stringify({
228
- handled: false,
229
- mode: 'fallback',
230
- file: relFile,
231
- hint: 'Session is in a generated file. Persist the accepted variant in source; do not rely on this script.',
232
- }));
233
- process.exit(0);
234
- }
235
-
236
- if (isDiscard) {
237
- let result;
238
- // handleDiscard takes the source lock, which throws SOURCE_LOCKED under
239
- // contention. Without this catch the CLI exits non-zero with empty stdout
240
- // and the agent gets no JSON to act on.
241
- try {
242
- result = handleDiscard(id, lines, targetFile);
243
- } catch (err) {
244
- emitResult(operationFailure(err, { file: relFile }));
245
- return;
246
- }
247
- emitResult({ handled: true, file: relFile, carbonize: false, ...result });
248
- } else {
249
- let result;
250
- try {
251
- result = handleAccept(id, variantNum, lines, targetFile, paramValues);
252
- } catch (err) {
253
- emitResult(operationFailure(err, { file: relFile }));
254
- return;
255
- }
256
- const acceptedOriginalText = result.acceptedOriginalText || '';
257
- delete result.acceptedOriginalText;
258
- // Single-line attention-grabber when cleanup is required. The full
259
- // five-step checklist lives in reference/live.md (loaded once per
260
- // session); repeating it per-event would waste tokens.
261
- if (result.carbonize) {
262
- result.todo = 'REQUIRED before next poll: carbonize cleanup in ' + relFile + '. See reference/live.md "Required after accept".';
263
- }
264
- // Scrub stash entries whose text appeared inside the just-replaced
265
- // original wrap block. The accept embodies those manual edits (wrap was
266
- // buffer-aware), so only those scoped ops are redundant.
267
- if (result.handled !== false) {
268
- try {
269
- scrubManualEditsAgainstOriginalBlock(acceptedOriginalText, process.cwd(), pageUrl);
270
- } catch {
271
- // Non-fatal; the buffer stays as-is and the user can discard later.
272
- }
273
- }
274
- emitResult({ handled: true, file: relFile, ...result });
275
- }
276
- }
277
-
278
- /**
279
- * After a variant accept rewrites one wrapper, drop only buffer ops whose
280
- * text appeared inside that wrapper's original block. The previous file-wide
281
- * scrub dropped unrelated staged edits from other components/files whenever
282
- * their originalText wasn't present in the just-accepted file.
283
- *
284
- * Match both originalText and newText because live-wrap rewrites the original
285
- * preview block to reflect pending manual edits before variants are generated.
286
- */
287
- function scrubManualEditsAgainstOriginalBlock(originalBlockText, cwd = process.cwd(), pageUrl = null) {
288
- const originalBlock = String(originalBlockText || '');
289
- if (!originalBlock) return;
290
- if (!pageUrl) return;
291
- const buffer = readManualEditsBuffer(cwd);
292
- if (buffer.entries.length === 0) return;
293
- let mutated = false;
294
- for (const entry of buffer.entries) {
295
- if (entry.pageUrl !== pageUrl) continue;
296
- const before = entry.ops.length;
297
- entry.ops = entry.ops.filter((op) => {
298
- return !manualEditOpAppearsInBlock(op, originalBlock);
299
- });
300
- if (entry.ops.length !== before) mutated = true;
301
- }
302
- buffer.entries = buffer.entries.filter((entry) => entry.ops.length > 0);
303
- if (mutated) writeManualEditsBuffer(cwd, buffer);
304
- }
305
-
306
- function manualEditOpAppearsInBlock(op, originalBlock) {
307
- const candidates = [op?.newText, op?.originalText]
308
- .filter((text) => typeof text === 'string' && text.length > 0);
309
- return candidates.some((text) => originalBlockHasExactManualText(originalBlock, text));
310
- }
311
-
312
- function originalBlockHasExactManualText(originalBlock, text) {
313
- const needle = normalizeManualEditText(text);
314
- if (!needle) return false;
315
- return manualEditTextSegments(originalBlock).some((segment) => segment === needle);
316
- }
317
-
318
- function manualEditTextSegments(source) {
319
- return String(source || '')
320
- .replace(/<[^>]*>/g, '\n')
321
- .replace(/\{\/\*[\s\S]*?\*\/\}/g, '\n')
322
- .replace(/<!--[\s\S]*?-->/g, '\n')
323
- .split(/\n+/)
324
- .map(normalizeManualEditText)
325
- .filter(Boolean);
326
- }
327
-
328
- function normalizeManualEditText(text) {
329
- return String(text || '').replace(/\s+/g, ' ').trim();
330
- }
331
-
332
- // Compatibility export for older tests/callers. The unsafe file-wide scrub was
333
- // removed; callers must pass accepted original-block text for scoped cleanup.
334
- function scrubManualEditsAgainstFile(_targetFile, cwd = process.cwd(), originalBlockText = '', pageUrl = null) {
335
- return scrubManualEditsAgainstOriginalBlock(originalBlockText, cwd, pageUrl);
336
- }
337
-
338
- // ---------------------------------------------------------------------------
339
- // Discard
340
- // ---------------------------------------------------------------------------
341
-
342
- function handleDiscard(id, _lines, targetFile) {
343
- return withSourceLockSync(targetFile, 'discard:' + id, () => {
344
- const lines = fs.readFileSync(targetFile, 'utf-8').split('\n');
345
- return handleDiscardUnlocked(id, lines, targetFile);
346
- }, { waitMs: ACCEPT_LOCK_WAIT_MS });
347
- }
348
-
349
- function handleDiscardUnlocked(id, lines, targetFile) {
350
- const block = findMarkerBlock(id, lines);
351
- if (!block) return { handled: false, error: 'Markers not found' };
352
-
353
- const original = extractOriginal(lines, block);
354
- const isJsx = detectCommentSyntax(targetFile).open === '{/*';
355
- const replaceRange = expandReplaceRange(block, lines, isJsx);
356
-
357
- // Restore at the line we're actually replacing FROM, not the marker line.
358
- // For JSX wrappers the marker comments live INSIDE the outer `<div>`, so
359
- // `block.start` sits 2 spaces deeper than the original element. Using that
360
- // as the deindent base would push the restored content 2 spaces too far
361
- // right on every JSX/TSX session. `replaceRange.start` is the outer wrapper
362
- // line, which is at the original element's indent for both HTML and JSX.
363
- const indent = lines[replaceRange.start].match(/^(\s*)/)[1];
364
- const restored = deindentContent(original, indent);
365
-
366
- const newLines = [
367
- ...lines.slice(0, replaceRange.start),
368
- ...restored,
369
- ...lines.slice(replaceRange.end + 1),
370
- ];
371
- fs.writeFileSync(targetFile, newLines.join('\n'), 'utf-8');
372
- return {};
373
- }
374
-
375
- // ---------------------------------------------------------------------------
376
- // Accept
377
- // ---------------------------------------------------------------------------
378
-
379
- /**
380
- * Build carbonize stitch-in lines. JSX targets occupy a single child slot
381
- * (ternary branch, return value, etc.) — the same constraint as live-wrap.
382
- * When isJsx, tuck markers + <style> + variant wrapper inside one outer
383
- * <div data-impeccable-carbonize> so the slot keeps a single root node.
384
- */
385
- function buildCarbonizeReplacement({
386
- indent,
387
- commentSyntax,
388
- isJsx,
389
- id,
390
- variantNum,
391
- cssContent,
392
- paramValues,
393
- restored,
394
- }) {
395
- const lines = [];
396
- if (!cssContent) {
397
- lines.push(...restored);
398
- return lines;
399
- }
400
-
401
- const variantStyleAttr = isJsx
402
- ? "style={{ display: 'contents' }}"
403
- : 'style="display: contents"';
404
-
405
- const pushCarbonizeBody = (bodyIndent) => {
406
- const bodyRestored = reindentContent(restored, indent, bodyIndent + ' ');
407
- lines.push(bodyIndent + commentSyntax.open + ' impeccable-carbonize-start ' + id + ' ' + commentSyntax.close);
408
- lines.push(bodyIndent + '<style data-impeccable-css="' + id + '">' + (isJsx ? '{`' : ''));
409
- for (const cssLine of cssContent) {
410
- lines.push(bodyIndent + cssLine.trimStart());
411
- }
412
- lines.push(bodyIndent + (isJsx ? '`}</style>' : '</style>'));
413
- if (paramValues && Object.keys(paramValues).length > 0) {
414
- lines.push(
415
- bodyIndent + commentSyntax.open + ' impeccable-param-values ' + id + ': ' + JSON.stringify(paramValues) + ' ' + commentSyntax.close,
416
- );
417
- }
418
- lines.push(bodyIndent + commentSyntax.open + ' impeccable-carbonize-end ' + id + ' ' + commentSyntax.close);
419
- lines.push(bodyIndent + '<div data-impeccable-variant="' + variantNum + '" ' + variantStyleAttr + '>');
420
- lines.push(...bodyRestored);
421
- lines.push(bodyIndent + '</div>');
422
- };
423
-
424
- if (isJsx) {
425
- const wrapperStyle = 'style={{ display: "contents" }}';
426
- lines.push(indent + '<div data-impeccable-carbonize="' + id + '" ' + wrapperStyle + '>');
427
- pushCarbonizeBody(indent + ' ');
428
- lines.push(indent + '</div>');
429
- } else {
430
- pushCarbonizeBody(indent);
431
- }
432
-
433
- return lines;
434
- }
435
-
436
- function reindentContent(contentLines, fromIndent, toIndent) {
437
- return contentLines.map((line) => {
438
- if (line.trim() === '') return '';
439
- if (line.startsWith(fromIndent)) return toIndent + line.slice(fromIndent.length);
440
- return toIndent + line.trimStart();
441
- });
442
- }
443
-
444
- function handleAccept(id, variantNum, _lines, targetFile, paramValues) {
445
- return withSourceLockSync(targetFile, 'accept:' + id, () => {
446
- const lines = fs.readFileSync(targetFile, 'utf-8').split('\n');
447
- return handleAcceptUnlocked(id, variantNum, lines, targetFile, paramValues);
448
- }, { waitMs: ACCEPT_LOCK_WAIT_MS });
449
- }
450
-
451
- function handleAcceptUnlocked(id, variantNum, lines, targetFile, paramValues) {
452
- const built = buildAcceptedWrappedSource(id, variantNum, lines, targetFile, paramValues);
453
- if (built.handled === false) return built;
454
- fs.writeFileSync(targetFile, built.content, 'utf-8');
455
- return {
456
- carbonize: built.carbonize,
457
- acceptedOriginalText: built.acceptedOriginalText,
458
- };
459
- }
460
-
461
- function buildAcceptedWrappedSource(id, variantNum, lines, targetFile, paramValues) {
462
- const block = findMarkerBlock(id, lines);
463
- if (!block) return { handled: false, error: 'Markers not found' };
464
-
465
- const commentSyntax = detectCommentSyntax(targetFile);
466
- const isJsx = commentSyntax.open === '{/*';
467
- // Anchor indent on the line we're replacing FROM (the outer wrapper),
468
- // not on `block.start` — for JSX that's the marker comment 2 spaces
469
- // deeper than the original element. See handleDiscard for the full
470
- // rationale.
471
- const replaceRange = expandReplaceRange(block, lines, isJsx);
472
- const indent = lines[replaceRange.start].match(/^(\s*)/)[1];
473
-
474
- // Extract the chosen variant's inner content
475
- const variantContent = extractVariant(lines, block, variantNum);
476
- if (!variantContent) return { handled: false, error: 'Variant ' + variantNum + ' not found' };
477
- const originalContent = extractOriginal(lines, block);
478
-
479
- // Extract CSS block if present
480
- const cssContent = extractCss(lines, block, id);
481
-
482
- // Check if carbonizing is needed:
483
- // - CSS block exists, OR
484
- // - variant HTML contains helper classes/attributes that need cleanup
485
- const variantText = variantContent.join('\n');
486
- const hasHelperAttrs = variantText.includes('data-impeccable-variant');
487
- const needsCarbonize = !!(cssContent || hasHelperAttrs);
488
-
489
- const restored = deindentContent(variantContent, indent);
490
- const replacement = buildCarbonizeReplacement({
491
- indent,
492
- commentSyntax,
493
- isJsx,
494
- id,
495
- variantNum,
496
- cssContent,
497
- paramValues,
498
- restored,
499
- });
500
-
501
- const newLines = [
502
- ...lines.slice(0, replaceRange.start),
503
- ...replacement,
504
- ...lines.slice(replaceRange.end + 1),
505
- ];
506
- return {
507
- content: newLines.join('\n'),
508
- carbonize: needsCarbonize,
509
- acceptedOriginalText: originalContent.join('\n'),
510
- };
511
- }
512
-
513
-
514
- function readSourceShadowPreviewMeta(content, id) {
515
- const escaped = escapeRegExp(id);
516
- const wrapperRe = new RegExp('<[^>]+data-impeccable-variants=(["\'])' + escaped + '\\1[^>]*>');
517
- const match = String(content || '').match(wrapperRe);
518
- if (!match) return null;
519
- const tag = match[0];
520
- if (readHtmlAttr(tag, 'data-impeccable-preview') !== 'source-shadow') return null;
521
- const sourceFile = readHtmlAttr(tag, 'data-impeccable-source-file');
522
- const sourceStartLine = Number(readHtmlAttr(tag, 'data-impeccable-source-start'));
523
- const sourceEndLine = Number(readHtmlAttr(tag, 'data-impeccable-source-end'));
524
- if (!sourceFile || !Number.isFinite(sourceStartLine) || !Number.isFinite(sourceEndLine)) return null;
525
- return { sourceFile, sourceStartLine, sourceEndLine };
526
- }
527
-
528
- function readHtmlAttr(tag, name) {
529
- const match = String(tag || '').match(new RegExp('\\s' + escapeRegExp(name) + '\\s*=\\s*(["\'])(.*?)\\1'));
530
- if (!match) return null;
531
- return decodeHtmlAttr(match[2]);
532
- }
533
-
534
- function decodeHtmlAttr(value) {
535
- return String(value || '')
536
- .replace(/&quot;/g, '"')
537
- .replace(/&lt;/g, '<')
538
- .replace(/&gt;/g, '>')
539
- .replace(/&amp;/g, '&');
540
- }
541
-
542
- // ---------------------------------------------------------------------------
543
- // Parsing helpers
544
- // ---------------------------------------------------------------------------
545
-
546
- /**
547
- * Find the start/end marker lines for a session.
548
- * Returns { start, end } (0-indexed line numbers) or null.
549
- */
550
- function findMarkerBlock(id, lines) {
551
- let start = -1;
552
- let end = -1;
553
- const startPattern = 'impeccable-variants-start ' + id;
554
- const endPattern = 'impeccable-variants-end ' + id;
555
-
556
- for (let i = 0; i < lines.length; i++) {
557
- if (start === -1 && lines[i].includes(startPattern)) start = i;
558
- if (lines[i].includes(endPattern)) { end = i; break; }
559
- }
560
-
561
- return (start !== -1 && end !== -1) ? { start, end, id } : null;
562
- }
563
-
564
- /**
565
- * Compute the line range to REPLACE (vs. just the marker range to extract
566
- * from). For JSX/TSX wrappers, live-wrap places the marker comments INSIDE
567
- * the `<div data-impeccable-variants="ID">` outer wrapper so the picked
568
- * element's JSX slot keeps a single child — a Fragment `<></>` would have
569
- * solved the multi-sibling case but failed inside `asChild` / cloneElement
570
- * parents with "Invalid prop supplied to React.Fragment".
571
- *
572
- * That means the marker block is enclosed by the wrapper `<div>` opener
573
- * (with `data-impeccable-variants="ID"`) and its matching `</div>`. We
574
- * walk back to the opener and forward to the closer so accept/discard
575
- * remove the entire scaffold, not just the inner markers.
576
- *
577
- * Marker lines themselves stay where they were so extractOriginal /
578
- * extractVariant / extractCss continue to walk the same range.
579
- */
580
- function expandReplaceRange(block, lines, isJsx) {
581
- if (!isJsx) return { start: block.start, end: block.end };
582
-
583
- let { start, end } = block;
584
-
585
- // Walk back for the wrapper `<div data-impeccable-variants="..."` opener.
586
- // The attr may sit on a continuation line of a multi-line opening tag, so
587
- // also walk to the line that actually contains `<div`.
588
- for (let i = start - 1; i >= 0; i--) {
589
- if (isVariantEndMarkerLine(lines[i], block.id)) break;
590
- if (hasVariantWrapperAttr(lines[i], block.id)) {
591
- let opener = i;
592
- while (opener > 0 && !/<div\b/.test(lines[opener]) && !isVariantEndMarkerLine(lines[opener], block.id)) {
593
- opener--;
594
- }
595
- if (/<div\b/.test(lines[opener])) start = opener;
596
- break;
597
- }
598
- }
599
-
600
- // Walk forward to the matching `</div>` by div-depth tracking from the
601
- // wrapper opener. Operate on JOINED text instead of per-line: a
602
- // multi-line self-closing JSX `<div\n className="spacer"\n/>` would
603
- // fool per-line regex tracking (the `<div` line matches openRe but the
604
- // `/>` line never matches selfCloseRe since it needs `<div` on the same
605
- // line). That left depth permanently over-counted and the wrapper's
606
- // outer `</div>` orphaned after accept/discard. Single regex with
607
- // `[^>]*?` (which spans newlines in JS) handles either form correctly.
608
- const joined = lines.slice(start).join('\n');
609
- // Match either `<div … />` (self-close, group 1 is `/`), `<div … >`
610
- // (open, group 1 is empty), or `</div>`.
611
- const tagRe = /<div\b[^>]*?(\/?)>|<\/div\s*>/g;
612
- let depth = 0;
613
- let m;
614
- while ((m = tagRe.exec(joined)) !== null) {
615
- const isClose = m[0].startsWith('</');
616
- const isSelfClose = !isClose && m[1] === '/';
617
- if (isClose) depth--;
618
- else if (!isSelfClose) depth++;
619
- if (depth <= 0) {
620
- // m.index is offset within `joined`; convert back to a file line.
621
- const linesBefore = joined.slice(0, m.index + m[0].length).split('\n').length - 1;
622
- const candidateEnd = start + linesBefore;
623
- if (candidateEnd >= end) {
624
- end = candidateEnd;
625
- break;
626
- }
627
- }
628
- }
629
-
630
- return { start, end };
631
- }
632
-
633
- function escapeRegExp(value) {
634
- return String(value).replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
635
- }
636
-
637
- function isVariantEndMarkerLine(line, id) {
638
- return new RegExp('impeccable-variants-end\\s+' + escapeRegExp(id) + '(?:\\s|--|\\*/|$)').test(line);
639
- }
640
-
641
- function hasVariantWrapperAttr(line, id) {
642
- const escaped = escapeRegExp(id);
643
- return new RegExp(`data-impeccable-variants\\s*=\\s*(?:"${escaped}"|'${escaped}'|\\{["']${escaped}["']\\})`).test(line);
644
- }
645
-
646
- /**
647
- * Join wrapper lines into a single string with `<style>` elements removed so
648
- * marker matching and div-depth tracking aren't confused by:
649
- * - CSS `@scope ([data-impeccable-variant="N"])` strings that look like the
650
- * HTML marker we're searching for
651
- * - JSX self-closing `<style ... />` (no separate `</style>` to close on)
652
- * - Same-line `<style>…</style>` blocks
653
- * - Multi-line `<style>\n…\n</style>` blocks
654
- */
655
- function removeCompleteStyleElements(value) {
656
- let out = value;
657
- while (true) {
658
- const lower = out.toLowerCase();
659
- const start = lower.indexOf('<style');
660
- if (start === -1) break;
661
- const openEnd = lower.indexOf('>', start + 6);
662
- if (openEnd === -1) break;
663
- if (lower.slice(start, openEnd).trimEnd().endsWith('/')) {
664
- out = out.slice(0, start) + out.slice(openEnd + 1);
665
- continue;
666
- }
667
- const closeStart = lower.indexOf('</style', openEnd + 1);
668
- const closeEnd = closeStart === -1 ? -1 : lower.indexOf('>', closeStart + 7);
669
- if (closeStart === -1 || closeEnd === -1) break;
670
- out = out.slice(0, start) + out.slice(closeEnd + 1);
671
- }
672
- return out;
673
- }
674
-
675
- function stripStyleAndJoin(lines, block) {
676
- const out = [];
677
- let inStyle = false;
678
- for (let i = block.start; i <= block.end; i++) {
679
- let line = lines[i];
680
-
681
- if (!inStyle) {
682
- // Strip any complete <style> elements on this line (self-closed or
683
- // same-line-closed), including their body content.
684
- line = removeCompleteStyleElements(line);
685
-
686
- // If a <style> opener remains (multi-line body starts here), strip from
687
- // the opener to end-of-line and flip into skip mode.
688
- const openerIdx = line.toLowerCase().indexOf('<style');
689
- if (openerIdx !== -1) {
690
- line = line.slice(0, openerIdx);
691
- inStyle = true;
692
- }
693
- out.push(line);
694
- } else {
695
- // In multi-line style body; drop everything until we see </style>.
696
- const closeIdx = line.toLowerCase().indexOf('</style');
697
- if (closeIdx !== -1) {
698
- const closeEnd = line.indexOf('>', closeIdx + 7);
699
- if (closeEnd === -1) continue;
700
- inStyle = false;
701
- out.push(line.slice(closeEnd + 1));
702
- }
703
- // else: skip line entirely
704
- }
705
- }
706
- return out.join('\n');
707
- }
708
-
709
- /**
710
- * Find the inner content of `<TAG ...attrMatch...>…</TAG>` inside `text`,
711
- * handling nested same-tag elements via depth counting. `attrMatch` is a
712
- * regex source fragment that must appear inside the opener tag.
713
- * Returns the inner string (may be empty), or null if not found.
714
- */
715
- function extractInnerByAttr(text, attrMatch) {
716
- const openerRe = new RegExp('<([A-Za-z][A-Za-z0-9]*)\\b[^>]*' + attrMatch + '[^>]*>');
717
- const openMatch = text.match(openerRe);
718
- if (!openMatch) return null;
719
-
720
- const tagName = openMatch[1];
721
- const innerStart = openMatch.index + openMatch[0].length;
722
-
723
- // Match any opener or closer of this tag name after innerStart.
724
- // (Does not match self-closing <TAG … />, which doesn't contribute to depth.)
725
- const tagRe = new RegExp('<(?:/)?' + tagName + '\\b[^>]*>', 'g');
726
- tagRe.lastIndex = innerStart;
727
-
728
- let depth = 1;
729
- let m;
730
- while ((m = tagRe.exec(text))) {
731
- const isClose = m[0].startsWith('</');
732
- const isSelfClose = !isClose && /\/\s*>$/.test(m[0]);
733
- if (isClose) {
734
- depth--;
735
- if (depth === 0) return text.slice(innerStart, m.index);
736
- } else if (!isSelfClose) {
737
- depth++;
738
- }
739
- }
740
- return null;
741
- }
742
-
743
- /**
744
- * Extract the original element content from within the variant wrapper.
745
- * Returns an array of lines.
746
- */
747
- function extractOriginal(lines, block) {
748
- const text = stripStyleAndJoin(lines, block);
749
- const inner = extractInnerByAttr(text, 'data-impeccable-variant="original"');
750
- if (inner === null) return [];
751
- return inner.split('\n');
752
- }
753
-
754
- /**
755
- * Extract a specific variant's inner content (stripping the wrapper div).
756
- * Returns an array of lines, or null if not found.
757
- */
758
- function extractVariant(lines, block, variantNum) {
759
- const text = stripStyleAndJoin(lines, block);
760
- // `variantNum` is digit-validated at the CLI boundary, but escape it anyway:
761
- // it originates from a command-line argument, and an inert fragment is what
762
- // CodeQL's js/regex-injection remediation asks for.
763
- const inner = extractInnerByAttr(text, 'data-impeccable-variant="' + escapeRegExp(String(variantNum)) + '"');
764
- if (inner === null) return null;
765
- const result = inner.split('\n');
766
- // Collapse a lone empty leading/trailing line (common after string splice).
767
- while (result.length > 1 && result[0].trim() === '') result.shift();
768
- while (result.length > 1 && result[result.length - 1].trim() === '') result.pop();
769
- return result.length > 0 ? result : null;
770
- }
771
-
772
- /**
773
- * Extract the colocated <style> block content (between the style tags).
774
- * Returns an array of CSS lines, or null if no style block found.
775
- *
776
- * Handles three shapes of `<style data-impeccable-css="ID" ...>`:
777
- * 1. Self-closing: `<style ... />` — no body; return null (nothing to carbonize).
778
- * 2. Same-line open+close: `<style>...</style>` — return the inner content.
779
- * 3. Multi-line: `<style>` on one line, `</style>` on a later line — return
780
- * the lines between them.
781
- */
782
- function extractCss(lines, block, id) {
783
- const styleAttr = 'data-impeccable-css="' + id + '"';
784
- let inStyle = false;
785
- const content = [];
786
-
787
- for (let i = block.start; i <= block.end; i++) {
788
- const line = lines[i];
789
-
790
- if (!inStyle && line.includes(styleAttr)) {
791
- // Self-closing: nothing to carbonize.
792
- if (/<style\b[^>]*\/\s*>/.test(line)) return null;
793
- // Same-line open + close: extract inner text.
794
- const sameLine = line.match(/<style\b[^>]*>([\s\S]*?)<\/style\s*>/);
795
- if (sameLine) {
796
- const inner = stripJsxTemplateWrap(sameLine[1]);
797
- return inner.length > 0 ? inner.split('\n') : null;
798
- }
799
- inStyle = true;
800
- continue; // skip the <style> opening tag
801
- }
802
-
803
- if (inStyle) {
804
- // Detect </style> anywhere on the line — JSX template-literal closes
805
- // (`}</style>`) put the close mid-line, and we don't want to absorb the
806
- // template-literal punctuation as CSS content.
807
- const closeIdx = line.indexOf('</style>');
808
- if (closeIdx !== -1) break;
809
- content.push(line);
810
- }
811
- }
812
-
813
- if (content.length === 0) return null;
814
- return stripJsxTemplateLines(content);
815
- }
816
-
817
- /**
818
- * Strip a JSX template-literal wrap (`{` … `}`) from CSS extracted out of a
819
- * `<style>` element in a JSX/TSX file. The agent may write the wrap with
820
- * `{` and `}` directly attached to the `<style>` tags, on their own lines,
821
- * or attached to the first/last CSS lines — all three are JSX-legal.
822
- *
823
- * Stripping is required because handleAccept re-wraps the CSS itself when
824
- * carbonizing. Without this, two consecutive accepts (or a previously-
825
- * accepted variants block being carbonized) would produce nested
826
- * `{` `{` … `}` `}`, which oxc rejects with "Expected `}` but found `@`".
827
- */
828
- function stripJsxTemplateLines(content) {
829
- const out = content.slice();
830
-
831
- // Drop any leading blank lines so we don't miss a `{` line buried below
832
- // them; same for trailing.
833
- while (out.length > 0 && out[0].trim() === '') out.shift();
834
- while (out.length > 0 && out[out.length - 1].trim() === '') out.pop();
835
- if (out.length === 0) return null;
836
-
837
- // Leading `{`: own line, or attached to the first CSS line.
838
- const firstTrim = out[0].trimStart();
839
- if (firstTrim === '{`') {
840
- out.shift();
841
- } else if (firstTrim.startsWith('{`')) {
842
- const idx = out[0].indexOf('{`');
843
- out[0] = out[0].slice(0, idx) + out[0].slice(idx + 2);
844
- if (out[0].trim() === '') out.shift();
845
- }
846
- if (out.length === 0) return null;
847
-
848
- // Trailing `` ` `` `}`: own line, or attached to the last CSS line.
849
- const lastIdx = out.length - 1;
850
- const lastTrim = out[lastIdx].trimEnd();
851
- if (lastTrim === '`}') {
852
- out.pop();
853
- } else if (lastTrim.endsWith('`}')) {
854
- const text = out[lastIdx];
855
- const idx = text.lastIndexOf('`}');
856
- out[lastIdx] = text.slice(0, idx) + text.slice(idx + 2);
857
- if (out[lastIdx].trim() === '') out.pop();
858
- }
859
-
860
- return out.length > 0 ? out : null;
861
- }
862
-
863
- function stripJsxTemplateWrap(text) {
864
- const lines = text.split('\n');
865
- const stripped = stripJsxTemplateLines(lines);
866
- return stripped ? stripped.join('\n') : '';
867
- }
868
-
869
- /**
870
- * De-indent content that was indented by live-wrap.mjs.
871
- * The wrap script adds `indent + ' '` (4 extra spaces) to each line.
872
- * We restore to just `indent` level.
873
- */
874
- function deindentContent(contentLines, baseIndent) {
875
- // Find the minimum indentation in the content to determine how much was added
876
- let minIndent = Infinity;
877
- for (const line of contentLines) {
878
- if (line.trim() === '') continue;
879
- const leadingSpaces = line.match(/^(\s*)/)[1].length;
880
- minIndent = Math.min(minIndent, leadingSpaces);
881
- }
882
- if (minIndent === Infinity) minIndent = 0;
883
-
884
- // Strip the extra indentation and re-add base indent
885
- return contentLines.map(line => {
886
- if (line.trim() === '') return '';
887
- return baseIndent + line.slice(minIndent);
888
- });
889
- }
890
-
891
- function detectCommentSyntax(filePath) {
892
- const ext = path.extname(filePath).toLowerCase();
893
- if (ext === '.jsx' || ext === '.tsx') {
894
- return { open: '{/*', close: '*/}' };
895
- }
896
- return { open: '<!--', close: '-->' };
897
- }
898
-
899
- // ---------------------------------------------------------------------------
900
- // File search (find the file containing session markers)
901
- // ---------------------------------------------------------------------------
902
-
903
- /**
904
- * Accept also skips `dist` / `build` outright, where wrap descends into them so
905
- * its `includeGenerated` second pass can report a `generatedMatch`. Accept has
906
- * no such pass: a marker found in build output is only ever a stale copy of the
907
- * marker in source.
908
- */
909
- const SEARCH_SKIP_DIRS = [...NEVER_SOURCE_DIRS, 'dist', 'build'];
910
-
911
- function findSessionFile(id, cwd) {
912
- const result = findSourceFile({
913
- query: 'impeccable-variants-start ' + id,
914
- cwd,
915
- extensions: resolveLiveTemplateExtensions(cwd),
916
- skipDirs: SEARCH_SKIP_DIRS,
917
- });
918
- if (!result) return null;
919
- const content = fs.readFileSync(result, 'utf-8');
920
- return { file: result, content, lines: content.split('\n') };
921
- }
922
-
923
- // ---------------------------------------------------------------------------
924
- // Utilities
925
- // ---------------------------------------------------------------------------
926
-
927
- function acceptReceiptPath(cwd, id) {
928
- return path.join(getLiveDir(cwd), 'accept-receipts', `${safeSessionId(id)}.json`);
929
- }
930
-
931
- function readAcceptReceipt(cwd, id) {
932
- try { return JSON.parse(fs.readFileSync(acceptReceiptPath(cwd, id), 'utf-8')); } catch { return null; }
933
- }
934
-
935
- function writeAcceptReceipt(cwd, id, receipt) {
936
- const file = acceptReceiptPath(cwd, id);
937
- fs.mkdirSync(path.dirname(file), { recursive: true });
938
- const value = {
939
- id,
940
- ...receipt,
941
- completedAt: new Date().toISOString(),
942
- };
943
- const temporary = `${file}.${process.pid}.${Date.now()}.tmp`;
944
- fs.writeFileSync(temporary, JSON.stringify(value, null, 2) + '\n', 'utf-8');
945
- fs.renameSync(temporary, file);
946
- return value;
947
- }
948
-
949
- function argVal(args, flag) {
950
- const idx = args.indexOf(flag);
951
- return idx !== -1 && idx + 1 < args.length ? args[idx + 1] : null;
952
- }
953
-
954
- // Auto-execute when run directly
955
- const _running = process.argv[1];
956
- if (_running?.endsWith('live-accept.mjs') || _running?.endsWith('live-accept.mjs/')) {
957
- enterLiveRoot();
958
- acceptCli();
959
- }
960
-
961
- export { findMarkerBlock, extractOriginal, extractVariant, extractCss, deindentContent, detectCommentSyntax, scrubManualEditsAgainstFile, scrubManualEditsAgainstOriginalBlock, applyDeferredSvelteComponentAccepts };