sygnal 5.4.0 → 6.1.0

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 (360) hide show
  1. package/CHANGELOG.md +716 -0
  2. package/README.md +24 -9
  3. package/dist/ai.cjs.js +115 -0
  4. package/dist/ai.cjs.js.map +1 -0
  5. package/dist/ai.esm.js +2 -0
  6. package/dist/ai.esm.js.map +1 -0
  7. package/dist/astro/client.cjs.js +16 -9
  8. package/dist/astro/client.cjs.js.map +1 -1
  9. package/dist/astro/client.mjs +16 -9
  10. package/dist/astro/client.mjs.map +1 -1
  11. package/dist/astro/index.cjs.js +958 -92
  12. package/dist/astro/index.cjs.js.map +1 -1
  13. package/dist/astro/index.mjs +958 -93
  14. package/dist/astro/index.mjs.map +1 -1
  15. package/dist/astro/server.cjs.js +3396 -165
  16. package/dist/astro/server.cjs.js.map +1 -1
  17. package/dist/astro/server.mjs +3396 -165
  18. package/dist/astro/server.mjs.map +1 -1
  19. package/dist/devtools.cjs.js +1840 -0
  20. package/dist/devtools.cjs.js.map +1 -0
  21. package/dist/devtools.esm.js +1827 -0
  22. package/dist/devtools.esm.js.map +1 -0
  23. package/dist/diagnostics.cjs.js +3190 -296
  24. package/dist/diagnostics.cjs.js.map +1 -1
  25. package/dist/diagnostics.esm.js +3190 -296
  26. package/dist/diagnostics.esm.js.map +1 -1
  27. package/dist/element.cjs.js +230 -0
  28. package/dist/element.cjs.js.map +1 -0
  29. package/dist/element.esm.js +228 -0
  30. package/dist/element.esm.js.map +1 -0
  31. package/dist/guide/accessibility.md +310 -0
  32. package/dist/guide/adapters.md +221 -0
  33. package/dist/guide/agent.md +588 -0
  34. package/dist/guide/ai-chat.md +693 -0
  35. package/dist/guide/ai-decisions.md +330 -0
  36. package/dist/guide/behaviors.md +312 -0
  37. package/dist/guide/browser-sources.md +203 -0
  38. package/dist/guide/drag-and-drop.md +342 -0
  39. package/dist/guide/element-commands.md +306 -0
  40. package/dist/guide/error-boundaries.md +169 -0
  41. package/dist/guide/forms-reference.md +409 -0
  42. package/dist/guide/forms.md +251 -0
  43. package/dist/guide/http.md +301 -0
  44. package/dist/guide/inputs.md +173 -0
  45. package/dist/guide/mcp-apps.md +272 -0
  46. package/dist/guide/persistence.md +245 -0
  47. package/dist/guide/recipes/ai-form-fill.md +163 -0
  48. package/dist/guide/recipes/ai-summarize.md +155 -0
  49. package/dist/guide/recipes/ai-support-inbox.md +190 -0
  50. package/dist/guide/recipes/carousel.md +155 -0
  51. package/dist/guide/recipes/charts.md +177 -0
  52. package/dist/guide/recipes/code-editor.md +135 -0
  53. package/dist/guide/recipes/data-grid.md +155 -0
  54. package/dist/guide/recipes/data-table.md +196 -0
  55. package/dist/guide/recipes/i18n.md +222 -0
  56. package/dist/guide/recipes/icons.md +115 -0
  57. package/dist/guide/recipes/overview.md +43 -0
  58. package/dist/guide/recipes/rich-text.md +154 -0
  59. package/dist/guide/resources.md +471 -0
  60. package/dist/guide/ssr.md +255 -0
  61. package/dist/guide/timers.md +178 -0
  62. package/dist/guide/ui/accordion.md +93 -0
  63. package/dist/guide/ui/combobox.md +144 -0
  64. package/dist/guide/ui/dialog.md +124 -0
  65. package/dist/guide/ui/disclosure.md +60 -0
  66. package/dist/guide/ui/menu.md +125 -0
  67. package/dist/guide/ui/overview.md +166 -0
  68. package/dist/guide/ui/popover.md +101 -0
  69. package/dist/guide/ui/select.md +114 -0
  70. package/dist/guide/ui/tabs.md +161 -0
  71. package/dist/guide/ui/toaster.md +152 -0
  72. package/dist/guide/ui/tooltip.md +103 -0
  73. package/dist/guide/undo.md +178 -0
  74. package/dist/guide/virtual-collections.md +183 -0
  75. package/dist/guide/web-components.md +179 -0
  76. package/dist/guide/webmcp.md +226 -0
  77. package/dist/guide/widgets.md +217 -0
  78. package/dist/index.cjs.js +19288 -7408
  79. package/dist/index.cjs.js.map +1 -1
  80. package/dist/index.d.ts +4466 -552
  81. package/dist/index.esm.js +19274 -7461
  82. package/dist/index.esm.js.map +1 -1
  83. package/dist/jsx-dev-runtime.cjs.js +26 -334
  84. package/dist/jsx-dev-runtime.cjs.js.map +1 -1
  85. package/dist/jsx-dev-runtime.esm.js +19 -327
  86. package/dist/jsx-dev-runtime.esm.js.map +1 -1
  87. package/dist/jsx-runtime.cjs.js +26 -334
  88. package/dist/jsx-runtime.cjs.js.map +1 -1
  89. package/dist/jsx-runtime.esm.js +19 -327
  90. package/dist/jsx-runtime.esm.js.map +1 -1
  91. package/dist/jsx.cjs.js +10 -314
  92. package/dist/jsx.cjs.js.map +1 -1
  93. package/dist/jsx.esm.js +8 -315
  94. package/dist/jsx.esm.js.map +1 -1
  95. package/dist/react.cjs.js +117 -0
  96. package/dist/react.cjs.js.map +1 -0
  97. package/dist/react.esm.js +115 -0
  98. package/dist/react.esm.js.map +1 -0
  99. package/dist/shims/globalthis.cjs +20 -0
  100. package/dist/sygnal.min.js +1 -1
  101. package/dist/sygnal.min.js.map +1 -1
  102. package/dist/ui-combobox.cjs.js +169 -0
  103. package/dist/ui-combobox.cjs.js.map +1 -0
  104. package/dist/ui-combobox.esm.js +148 -0
  105. package/dist/ui-combobox.esm.js.map +1 -0
  106. package/dist/ui-menu.cjs.js +87 -0
  107. package/dist/ui-menu.cjs.js.map +1 -0
  108. package/dist/ui-menu.esm.js +66 -0
  109. package/dist/ui-menu.esm.js.map +1 -0
  110. package/dist/ui-select.cjs.js +104 -0
  111. package/dist/ui-select.cjs.js.map +1 -0
  112. package/dist/ui-select.esm.js +83 -0
  113. package/dist/ui-select.esm.js.map +1 -0
  114. package/dist/ui.cjs.js +738 -0
  115. package/dist/ui.cjs.js.map +1 -0
  116. package/dist/ui.esm.js +727 -0
  117. package/dist/ui.esm.js.map +1 -0
  118. package/dist/vike/ClientOnly.cjs.js +4 -14
  119. package/dist/vike/ClientOnly.cjs.js.map +1 -1
  120. package/dist/vike/ClientOnly.mjs +4 -14
  121. package/dist/vike/ClientOnly.mjs.map +1 -1
  122. package/dist/vike/{+config.js → config/+config.js} +9 -1
  123. package/dist/vike/config/+config.js.map +1 -0
  124. package/dist/vike/config/package.json +6 -0
  125. package/dist/vike/onRenderClient.cjs.js +165 -95
  126. package/dist/vike/onRenderClient.cjs.js.map +1 -1
  127. package/dist/vike/onRenderClient.mjs +165 -95
  128. package/dist/vike/onRenderClient.mjs.map +1 -1
  129. package/dist/vike/onRenderHtml.cjs.js +59 -24
  130. package/dist/vike/onRenderHtml.cjs.js.map +1 -1
  131. package/dist/vike/onRenderHtml.mjs +60 -25
  132. package/dist/vike/onRenderHtml.mjs.map +1 -1
  133. package/dist/vite/plugin.cjs.js +919 -89
  134. package/dist/vite/plugin.cjs.js.map +1 -1
  135. package/dist/vite/plugin.mjs +919 -90
  136. package/dist/vite/plugin.mjs.map +1 -1
  137. package/dist/zag.cjs.js +408 -0
  138. package/dist/zag.cjs.js.map +1 -0
  139. package/dist/zag.esm.js +405 -0
  140. package/dist/zag.esm.js.map +1 -0
  141. package/llms.txt +172 -103
  142. package/package.json +112 -14
  143. package/src/ai.d.ts +1186 -0
  144. package/src/ai.ts +23 -0
  145. package/src/astro/client.ts +27 -16
  146. package/src/astro/index.d.ts +24 -0
  147. package/src/astro/index.ts +69 -3
  148. package/src/astro/server.ts +8 -2
  149. package/src/collection.ts +6 -93
  150. package/src/core/actions.ts +134 -0
  151. package/src/core/cell.ts +202 -0
  152. package/src/core/debug.ts +23 -0
  153. package/src/core/define.ts +242 -0
  154. package/src/core/hooks.ts +314 -0
  155. package/src/core/hosts/collection.ts +325 -0
  156. package/src/core/hosts/switchable.ts +146 -0
  157. package/src/core/instance.ts +592 -0
  158. package/src/core/markers/clientonly.ts +13 -0
  159. package/src/core/markers/lazy.ts +40 -0
  160. package/src/core/markers/portal.ts +96 -0
  161. package/src/core/markers/suspense.ts +41 -0
  162. package/src/core/markers/transition.ts +70 -0
  163. package/src/core/registry.ts +25 -0
  164. package/src/core/runtime.ts +573 -0
  165. package/src/core/statics.ts +104 -0
  166. package/src/core/teardown.ts +60 -0
  167. package/src/core/view.ts +37 -0
  168. package/src/cycle/dom/DocumentDOMSource.ts +13 -8
  169. package/src/cycle/dom/ElementFinder.ts +7 -9
  170. package/src/cycle/dom/EventDelegator.ts +174 -223
  171. package/src/cycle/dom/IsolateModule.ts +65 -35
  172. package/src/cycle/dom/MainDOMSource.ts +9 -2
  173. package/src/cycle/dom/PriorityQueue.ts +4 -2
  174. package/src/cycle/dom/SymbolTree.ts +18 -47
  175. package/src/cycle/dom/classNameModule.ts +9 -7
  176. package/src/cycle/dom/controlledInputModule.ts +23 -6
  177. package/src/cycle/dom/enrichEventStream.ts +25 -47
  178. package/src/cycle/dom/fragment.ts +7 -0
  179. package/src/cycle/dom/isolate.ts +30 -27
  180. package/src/cycle/dom/makeDOMDriver.ts +115 -56
  181. package/src/cycle/dom/mockDOMSource.ts +21 -1
  182. package/src/cycle/dom/modules.ts +16 -3
  183. package/src/cycle/dom/propsModule.ts +65 -0
  184. package/src/cycle/dom/selectModule.ts +22 -17
  185. package/src/cycle/dom/snabbdom.ts +1 -6
  186. package/src/cycle/dom/thunk.ts +3 -0
  187. package/src/cycle/dom/utils.ts +98 -0
  188. package/src/cycle/dom/viewTransition.ts +43 -0
  189. package/src/cycle/state/StateSource.ts +19 -3
  190. package/src/cycle/state/objIsEqual.ts +50 -0
  191. package/src/cycle/state/types.ts +0 -10
  192. package/src/defineComponent.ts +34 -0
  193. package/src/devtools.d.ts +170 -0
  194. package/src/devtools.ts +37 -0
  195. package/src/element.d.ts +59 -0
  196. package/src/element.ts +235 -0
  197. package/src/extra/ai/agent/index.ts +484 -0
  198. package/src/extra/ai/answers.ts +115 -0
  199. package/src/extra/ai/chat/behavior.ts +336 -0
  200. package/src/extra/ai/chat/driver.ts +271 -0
  201. package/src/extra/ai/chat/memoryTransport.ts +61 -0
  202. package/src/extra/ai/chat/output.ts +37 -0
  203. package/src/extra/ai/commandBar.ts +281 -0
  204. package/src/extra/ai/decide.ts +104 -0
  205. package/src/extra/ai/index.ts +42 -0
  206. package/src/extra/ai/link.ts +90 -0
  207. package/src/extra/ai/mcpApp.ts +314 -0
  208. package/src/extra/ai/messages.ts +51 -0
  209. package/src/extra/ai/schema/index.ts +166 -0
  210. package/src/extra/ai/schema/jsonSchema.ts +72 -0
  211. package/src/extra/ai/schema/strict.ts +152 -0
  212. package/src/extra/ai/transports/agui.ts +177 -0
  213. package/src/extra/ai/transports/anthropicMessages.ts +175 -0
  214. package/src/extra/ai/transports/chatCompletions.ts +105 -0
  215. package/src/extra/ai/transports/chromePrompt.ts +77 -0
  216. package/src/extra/ai/transports/encodeOpenResponses.ts +87 -0
  217. package/src/extra/ai/transports/fromAISDK.ts +126 -0
  218. package/src/extra/ai/transports/openResponses.ts +105 -0
  219. package/src/extra/ai/transports/shared.ts +125 -0
  220. package/src/extra/ai/transports/tools.ts +59 -0
  221. package/src/extra/ai/transports/uiMessageStream.ts +107 -0
  222. package/src/extra/ai/webmcp.ts +260 -0
  223. package/src/extra/backoff.ts +9 -0
  224. package/src/extra/behaviors.ts +169 -0
  225. package/src/extra/browserSignals.ts +23 -0
  226. package/src/extra/browserSources.ts +326 -0
  227. package/src/extra/command.ts +3 -3
  228. package/src/extra/controls.ts +47 -0
  229. package/src/extra/copyAsTest.ts +286 -0
  230. package/src/extra/devMcp.ts +386 -0
  231. package/src/extra/devtools.ts +101 -31
  232. package/src/extra/devtoolsActions.ts +379 -0
  233. package/src/extra/devtoolsHook.ts +9 -0
  234. package/src/extra/devtoolsNext.ts +83 -0
  235. package/src/extra/diagnostics/checks/actionLog.ts +108 -0
  236. package/src/extra/diagnostics/checks/behaviors.ts +49 -0
  237. package/src/extra/diagnostics/checks/browserSources.ts +96 -0
  238. package/src/extra/diagnostics/checks/chat.ts +71 -0
  239. package/src/extra/diagnostics/checks/collections.ts +1 -1
  240. package/src/extra/diagnostics/checks/controls.ts +148 -0
  241. package/src/extra/diagnostics/checks/dataset.ts +57 -0
  242. package/src/extra/diagnostics/checks/dom.ts +20 -11
  243. package/src/extra/diagnostics/checks/elementCommands.ts +175 -0
  244. package/src/extra/diagnostics/checks/events.ts +17 -2
  245. package/src/extra/diagnostics/checks/fetch.ts +135 -0
  246. package/src/extra/diagnostics/checks/forms.ts +171 -0
  247. package/src/extra/diagnostics/checks/index.ts +103 -4
  248. package/src/extra/diagnostics/checks/inspect.ts +140 -32
  249. package/src/extra/diagnostics/checks/next.ts +417 -0
  250. package/src/extra/diagnostics/checks/persist.ts +54 -0
  251. package/src/extra/diagnostics/checks/props.ts +10 -5
  252. package/src/extra/diagnostics/checks/public.d.ts +115 -7
  253. package/src/extra/diagnostics/checks/replies.ts +128 -0
  254. package/src/extra/diagnostics/checks/router.ts +100 -0
  255. package/src/extra/diagnostics/checks/rxjsHints.ts +1 -1
  256. package/src/extra/diagnostics/checks/shared.ts +86 -2
  257. package/src/extra/diagnostics/checks/shorthand.ts +115 -0
  258. package/src/extra/diagnostics/checks/sortable.ts +129 -0
  259. package/src/extra/diagnostics/checks/state.ts +100 -7
  260. package/src/extra/diagnostics/checks/statics.ts +48 -0
  261. package/src/extra/diagnostics/checks/strict.ts +10 -67
  262. package/src/extra/diagnostics/checks/timers.ts +80 -0
  263. package/src/extra/diagnostics/checks/viewTransitions.ts +47 -0
  264. package/src/extra/diagnostics/checks/virtual.ts +73 -0
  265. package/src/extra/diagnostics/checks/widgets.ts +109 -0
  266. package/src/extra/diagnostics/checks/wiring.ts +69 -10
  267. package/src/extra/diagnostics/codes.ts +335 -23
  268. package/src/extra/diagnostics/index.ts +34 -9
  269. package/src/extra/diagnostics/legacy.ts +17 -0
  270. package/src/extra/driverFactories.ts +83 -19
  271. package/src/extra/elementCommands.ts +53 -0
  272. package/src/extra/fetchDriver.ts +519 -0
  273. package/src/extra/focusWithin.ts +27 -0
  274. package/src/extra/form.ts +284 -0
  275. package/src/extra/formHelpers.ts +139 -0
  276. package/src/extra/formTool.ts +150 -0
  277. package/src/extra/head.ts +106 -0
  278. package/src/extra/hmr.ts +2 -3
  279. package/src/extra/owned.ts +24 -0
  280. package/src/extra/pager.ts +50 -0
  281. package/src/extra/persist.ts +133 -0
  282. package/src/extra/pwa.ts +1 -1
  283. package/src/extra/queryCache.ts +107 -0
  284. package/src/extra/reducers.ts +1 -1
  285. package/src/extra/reduxDevtools.ts +92 -0
  286. package/src/extra/replies.ts +54 -0
  287. package/src/extra/router.ts +323 -0
  288. package/src/extra/run.ts +90 -217
  289. package/src/extra/selection.ts +76 -0
  290. package/src/extra/socketDriver.ts +265 -0
  291. package/src/extra/sortable.ts +377 -0
  292. package/src/extra/ssr.ts +427 -160
  293. package/src/extra/standardSchema.ts +27 -0
  294. package/src/extra/testing.ts +2550 -175
  295. package/src/extra/timers.ts +95 -0
  296. package/src/extra/undo.ts +261 -0
  297. package/src/extra/viewTransitions.ts +38 -0
  298. package/src/extra/virtual.ts +513 -0
  299. package/src/extra/widget.ts +201 -0
  300. package/src/index.d.ts +2754 -127
  301. package/src/index.ts +45 -4
  302. package/src/jsx-runtime.ts +15 -1
  303. package/src/jsx.ts +2 -1
  304. package/src/lazy.ts +50 -7
  305. package/src/portal.ts +3 -1
  306. package/src/pragma/index.ts +256 -133
  307. package/src/react-peers.d.ts +5 -0
  308. package/src/react.d.ts +43 -0
  309. package/src/react.ts +110 -0
  310. package/src/shared.ts +57 -0
  311. package/src/slot.ts +1 -1
  312. package/src/suspense.ts +3 -1
  313. package/src/switchable.ts +6 -121
  314. package/src/transition.ts +3 -1
  315. package/src/ui/accordion.ts +64 -0
  316. package/src/ui/dialog.ts +129 -0
  317. package/src/ui/disclosure.ts +35 -0
  318. package/src/ui/popover.ts +45 -0
  319. package/src/ui/shared.ts +94 -0
  320. package/src/ui/tabs.ts +82 -0
  321. package/src/ui/toaster.ts +198 -0
  322. package/src/ui/tooltip.ts +70 -0
  323. package/src/ui/zag/combobox.ts +115 -0
  324. package/src/ui/zag/menu.ts +40 -0
  325. package/src/ui/zag/select.ts +54 -0
  326. package/src/ui/zag/shared.ts +43 -0
  327. package/src/ui-combobox.d.ts +20 -0
  328. package/src/ui-combobox.ts +6 -0
  329. package/src/ui-menu.d.ts +30 -0
  330. package/src/ui-menu.ts +6 -0
  331. package/src/ui-select.d.ts +17 -0
  332. package/src/ui-select.ts +6 -0
  333. package/src/ui-zag-types.d.ts +42 -0
  334. package/src/ui.d.ts +208 -0
  335. package/src/ui.ts +15 -0
  336. package/src/vike/+config.ts +9 -1
  337. package/src/vike/ClientOnly.ts +1 -1
  338. package/src/vike/onRenderClient.ts +144 -96
  339. package/src/vike/onRenderHtml.ts +69 -26
  340. package/src/vike/types.ts +7 -1
  341. package/src/vite/globalthis-shim.ts +18 -0
  342. package/src/vite/globalthis.ts +56 -0
  343. package/src/vite/mcp.ts +568 -0
  344. package/src/vite/plugin.d.ts +47 -3
  345. package/src/vite/plugin.ts +262 -25
  346. package/src/zag.d.ts +64 -0
  347. package/src/zag.ts +238 -0
  348. package/dist/vike/+config.cjs.js +0 -66
  349. package/dist/vike/+config.cjs.js.map +0 -1
  350. package/dist/vike/+config.js.map +0 -1
  351. package/src/component.ts +0 -2301
  352. package/src/cycle/isolate/index.ts +0 -196
  353. package/src/cycle/run/index.ts +0 -151
  354. package/src/cycle/run/internals.ts +0 -143
  355. package/src/cycle/state/Collection.ts +0 -184
  356. package/src/cycle/state/index.ts +0 -5
  357. package/src/cycle/state/pickCombine.ts +0 -201
  358. package/src/cycle/state/pickMerge.ts +0 -122
  359. package/src/cycle/state/withState.ts +0 -47
  360. package/src/pragma/fn.ts +0 -55
@@ -1,7 +1,624 @@
1
1
  import fs from 'node:fs';
2
2
  import path from 'node:path';
3
3
  import { createRequire } from 'node:module';
4
- import { pathToFileURL } from 'node:url';
4
+ import { fileURLToPath, pathToFileURL } from 'node:url';
5
+
6
+ /**
7
+ * G-099: xstream does `require('globalthis').getPolyfill()`, which pulls the
8
+ * `globalthis` polyfill and its dependency chain (define-properties,
9
+ * get-intrinsic, object-keys, has-symbols, ...; ~4 KB gzip) into every app
10
+ * bundle. Every runtime Sygnal supports has a native `globalThis`, so
11
+ * `sygnal/vite` (and the sygnal/astro integration) alias the package to
12
+ * dist/shims/globalthis.cjs (src/vite/globalthis-shim.ts) unless
13
+ * `nativeGlobalThis: false`. A `resolve.alias`, not a resolveId hook: Vite's
14
+ * dependency pre-bundling only applies aliases.
15
+ */
16
+ // Node built-ins (this runs in Node). The package has no @types/node.
17
+ // @ts-ignore
18
+ /**
19
+ * Absolute path of the stub in the sygnal package this code belongs to (found
20
+ * by walking up from this file: dist/vite, dist/astro or src/vite), or
21
+ * undefined when it is missing (e.g. sygnal not built).
22
+ */
23
+ function globalThisShim() {
24
+ try {
25
+ let dir = path.dirname(fileURLToPath(import.meta.url));
26
+ while (dir !== path.dirname(dir)) {
27
+ const pkgFile = path.join(dir, 'package.json');
28
+ if (fs.existsSync(pkgFile) && JSON.parse(fs.readFileSync(pkgFile, 'utf8')).name === 'sygnal') {
29
+ const file = path.join(dir, 'dist', 'shims', 'globalthis.cjs');
30
+ return fs.existsSync(file) ? file : undefined;
31
+ }
32
+ dir = path.dirname(dir);
33
+ }
34
+ }
35
+ catch (_) { }
36
+ return undefined;
37
+ }
38
+ /**
39
+ * Whether a Vite `resolve.alias` value (object or array form) already maps
40
+ * `globalthis` (R2-7): the user's alias wins and the stub is not added.
41
+ */
42
+ function hasGlobalThisAlias(alias) {
43
+ if (!alias)
44
+ return false;
45
+ if (!Array.isArray(alias))
46
+ return Object.prototype.hasOwnProperty.call(alias, 'globalthis');
47
+ return alias.some((a) => a && (a.find instanceof RegExp ? a.find.test('globalthis') : a.find === 'globalthis'));
48
+ }
49
+ /**
50
+ * Vite `resolve.alias` entries for the stub (empty when it is missing, or
51
+ * when `userAlias` — the user's `resolve.alias` — already maps `globalthis`).
52
+ */
53
+ function globalThisAlias(userAlias) {
54
+ const shim = hasGlobalThisAlias(userAlias) ? undefined : globalThisShim();
55
+ return shim ? [{ find: /^globalthis$/, replacement: shim }] : [];
56
+ }
57
+
58
+ /**
59
+ * PLAN-6 E-1: the dev MCP endpoint of sygnal/vite (`sygnal({ mcp: true })`), dev server only.
60
+ *
61
+ * `/__sygnal/mcp` speaks MCP's streamable HTTP transport: JSON-RPC 2.0 over POST, answered as
62
+ * one `application/json` body, in both protocol eras (G-655: a dual-era server):
63
+ *
64
+ * - legacy, the `initialize` revisions (2024-11-05 … 2025-11-25). G-638: JSON replies make a
65
+ * complete server under the spec (the client must accept JSON or SSE; a server without a GET
66
+ * stream answers 405; session ids are optional, "MAY assign"). Methods: initialize, ping,
67
+ * tools/list, tools/call; notifications get 202; batches (2025-03-26) are answered.
68
+ * - modern, the stateless 2026-07-28 revision (no initialize, no sessions, no ping): each request
69
+ * carries `_meta['io.modelcontextprotocol/protocolVersion']` and `.../clientCapabilities`, and
70
+ * the `MCP-Protocol-Version`, `Mcp-Method` and (tools/call) `Mcp-Name` headers, which must
71
+ * match the body (else 400 with -32020 HeaderMismatch; missing `_meta` fields: 400, -32602).
72
+ * Methods: server/discover, tools/list, tools/call; any other gets 404 with -32601. Results
73
+ * carry `resultType: 'complete'` and `_meta['io.modelcontextprotocol/serverInfo']`; tools/list
74
+ * and server/discover are cacheable results (`ttlMs`, `cacheScope`). No subscriptions/listen
75
+ * (the tool list never changes), no MRTR input requests, no logging.
76
+ *
77
+ * The era comes from each request: a 2026-07-28 header or `_meta` version is modern, anything else
78
+ * legacy (no header: 2025-03-26, as the spec allows). An unknown version gets 400 with -32022
79
+ * (UnsupportedProtocolVersion, `data: { supported, requested }`), so a modern client retries
80
+ * with one this server speaks. The server never sends requests or notifications of its own (no
81
+ * sampling, no progress, tools/list never changes), so an SSE stream would carry nothing; without
82
+ * session ids each POST stands alone (the page state lives in the browser, not in a session).
83
+ * GET and DELETE get 405. Spec: modelcontextprotocol.io/specification/2026-07-28/basic/versioning
84
+ * and .../basic/transports/streamable-http. Hand-written like sygnal-check's stdio server (no
85
+ * dependency, D209).
86
+ *
87
+ * Tools that read the page (get_state, dispatch, component_tree, recent_actions,
88
+ * get_diagnostics, copy_as_test, agent_tools) go to an open tab through a PageBridge: in the dev
89
+ * server, Vite's HMR channel (custom events 'sygnal:mcp:*', see src/extra/devMcp.ts), request /
90
+ * response with ids and a timeout. With several tabs the most recently loaded or focused one
91
+ * answers, or the `tab` argument picks one; the result says which (`tab`), and `tabs` lists
92
+ * them with their apps. G-638: every run() app of a page is served: `app` (an index, or the
93
+ * root component's name) picks one on get_state, dispatch, component_tree, copy_as_test and
94
+ * agent_tools (default: the first, or the app that has `component`); `apps` lists them. check / graph / explain run sygnal-check's own MCP server in-process when sygnal-check
95
+ * is installed in the project.
96
+ *
97
+ * Security (the endpoint can read and change the running app): requests must come from the
98
+ * loopback interface; the Host header must be localhost, a *.localhost name, a loopback IP or a
99
+ * name in Vite's `server.allowedHosts`; a request with an Origin header must come from a
100
+ * localhost / loopback origin (a web page elsewhere, or a DNS-rebinding page, gets 403).
101
+ */
102
+ // @ts-ignore
103
+ const MCP_PATH = '/__sygnal/mcp';
104
+ const MCP_HELLO = 'sygnal:mcp:hello';
105
+ const MCP_REQUEST = 'sygnal:mcp:request';
106
+ const MCP_RESPONSE = 'sygnal:mcp:response';
107
+ /** G-655: the stateless revisions (per-request `_meta`, no initialize), newest first */
108
+ const MODERN_VERSIONS = ['2026-07-28'];
109
+ /** the `initialize` revisions, newest first; initialize answers with the client's version when it knows it */
110
+ const LEGACY_VERSIONS = ['2025-11-25', '2025-06-18', '2025-03-26', '2024-11-05'];
111
+ const SUPPORTED_VERSIONS = [...MODERN_VERSIONS, ...LEGACY_VERSIONS];
112
+ const META = 'io.modelcontextprotocol/';
113
+ const INSTRUCTIONS = 'The running Sygnal apps in the dev server\'s open page: component_tree to orient, get_state / recent_actions / get_diagnostics to read, dispatch or agent_tools to act, copy_as_test to turn a session into a test; apps lists the page\'s run() apps when there are several (`app` picks one). check, graph and explain (when present) are sygnal-check on the sources.';
114
+ /** 2026-07-28 cacheable results (tools/list, server/discover): the list is fixed while the dev server runs, not across restarts */
115
+ const CACHE = { ttlMs: 0, cacheScope: 'private' };
116
+ const MAX_BODY = 1 << 20;
117
+ class ToolError extends Error {
118
+ }
119
+ const isObj = (v) => !!v && typeof v === 'object' && !Array.isArray(v);
120
+ const tabSchema = { type: 'integer', description: 'The tab to ask (see tabs); default: the most recently loaded or focused tab' };
121
+ const componentSchema = { type: ['string', 'integer'], description: 'A component name, or an instance id (see component_tree); default: the root' };
122
+ const appSchema = { type: ['string', 'integer'], description: "The app on the page: an index or the root component's name (see apps); default: the first app, or the one that has `component`" };
123
+ const obj = (properties, required) => ({
124
+ type: 'object', properties: { ...properties, tab: tabSchema }, ...(required ? { required } : {}), additionalProperties: false,
125
+ });
126
+ /** The tools answered by the page */
127
+ const PAGE_TOOLS = [
128
+ {
129
+ name: 'get_state',
130
+ title: 'Get component state',
131
+ description: "The live state of a component instance in the open page (the root by default). With several instances of a component (Collection items) you get each one's id and state. `path` reads one field: 'todos.0.text' or ['todos', 0, 'text'].",
132
+ inputSchema: obj({ component: componentSchema, app: appSchema, path: { type: ['string', 'array'], items: { type: ['string', 'integer'] }, description: "A field path: 'a.b.0' or ['a', 'b', 0]" } }),
133
+ annotations: { readOnlyHint: true },
134
+ },
135
+ {
136
+ name: 'dispatch',
137
+ title: 'Dispatch an action',
138
+ description: "Send an action to a component instance in the open page, as if its intent had produced it (recorded with cause 'agent'), and wait for the render. Returns the instance's new state. The action must be one of the component's model entries (an unknown name lists them).",
139
+ inputSchema: obj({ component: componentSchema, app: appSchema, action: { type: 'string', description: "The action name, e.g. 'ADD'" }, data: { description: 'The action data (any JSON value)' } }, ['action']),
140
+ },
141
+ {
142
+ name: 'component_tree',
143
+ title: 'Component tree (inspect)',
144
+ description: "The running apps' graph from inspect(): component instances (id, parentId, kind), their actions and what triggers them, state keys, context, EVENTS, children, intent selectors (matched or not) and the runtime diagnostics attached to each. `app` keeps one app's instances, `component` only that component's.",
145
+ inputSchema: obj({ component: componentSchema, app: { ...appSchema, description: "Only this app's instances: an index or the root component's name (see apps); default: every app" } }),
146
+ annotations: { readOnlyHint: true },
147
+ },
148
+ {
149
+ name: 'recent_actions',
150
+ title: 'Recent actions',
151
+ description: "The DevTools action log of the open page, newest last: type, data, component, instance, cause ('intent', 'agent', 'reply', ...), the sinks it reached and the state before / after a STATE change.",
152
+ inputSchema: obj({
153
+ limit: { type: 'integer', minimum: 1, maximum: 500, description: 'How many (default 20)' },
154
+ component: { type: 'string', description: 'Only this component' },
155
+ type: { type: 'string', description: 'Only this action type' },
156
+ cause: { type: 'string', enum: ['intent', 'next', 'reply', 'built-in', 'simulateAction', 'behavior', 'agent', 'setState'], description: 'Only this cause' },
157
+ }),
158
+ annotations: { readOnlyHint: true },
159
+ },
160
+ {
161
+ name: 'get_diagnostics',
162
+ title: 'Runtime diagnostics',
163
+ description: 'The runtime diagnostics the open page reported (SYG codes): code, severity, component, message, fix and docsUrl, with a summary. Use explain for a code you do not know.',
164
+ inputSchema: obj({
165
+ code: { type: 'string', description: "Only this code, e.g. 'SYG104'" },
166
+ severity: { type: 'string', enum: ['error', 'warn', 'info'] },
167
+ limit: { type: 'integer', minimum: 1, maximum: 500, description: 'How many, newest (default 100)' },
168
+ }),
169
+ annotations: { readOnlyHint: true },
170
+ },
171
+ {
172
+ name: 'copy_as_test',
173
+ title: 'Copy session as test',
174
+ description: "DevTools' Copy as test: a Vitest + renderComponent test file that replays what happened to a component instance in the open page (default: the root) and asserts its final state. Returns { code, complete, warnings, replayed }.",
175
+ inputSchema: obj({ component: componentSchema, app: appSchema, componentImport: { type: 'string', description: "Where the test imports the component from: a module path ('./App.jsx') or a whole import line" } }),
176
+ annotations: { readOnlyHint: true },
177
+ },
178
+ {
179
+ name: 'agent_tools',
180
+ title: "The app's agent tools",
181
+ description: "The open page's own agent tools (the `agent` statics, sygnal/ai): without `call`, the tools offered now (name, description, inputSchema, annotations) and the readable context; with `call`, runs that tool with `input` under the app's rules (validation, `when`, a consequential tool asks the person in the page first).",
182
+ inputSchema: obj({
183
+ call: { type: 'string', description: 'A tool name from the list' },
184
+ input: { description: 'The tool input' },
185
+ all: { type: 'boolean', description: 'List also the declared tools that are not offered, with why' },
186
+ app: { ...appSchema, description: "The app whose tools to use: an index or the root component's name (see apps); default: the first" },
187
+ }),
188
+ },
189
+ {
190
+ name: 'apps',
191
+ title: 'Apps on the page',
192
+ description: "The Sygnal apps (run() calls) running in the open page: index, root component, root instance id and instance count. The first is the default of the tools' `app` argument.",
193
+ inputSchema: obj({}),
194
+ annotations: { readOnlyHint: true },
195
+ },
196
+ ];
197
+ const TABS_TOOL = {
198
+ name: 'tabs',
199
+ title: 'Open pages',
200
+ description: 'The pages of this dev server connected to the endpoint (id, url, title, apps: { index, component } per run() app); the page tools use the most recently loaded or focused one unless given `tab`.',
201
+ inputSchema: { type: 'object', properties: {}, additionalProperties: false },
202
+ annotations: { readOnlyHint: true },
203
+ };
204
+ /** sygnal-check's MCP server (its `src/mcp.js`), loaded from the project; undefined when missing */
205
+ async function loadCheckServer(root) {
206
+ try {
207
+ const main = createRequire(path.join(root, 'package.json')).resolve('sygnal-check');
208
+ const file = path.join(path.dirname(main), 'mcp.js');
209
+ if (!fs.existsSync(file))
210
+ return undefined;
211
+ const mod = await import(/* @vite-ignore */ pathToFileURL(file).href);
212
+ if (typeof mod.createMcpServer !== 'function' || !Array.isArray(mod.TOOLS))
213
+ return undefined;
214
+ return { tools: mod.TOOLS, server: mod.createMcpServer({ cwd: root }) };
215
+ }
216
+ catch (_) {
217
+ return undefined;
218
+ }
219
+ }
220
+ /** The JSON-RPC side of the endpoint (transport-free; tests drive it directly) */
221
+ function createDevMcpServer(o) {
222
+ const timeout = o.timeout && o.timeout > 0 ? o.timeout : 10000;
223
+ const result = (id, value) => ({ jsonrpc: '2.0', id, result: value });
224
+ const error = (id, code, message) => ({ jsonrpc: '2.0', id, error: { code, message } });
225
+ let check;
226
+ const getCheck = async () => (check === undefined ? (check = (await o.check) || null) : check);
227
+ const pickTab = (want) => {
228
+ const tabs = o.bridge.tabs();
229
+ if (!tabs.length) {
230
+ const url = o.url?.();
231
+ throw new ToolError(`no page is connected: open the app${url ? ` (${url})` : ''} in a browser, with the dev server running`);
232
+ }
233
+ if (want !== undefined && want !== null) {
234
+ const tab = tabs.find(t => t.id === Number(want));
235
+ if (!tab)
236
+ throw new ToolError(`no tab ${want}; open tabs: ${tabs.map(t => `${t.id} ${t.url}`).join(', ')}`);
237
+ return { tab };
238
+ }
239
+ const tab = tabs.reduce((a, b) => (b.active > a.active ? b : a));
240
+ return { tab, note: tabs.length > 1 ? `${tabs.length} tabs are open; used tab ${tab.id} (the most recently loaded or focused). Pass tab to choose one (see tabs).` : undefined };
241
+ };
242
+ const content = (value, isError = false) => {
243
+ const structured = isObj(value) ? value : { value };
244
+ return { content: [{ type: 'text', text: JSON.stringify(structured, null, 2) }], structuredContent: structured, isError };
245
+ };
246
+ async function callTool(name, args) {
247
+ if (name === 'tabs')
248
+ return content({ tabs: o.bridge.tabs().map(({ id, url, title, apps }) => ({ id, url, title, ...(apps ? { apps } : {}) })) });
249
+ const { tab: want, ...rest } = args;
250
+ const { tab, note } = pickTab(want);
251
+ const value = await o.bridge.request(tab.id, name, rest, timeout);
252
+ const out = isObj(value) ? value : { value };
253
+ return content({ ...out, tab: { id: tab.id, url: tab.url, title: tab.title }, ...(note ? { tabNote: note } : {}) });
254
+ }
255
+ const serverInfo = { name: 'sygnal-dev', title: 'Sygnal dev server', version: o.version || '0.0.0' };
256
+ async function handleMessage(msg, modern) {
257
+ if (!isObj(msg) || msg.jsonrpc !== '2.0' || typeof msg.method !== 'string') {
258
+ return isObj(msg) && 'id' in msg && !('result' in msg || 'error' in msg) ? error(msg.id ?? null, -32600, 'Invalid Request') : null;
259
+ }
260
+ if (!('id' in msg) || msg.id === null)
261
+ return null; // a notification
262
+ const { id, method } = msg;
263
+ const params = isObj(msg.params) ? msg.params : {};
264
+ // G-655: 2026-07-28 removed initialize and ping, and added server/discover
265
+ if (modern ? method === 'initialize' || method === 'ping' : method === 'server/discover')
266
+ return error(id, -32601, `Method not found: ${method}`);
267
+ switch (method) {
268
+ case 'initialize': {
269
+ const requested = params.protocolVersion;
270
+ return result(id, {
271
+ protocolVersion: LEGACY_VERSIONS.includes(requested) ? requested : LEGACY_VERSIONS[0],
272
+ capabilities: { tools: { listChanged: false } },
273
+ serverInfo,
274
+ instructions: INSTRUCTIONS,
275
+ });
276
+ }
277
+ case 'server/discover':
278
+ return result(id, { supportedVersions: SUPPORTED_VERSIONS, capabilities: { tools: {} }, instructions: INSTRUCTIONS, ...CACHE });
279
+ case 'ping':
280
+ return result(id, {});
281
+ case 'tools/list': {
282
+ const c = await getCheck();
283
+ return result(id, { tools: [...PAGE_TOOLS, TABS_TOOL, ...(c ? c.tools : [])], ...(modern ? CACHE : {}) });
284
+ }
285
+ case 'tools/call': {
286
+ const name = params.name;
287
+ const args = isObj(params.arguments) ? params.arguments : {};
288
+ if (name === 'tabs' || PAGE_TOOLS.some(t => t.name === name)) {
289
+ try {
290
+ return result(id, await callTool(name, args));
291
+ }
292
+ catch (err) {
293
+ return result(id, { content: [{ type: 'text', text: err instanceof ToolError ? err.message : `${name} failed: ${err?.message || err}` }], isError: true });
294
+ }
295
+ }
296
+ const c = await getCheck();
297
+ if (c && c.tools.some((t) => t.name === name)) {
298
+ // without `_meta`, sygnal-check's server answers in the initialize era's shape (G-656: it
299
+ // speaks 2026-07-28 too, but this endpoint checked the envelope and adds the fields itself)
300
+ const { _meta, ...rest } = params;
301
+ return { ...c.server.handle({ ...msg, params: { ...rest, arguments: args } }), id };
302
+ }
303
+ return error(id, -32602, `Unknown tool: ${name}`);
304
+ }
305
+ default:
306
+ return error(id, -32601, `Method not found: ${method}`);
307
+ }
308
+ }
309
+ /**
310
+ * One message (or a legacy batch); never throws. `modern`: a 2026-07-28 request whose envelope
311
+ * (version, headers, `_meta` fields) the transport checked (see mcpMiddleware); its result is
312
+ * marked `resultType: 'complete'` and names the server in `_meta`.
313
+ */
314
+ async function handle(msg, modern = false) {
315
+ if (Array.isArray(msg)) {
316
+ if (modern)
317
+ return error(null, -32600, 'Invalid Request: one JSON-RPC message per POST');
318
+ const out = (await Promise.all(msg.map((m) => handle(m)))).filter(Boolean);
319
+ return out.length ? out : null;
320
+ }
321
+ try {
322
+ const out = await handleMessage(msg, modern);
323
+ if (modern && out && isObj(out.result)) {
324
+ const meta = isObj(out.result._meta) ? out.result._meta : {};
325
+ out.result = { resultType: 'complete', ...out.result, _meta: { ...meta, [META + 'serverInfo']: serverInfo } };
326
+ }
327
+ return out;
328
+ }
329
+ catch (err) {
330
+ return error(isObj(msg) && 'id' in msg ? msg.id ?? null : null, -32603, `Internal error: ${err?.message || err}`);
331
+ }
332
+ }
333
+ return { handle };
334
+ }
335
+ // ---------------------------------------------------------------- security
336
+ const LOOPBACK_IP = /^(127\.\d{1,3}\.\d{1,3}\.\d{1,3}|::1|::ffff:127\.\d{1,3}\.\d{1,3}\.\d{1,3})$/;
337
+ /** The host part of a Host header value or URL host ('[::1]:5173' → '::1') */
338
+ function hostname(host) {
339
+ const h = host.trim().toLowerCase();
340
+ if (h.startsWith('['))
341
+ return h.slice(1, h.indexOf(']') > 0 ? h.indexOf(']') : undefined);
342
+ const i = h.lastIndexOf(':');
343
+ return i > 0 && h.indexOf(':') === i ? h.slice(0, i) : h;
344
+ }
345
+ const isLocalName = (h) => h === 'localhost' || h.endsWith('.localhost') || LOOPBACK_IP.test(h);
346
+ /** Vite's allowedHosts entries: 'example.test', or '.example.test' for it and its subdomains */
347
+ function inAllowed(h, allowed) {
348
+ if (!Array.isArray(allowed))
349
+ return false;
350
+ return allowed.some((a) => {
351
+ if (typeof a !== 'string' || !a)
352
+ return false;
353
+ const e = a.toLowerCase();
354
+ return e.startsWith('.') ? h === e.slice(1) || h.endsWith(e) : h === e;
355
+ });
356
+ }
357
+ /** Why the request is refused (403), or null */
358
+ function refusal(req, allowedHosts) {
359
+ const remote = String(req?.socket?.remoteAddress || '');
360
+ if (!LOOPBACK_IP.test(remote))
361
+ return `the Sygnal MCP endpoint only answers requests from this machine (not ${remote || 'an unknown address'})`;
362
+ const host = req?.headers?.host;
363
+ if (typeof host !== 'string' || !host)
364
+ return 'missing Host header';
365
+ const h = hostname(host);
366
+ if (!isLocalName(h) && !inAllowed(h, allowedHosts))
367
+ return `Host ${host} is not a local name (add it to server.allowedHosts to allow it)`;
368
+ const origin = req?.headers?.origin;
369
+ if (origin !== undefined && origin !== 'null') {
370
+ let oh = '';
371
+ try {
372
+ oh = new URL(String(origin)).hostname.replace(/^\[|\]$/g, '').toLowerCase();
373
+ }
374
+ catch (_) { }
375
+ if (!oh || (!isLocalName(oh) && !inAllowed(oh, allowedHosts)))
376
+ return `Origin ${origin} is not allowed`;
377
+ }
378
+ else if (origin === 'null') {
379
+ return 'Origin null is not allowed';
380
+ }
381
+ return null;
382
+ }
383
+ // ---------------------------------------------------------------- HTTP
384
+ function send(res, status, body, headers = {}) {
385
+ res.statusCode = status;
386
+ for (const k in headers)
387
+ res.setHeader(k, headers[k]);
388
+ if (body === undefined)
389
+ return res.end();
390
+ res.setHeader('Content-Type', 'application/json');
391
+ res.end(JSON.stringify(body));
392
+ }
393
+ function readBody(req) {
394
+ return new Promise((resolve, reject) => {
395
+ let size = 0;
396
+ const chunks = [];
397
+ req.on('data', (c) => {
398
+ size += c.length;
399
+ if (size > MAX_BODY) {
400
+ reject(new Error('too large'));
401
+ req.destroy?.();
402
+ }
403
+ else
404
+ chunks.push(c);
405
+ });
406
+ req.on('end', () => resolve(globalThis.Buffer.concat(chunks).toString('utf8')));
407
+ req.on('error', reject);
408
+ });
409
+ }
410
+ /** An `Mcp-Name` value: plain, or the spec's `=?base64?…?=` sentinel for one that isn't header-safe */
411
+ function headerValue(v) {
412
+ const m = /^=\?base64\?(.*)\?=$/.exec(v);
413
+ return m ? globalThis.Buffer.from(m[1], 'base64').toString('utf8') : v;
414
+ }
415
+ /**
416
+ * G-655: why a 2026-07-28 request's envelope is refused, as [code, message], or null. The spec
417
+ * (basic/index "_meta", transports/streamable-http "Server Validation"): `_meta` must carry the
418
+ * protocol version and the client capabilities (-32602), and the MCP-Protocol-Version, Mcp-Method
419
+ * and (tools/call, resources/read, prompts/get) Mcp-Name headers must be there and match the body
420
+ * (-32020 HeaderMismatch). This server marks no parameter with `x-mcp-header`, so no
421
+ * Mcp-Param-* header is required.
422
+ */
423
+ function modernEnvelope(msg, headers) {
424
+ const params = isObj(msg.params) ? msg.params : {};
425
+ const meta = isObj(params._meta) ? params._meta : {};
426
+ if (typeof meta[META + 'protocolVersion'] !== 'string')
427
+ return [-32602, `Invalid params: _meta["${META}protocolVersion"] is required`];
428
+ if (!isObj(meta[META + 'clientCapabilities']))
429
+ return [-32602, `Invalid params: _meta["${META}clientCapabilities"] is required`];
430
+ const header = headers['mcp-protocol-version'];
431
+ if (header !== meta[META + 'protocolVersion']) {
432
+ return [-32020, header === undefined ? 'Header mismatch: MCP-Protocol-Version header is required' : `Header mismatch: MCP-Protocol-Version header value '${header}' does not match body value '${meta[META + 'protocolVersion']}'`];
433
+ }
434
+ const method = headers['mcp-method'];
435
+ if (method !== msg.method)
436
+ return [-32020, method === undefined ? 'Header mismatch: Mcp-Method header is required' : `Header mismatch: Mcp-Method header value '${method}' does not match body value '${msg.method}'`];
437
+ if (msg.method === 'tools/call' || msg.method === 'prompts/get' || msg.method === 'resources/read') {
438
+ const want = msg.method === 'resources/read' ? params.uri : params.name;
439
+ const name = headers['mcp-name'];
440
+ if (typeof name !== 'string')
441
+ return [-32020, 'Header mismatch: Mcp-Name header is required'];
442
+ if (headerValue(name) !== want)
443
+ return [-32020, `Header mismatch: Mcp-Name header value '${name}' does not match body value '${want}'`];
444
+ }
445
+ return null;
446
+ }
447
+ /** The connect middleware for MCP_PATH */
448
+ function mcpMiddleware(server, allowedHosts) {
449
+ return async (req, res, next) => {
450
+ const url = String(req.url || '').replace(/[?#].*$/, '');
451
+ if (url !== MCP_PATH && url !== MCP_PATH + '/')
452
+ return next();
453
+ const why = refusal(req, allowedHosts());
454
+ if (why)
455
+ return send(res, 403, { jsonrpc: '2.0', id: null, error: { code: -32000, message: `Forbidden: ${why}` } });
456
+ // G-638: no SSE stream on GET (the spec's "MUST ... return 405" for a server that offers none), no sessions to DELETE
457
+ if (req.method !== 'POST')
458
+ return send(res, 405, { jsonrpc: '2.0', id: null, error: { code: -32000, message: 'Method not allowed: this endpoint takes JSON-RPC over POST and answers with application/json (no SSE stream, no sessions)' } }, { Allow: 'POST' });
459
+ let msg;
460
+ try {
461
+ msg = JSON.parse(await readBody(req));
462
+ }
463
+ catch (err) {
464
+ if (err?.message === 'too large')
465
+ return send(res, 413, { jsonrpc: '2.0', id: null, error: { code: -32600, message: 'Request too large' } });
466
+ return send(res, 400, { jsonrpc: '2.0', id: null, error: { code: -32700, message: 'Parse error' } });
467
+ }
468
+ // G-655: the era is per request: a 2026-07-28 version in the header or in `_meta` is modern
469
+ // (stateless), anything else the initialize era (no header: 2025-03-26)
470
+ const id = isObj(msg) && 'id' in msg ? msg.id ?? null : null;
471
+ const fail = (status, code, message, data) => send(res, status, { jsonrpc: '2.0', id, error: { code, message, ...(data ? { data } : {}) } });
472
+ const header = req.headers['mcp-protocol-version'];
473
+ const meta = isObj(msg) && isObj(msg.params) && isObj(msg.params._meta) ? msg.params._meta : {};
474
+ const metaVersion = meta[META + 'protocolVersion'];
475
+ for (const requested of [header, metaVersion]) {
476
+ if (requested !== undefined && !SUPPORTED_VERSIONS.includes(requested)) {
477
+ return fail(400, -32022, 'Unsupported protocol version', { supported: SUPPORTED_VERSIONS, requested });
478
+ }
479
+ }
480
+ const modern = MODERN_VERSIONS.includes(header) || MODERN_VERSIONS.includes(metaVersion);
481
+ if (modern) {
482
+ if (!isObj(msg))
483
+ return fail(400, -32600, 'Invalid Request: one JSON-RPC message per POST');
484
+ if ('id' in msg && msg.id !== null) {
485
+ const why = modernEnvelope(msg, req.headers);
486
+ if (why)
487
+ return fail(400, why[0], why[1]);
488
+ }
489
+ }
490
+ const out = await server.handle(msg, modern);
491
+ if (out === null || out === undefined)
492
+ return send(res, 202);
493
+ // 2026-07-28: a method this server doesn't implement is 404 (the JSON-RPC body tells it from a missing endpoint)
494
+ send(res, modern && out.error?.code === -32601 ? 404 : 200, out);
495
+ };
496
+ }
497
+ // ---------------------------------------------------------------- the page bridge (Vite's HMR channel)
498
+ /** A PageBridge over the dev server's HMR channel (server.ws / environments.client.hot) */
499
+ function hmrBridge(server) {
500
+ const ws = server?.ws || server?.environments?.client?.hot;
501
+ const tabs = new Map();
502
+ const pending = new Map();
503
+ let nextTab = 1;
504
+ let nextReq = 1;
505
+ let clock = 0;
506
+ const fail = (client) => {
507
+ const t = tabs.get(client);
508
+ tabs.delete(client);
509
+ if (!t)
510
+ return;
511
+ for (const [id, p] of pending) {
512
+ if (p.client !== client)
513
+ continue;
514
+ clearTimeout(p.timer);
515
+ pending.delete(id);
516
+ p.reject(new ToolError(`tab ${t.id} closed before it answered`));
517
+ }
518
+ };
519
+ if (ws && typeof ws.on === 'function') {
520
+ ws.on(MCP_HELLO, (data, client) => {
521
+ if (!client)
522
+ return;
523
+ let t = tabs.get(client);
524
+ if (!t) {
525
+ tabs.set(client, t = { id: nextTab++, url: '', title: '', active: 0 });
526
+ // Vite's socket client carries its WebSocket: a closed tab leaves at once
527
+ try {
528
+ client.socket?.once?.('close', () => fail(client));
529
+ }
530
+ catch (_) { }
531
+ }
532
+ t.url = String(data?.url || '');
533
+ t.title = String(data?.title || '');
534
+ if (Array.isArray(data?.apps))
535
+ t.apps = data.apps.map((a) => ({ index: Number(a?.index), component: String(a?.component ?? '') }));
536
+ // an apps update (an HMR swap, a second run()) is not a focus
537
+ if (!data?.update || !t.active)
538
+ t.active = ++clock;
539
+ });
540
+ ws.on(MCP_RESPONSE, (data, client) => {
541
+ const p = data && pending.get(data.id);
542
+ if (!p || p.client !== client)
543
+ return;
544
+ if (data.waiting) {
545
+ clearTimeout(p.timer);
546
+ p.timer = setTimeout(() => expire(data.id), 5 * 60000);
547
+ return;
548
+ }
549
+ clearTimeout(p.timer);
550
+ pending.delete(data.id);
551
+ if (data.ok)
552
+ p.resolve(data.result);
553
+ else
554
+ p.reject(new ToolError(String(data.error || 'the page reported an error')));
555
+ });
556
+ }
557
+ /** tabs whose socket is still open (when the channel tells) */
558
+ const live = () => {
559
+ let open;
560
+ try {
561
+ open = ws?.clients;
562
+ }
563
+ catch (_) { }
564
+ for (const c of [...tabs.keys()]) {
565
+ const closed = c.socket && typeof c.socket.readyState === 'number' && c.socket.readyState > 1;
566
+ if (closed || (open instanceof Set && c.socket && !open.has(c)))
567
+ fail(c);
568
+ }
569
+ return tabs;
570
+ };
571
+ function expire(id) {
572
+ const p = pending.get(id);
573
+ if (!p)
574
+ return;
575
+ pending.delete(id);
576
+ p.reject(new ToolError(`tab ${p.tab} did not answer in time (is the page frozen, or a dialog open?)`));
577
+ }
578
+ return {
579
+ tabs: () => [...live().values()].map(t => ({ ...t, ...(t.apps ? { apps: t.apps.map(a => ({ ...a })) } : {}) })),
580
+ request(tabId, tool, args, ms) {
581
+ const client = [...live().entries()].find(([, t]) => t.id === tabId)?.[0];
582
+ if (!client)
583
+ return Promise.reject(new ToolError(`no tab ${tabId}`));
584
+ const id = nextReq++;
585
+ return new Promise((resolve, reject) => {
586
+ const timer = setTimeout(() => expire(id), ms);
587
+ pending.set(id, { tab: tabId, resolve, reject, timer, client });
588
+ try {
589
+ client.send({ type: 'custom', event: MCP_REQUEST, data: { id, tool, args } });
590
+ }
591
+ catch (err) {
592
+ clearTimeout(timer);
593
+ pending.delete(id);
594
+ fail(client);
595
+ reject(new ToolError(`tab ${tabId} is gone: ${err?.message || err}`));
596
+ }
597
+ });
598
+ },
599
+ };
600
+ }
601
+ /** Wire the endpoint into a Vite dev server */
602
+ function attachMcp(server, root, options, version) {
603
+ const bridge = hmrBridge(server);
604
+ const mcp = createDevMcpServer({
605
+ ...options,
606
+ bridge,
607
+ version,
608
+ check: loadCheckServer(root),
609
+ url: () => server?.resolvedUrls?.local?.[0],
610
+ });
611
+ server.middlewares.use(mcpMiddleware(mcp, () => server?.config?.server?.allowedHosts));
612
+ return mcp;
613
+ }
614
+ /** 'virtual:sygnal/mcp': connects the page (dev only) */
615
+ function mcpClientModule(options) {
616
+ const confirm = options.confirm === undefined ? 'page' : options.confirm;
617
+ return `import { agentTools } from 'sygnal';
618
+ import { installMcpBridge } from 'sygnal/devtools';
619
+ if (import.meta.hot) installMcpBridge(import.meta.hot, { agentTools, confirm: ${JSON.stringify(confirm)} });
620
+ `;
621
+ }
5
622
 
6
623
  /**
7
624
  * Sygnal Vite Plugin
@@ -17,7 +634,10 @@ import { pathToFileURL } from 'node:url';
17
634
  * What it does:
18
635
  * 1. Configures the automatic JSX transform with sygnal as the import source:
19
636
  * `oxc` (Vite 8), plus `esbuild` under Vite 7 and older
20
- * 2. Detects files that call `run()` from sygnal and auto-injects HMR wiring
637
+ * 2. Detects files that call `run()` from sygnal and auto-injects HMR wiring.
638
+ * A module that calls `defineElement()` from 'sygnal/element' at the top level
639
+ * (and doesn't import run()) gets `if (import.meta.hot) import.meta.hot.accept()`
640
+ * appended: re-running it swaps the elements' component, keeping their state
21
641
  * 3. Dev mode (`vite` / `vite dev` only; never `vite build`). Into every
22
642
  * file that imports `run` from sygnal (including entries with manual HMR
23
643
  * wiring or `disableHmr`) it inserts, on an existing line:
@@ -53,9 +673,14 @@ import { pathToFileURL } from 'node:url';
53
673
  * current findings when the page loads ('sygnal:check:request'), and only
54
674
  * that client is answered; after a source change the new findings go to
55
675
  * every connected client, and only when they changed. Error-severity
56
- * findings also open Vite's error overlay (`overlay: false`: never).
57
- * sygnal-check's codes are currently all warnings or info, so in practice
58
- * everything goes to the console. Warnings never use the overlay: while
676
+ * findings also open Vite's error overlay (`overlay: false`: never):
677
+ * SYG112, SYG124, SYG125, SYG128, SYG405 and the checker's other
678
+ * error-severity codes. The a11y lane SYG701-708 is a warning, also
679
+ * under `diagnostics.strict` (D144, amending D111); `check.a11y: 'error'`
680
+ * makes it an error (and opens the overlay). Without that opt-in a 7xx
681
+ * finding never opens the overlay, even from an older sygnal-check that
682
+ * reports it as an error under strict. Everything else is a warning or
683
+ * info and goes to the console. Warnings never use the overlay: while
59
684
  * one is open Vite's client reloads the page on the next HMR update
60
685
  * (`overlay: 'warn'` is treated as 'error', with a notice). The dev
61
686
  * client closes a sygnal-check overlay before each update, and the
@@ -76,13 +701,35 @@ import { pathToFileURL } from 'node:url';
76
701
  * 7. Vike and Astro (G-014): the app is started by sygnal's own client
77
702
  * entry, which user code doesn't import. Client-side imports of
78
703
  * 'sygnal/vike/onRenderClient' resolve to a dev wrapper that sets the
79
- * flag and loads the checks first. Astro resolves its renderer entry on
704
+ * flag and loads the checks first. That entry is excluded from
705
+ * pre-bundling in dev (B-020), so it shares the pages' core. Astro resolves its renderer entry on
80
706
  * the server and the browser loads the file itself, so the same snippet
81
707
  * is added to sygnal's 'astro/client' file by the transform. That file
82
708
  * imports the public 'sygnal' entry (one shared core, B-019), so its
83
709
  * 'sygnal' import gets the run() wrapper too: every `diagnostics` mode
84
710
  * and ignore list works for islands. The sygnal/astro integration adds
85
711
  * this plugin in `astro dev`.
712
+ * 8. `nativeGlobalThis` (G-099, default true): a `resolve.alias` from
713
+ * `globalthis` (xstream's `require('globalthis').getPolyfill()`) to the
714
+ * package's dist/shims/globalthis.cjs, which returns the native
715
+ * globalThis. Drops the polyfill chain (~4 KB gzip) from every bundle,
716
+ * in dev (including pre-bundling), build and Vitest. Dependencies left
717
+ * external (SSR, Vitest) still load the real package from Node. The
718
+ * sygnal/astro integration adds the same alias in `astro build`. Any
719
+ * dependency's `require('globalthis')` gets the stub; a `globalthis`
720
+ * entry in the user's own `resolve.alias` wins (R2-7).
721
+ * 9. `devtools` option (D77, default true): in dev the same files (run()
722
+ * importers, the Vike wrapper, the Astro client) also get
723
+ * `import 'sygnal/devtools';`, first, which installs the DevTools bridge
724
+ * (window.__SYGNAL_DEVTOOLS__) for the browser extension. Independent of
725
+ * `diagnostics` ('off' still injects it). Never in `vite build` or under
726
+ * Vitest: production builds carry no DevTools code. `devtools: false`
727
+ * injects nothing. PLAN-4 3-E: `devtools: { redux: true }` also calls
728
+ * connectReduxDevtools() (actions + state to the Redux DevTools extension).
729
+ * 10. `mcp` option (PLAN-6 E-1, default false): the dev server serves an MCP endpoint at
730
+ * /__sygnal/mcp (./mcp.ts: streamable HTTP, loopback / local Host / local Origin only)
731
+ * and the dev entries also import 'virtual:sygnal/mcp', which connects the page over the
732
+ * HMR channel (installMcpBridge from 'sygnal/devtools'). Never in `vite build` or Vitest.
86
733
  *
87
734
  * Why not Vite's `define`? Vite's dependency optimizer does not apply user
88
735
  * `define` replacements to pre-bundled dependencies (only process.env.NODE_ENV),
@@ -123,11 +770,14 @@ const CHECK_EVENT = 'sygnal:check';
123
770
  // Sent by the dev client when it loads: the server answers that client only
124
771
  const CHECK_REQUEST = 'sygnal:check:request';
125
772
  const OVERLAY_PLUGIN = 'sygnal-check';
773
+ // PLAN-6 E-1: the page side of the dev MCP endpoint
774
+ const MCP_CLIENT = 'virtual:sygnal/mcp';
775
+ const MCP_CLIENT_ID = '\0' + MCP_CLIENT;
126
776
  // Register the runtime checks with the core that loaded last (see the Vike wrapper)
127
777
  const REINSTALL_IMPORT = `import { installChecks as __sygnalInstallChecks } from 'sygnal/diagnostics';`;
128
778
  const REINSTALL_CALL = 'try { __sygnalInstallChecks() } catch (e) { console.warn(e) }\n';
129
779
  function sygnal(options = {}) {
130
- const { disableJsx = false, disableHmr = false, vitestSetup = true } = options;
780
+ const { disableJsx = false, disableHmr = false, vitestSetup = true, nativeGlobalThis = true } = options;
131
781
  const diagnostics = normalizeDiagnostics(options.diagnostics);
132
782
  const devOn = diagnostics.mode !== 'off';
133
783
  // A mode other than the flag's 'warn', or an ignore list, needs run()'s option
@@ -140,6 +790,18 @@ function sygnal(options = {}) {
140
790
  // Statements run before the app starts: dev flag (+ strict flag)
141
791
  const flags = DEV_FLAG + (diagnostics.strict ? STRICT_FLAG : '');
142
792
  const devImports = `import 'sygnal/diagnostics';import '${DEV_CLIENT}';`;
793
+ // D77: the DevTools bridge, dev only. First, so the diagnostics entry finds it.
794
+ // E-1: the MCP endpoint needs the bridge, so `mcp` turns it on
795
+ const mcpOn = !!options.mcp;
796
+ const mcpOptions = typeof options.mcp === 'object' && options.mcp ? options.mcp : {};
797
+ const devtoolsOn = options.devtools !== false || mcpOn;
798
+ const redux = typeof options.devtools == 'object' && !!options.devtools?.redux;
799
+ const devtoolsImport = (!devtoolsOn ? ''
800
+ : redux ? `import { connectReduxDevtools as __sygnalReduxDevtools } from 'sygnal/devtools';__sygnalReduxDevtools();`
801
+ : `import 'sygnal/devtools';`) + (mcpOn ? `import '${MCP_CLIENT}';` : '');
802
+ // What a dev entry gets: DevTools, then (unless diagnostics are 'off') flags + checks
803
+ const devSnippet = devtoolsImport + (devOn ? flags + devImports : '');
804
+ const devInject = devOn || devtoolsOn;
143
805
  let astroClient;
144
806
  return {
145
807
  name: 'vite-plugin-sygnal',
@@ -155,6 +817,12 @@ function sygnal(options = {}) {
155
817
  noExternal: ['sygnal'],
156
818
  },
157
819
  };
820
+ // G-099: xstream's `require('globalthis')` gets the native-globalThis
821
+ // stub. An alias (not resolveId) so it also applies to pre-bundling.
822
+ // R2-7: not when the user's config already aliases `globalthis`.
823
+ const alias = nativeGlobalThis ? globalThisAlias(config?.resolve?.alias) : [];
824
+ if (alias.length)
825
+ result.resolve = { alias };
158
826
  if (!disableJsx) {
159
827
  result.oxc = {
160
828
  jsx: {
@@ -186,13 +854,31 @@ function sygnal(options = {}) {
186
854
  result.test = { setupFiles: [setup] };
187
855
  }
188
856
  }
189
- else if (isServe && devOn && sygnalInNodeModules(root)) {
857
+ else if (isServe && devInject && sygnalInNodeModules(root)) {
190
858
  // The dependency scan reads the original sources, which don't import
191
- // the checks entry: pre-bundle it with sygnal so the first page load
192
- // doesn't trigger a re-optimization. Only for an installed sygnal: a
193
- // linked one is served from source, and pre-bundling the checks alone
194
- // would give them their own copy of the core.
195
- result.optimizeDeps = { ...result.optimizeDeps, include: ['sygnal/diagnostics'] };
859
+ // the checks (or DevTools) entry: pre-bundle it with sygnal so the first
860
+ // page load doesn't trigger a re-optimization. Only for an installed
861
+ // sygnal: a linked one is served from source, and pre-bundling the
862
+ // checks alone would give them their own copy of the core.
863
+ const include = [...(devtoolsOn ? ['sygnal/devtools'] : []), ...(devOn ? ['sygnal/diagnostics'] : [])];
864
+ result.optimizeDeps = { ...result.optimizeDeps, include };
865
+ }
866
+ // B-020: Vike adds its client entry 'sygnal/vike/onRenderClient' to
867
+ // optimizeDeps.include. With a linked sygnal, the pages' 'sygnal' is
868
+ // served from source while that pre-bundle inlines a second copy of the
869
+ // core. Unbundled, the entry's own `import 'sygnal'` resolves like the
870
+ // pages' imports (source when linked, the shared pre-bundle when
871
+ // installed): one core. Vike honours the exclude list.
872
+ // G-098: Vite doesn't discover the imports of an excluded dependency, so for an
873
+ // installed sygnal 'sygnal' is pre-bundled up front (pages that reach it only through
874
+ // the JSX runtime would otherwise get it, and its CommonJS xstream, unbundled).
875
+ if (isServe && !isVitest) {
876
+ const include = result.optimizeDeps?.include || [];
877
+ result.optimizeDeps = {
878
+ ...result.optimizeDeps,
879
+ exclude: [VIKE_CLIENT],
880
+ ...(sygnalInNodeModules(root) ? { include: [...include, 'sygnal'] } : {}),
881
+ };
196
882
  }
197
883
  return result;
198
884
  },
@@ -225,10 +911,12 @@ function sygnal(options = {}) {
225
911
  return null;
226
912
  if (source === DEV_CLIENT)
227
913
  return DEV_CLIENT_ID;
914
+ if (source === MCP_CLIENT && mcpOn)
915
+ return MCP_CLIENT_ID;
228
916
  if (source === 'sygnal' && importer && wrapRun && runtimeImporters.has(cleanId(importer))) {
229
917
  return RUNTIME_ID;
230
918
  }
231
- if (source === VIKE_CLIENT && devOn && !opts?.ssr) {
919
+ if (source === VIKE_CLIENT && devInject && !opts?.ssr) {
232
920
  if (importer !== VIKE_CLIENT_ID)
233
921
  return VIKE_CLIENT_ID;
234
922
  // The wrapper's own import of the real entry: resolve it normally.
@@ -245,18 +933,28 @@ function sygnal(options = {}) {
245
933
  load(id) {
246
934
  if (id === DEV_CLIENT_ID)
247
935
  return devClientModule();
936
+ if (id === MCP_CLIENT_ID && mcpOn)
937
+ return mcpClientModule(mcpOptions);
248
938
  if (id === RUNTIME_ID)
249
939
  return runtimeModule(diagnostics);
250
940
  // The checks register again once the real entry has loaded: a
251
941
  // pre-bundled copy of it can carry its own copy of the Sygnal core
252
942
  // (e.g. with a linked sygnal), which then holds the diagnostics bridge.
253
943
  if (id === VIKE_CLIENT_ID) {
254
- return `${devImports}${REINSTALL_IMPORT}\nexport * from '${VIKE_CLIENT}';\n${flags}\n${REINSTALL_CALL}`;
944
+ if (!devOn)
945
+ return `${devtoolsImport}\nexport * from '${VIKE_CLIENT}';\n`;
946
+ return `${devtoolsImport}${devImports}${REINSTALL_IMPORT}\nexport * from '${VIKE_CLIENT}';\n${flags}\n${REINSTALL_CALL}`;
255
947
  }
256
948
  return null;
257
949
  },
258
950
  configureServer(server) {
259
- if (isVitest || options.check === false)
951
+ if (isVitest)
952
+ return;
953
+ // E-1: the MCP endpoint (a middleware ahead of Vite's own; it does its own host checks)
954
+ if (mcpOn && server?.middlewares) {
955
+ attachMcp(server, root, mcpOptions, sygnalVersion(root));
956
+ }
957
+ if (options.check === false)
260
958
  return;
261
959
  const checkOptions = typeof options.check === 'object' && options.check ? options.check : {};
262
960
  // Deferred: the dev server doesn't wait for the first check
@@ -267,84 +965,176 @@ function sygnal(options = {}) {
267
965
  }, 0);
268
966
  },
269
967
  transform(code, id, opts) {
270
- if (!isServe)
271
- return null;
272
- // sygnal/astro/client (Astro islands): flags + checks first. It imports
273
- // the public 'sygnal' entry (the app's core, B-019), which resolves to
274
- // the run() wrapper when the diagnostics option needs it.
275
- if (devOn && !isVitest && !opts?.ssr) {
276
- astroClient = astroClient || astroClientFiles(root);
277
- if (astroClient.has(cleanId(id))) {
278
- if (wrapRun)
279
- runtimeImporters.add(cleanId(id));
280
- return withSourcemap(code, [[0, flags + devImports]], '', id);
281
- }
282
- }
283
- // Only transform JS/TS/JSX/TSX files
284
- if (!/\.[jt]sx?$/.test(id))
285
- return null;
286
- // Skip node_modules
287
- if (id.includes('node_modules'))
288
- return null;
289
- // Must import run from sygnal
290
- if (!code.includes('sygnal'))
291
- return null;
292
- // Match against the code with comments blanked out (same offsets), so
293
- // e.g. `// run(App)` or a commented-out import is never matched.
294
- const noComments = blankOut(code, false);
295
- // Find: import { run, ... } from 'sygnal'
296
- const runImportRe = /import\s+\{[^}]*\brun\b[^}]*\}\s+from\s+['"]sygnal['"]/;
297
- if (!runImportRe.test(noComments))
298
- return null;
299
- // Dev snippet: injected into every file that imports run() — also when
300
- // HMR wiring below is skipped. Inserted after any shebang line and
301
- // directive prologue, without adding a line. Nothing under Vitest: a
302
- // global flag set by one test file would leak dev/strict mode into the
303
- // later test files of the same worker; there the checks come from
304
- // test.setupFiles and renderComponent() manages the modes.
305
- const inserts = [];
306
- if (devOn && !isVitest) {
307
- inserts.push(flagInsertion(code, flags + devImports));
968
+ // SYG666 (PLAN-5 W-2): an adapter entry imported without its optional peers; every mode
969
+ const adapters = adapterImports(this, code, id);
970
+ if (adapters)
971
+ return checkPeers(this, adapters, id).then(() => devTransform.call(this, code, id, opts));
972
+ return devTransform.call(this, code, id, opts);
973
+ },
974
+ };
975
+ function devTransform(code, id, opts) {
976
+ if (!isServe)
977
+ return null;
978
+ // sygnal/astro/client (Astro islands): flags + checks first. It imports
979
+ // the public 'sygnal' entry (the app's core, B-019), which resolves to
980
+ // the run() wrapper when the diagnostics option needs it.
981
+ if (devInject && !isVitest && !opts?.ssr) {
982
+ astroClient = astroClient || astroClientFiles(root);
983
+ if (astroClient.has(cleanId(id))) {
308
984
  if (wrapRun)
309
985
  runtimeImporters.add(cleanId(id));
986
+ return withSourcemap(code, [[0, devSnippet]], '', id);
310
987
  }
311
- const done = (tail = '') => (inserts.length || tail ? withSourcemap(code, inserts, tail, id) : null);
312
- // Skip HMR wiring if disabled, in tests, or already manually wired
313
- if (disableHmr || isVitest || /\.(test|spec)\.[jt]sx?$/.test(id))
314
- return done();
315
- if (noComments.includes('import.meta.hot'))
316
- return done();
317
- // Strings and template literals blanked out too: a statement-level match only
318
- const runCall = RUN_CALL_RE.exec(blankOut(code, true));
319
- if (!runCall)
320
- return done();
321
- const [, binding, componentName] = runCall;
322
- // Find the import path for this component
323
- // Handles: import App from './App.jsx'
324
- // import App from "./App"
325
- const componentImportRe = new RegExp(`import\\s+${componentName.replace(/\$/g, '\\$')}\\s+from\\s+['"]([^'"]+)['"]`);
326
- const componentImportMatch = noComments.match(componentImportRe);
327
- if (!componentImportMatch)
328
- return done();
329
- const componentPath = componentImportMatch[1];
330
- // Pattern 3: bare run(App, ...) — no result captured → const __sygnal = run(
331
- if (!binding) {
332
- inserts.push([runCall.index, 'const __sygnal = ']);
333
- return done(hmrBlock(componentPath, '__sygnal.hmr', '__sygnal.dispose'));
334
- }
335
- // Pattern 2: const app = run(App, ...)
336
- if (binding[0] !== '{') {
337
- return done(hmrBlock(componentPath, `${binding}.hmr`, `${binding}.dispose`));
988
+ }
989
+ // Only transform JS/TS/JSX/TSX files
990
+ if (!/\.[jt]sx?$/.test(id))
991
+ return null;
992
+ // Skip node_modules
993
+ if (id.includes('node_modules'))
994
+ return null;
995
+ // Must import run from sygnal
996
+ if (!code.includes('sygnal'))
997
+ return null;
998
+ // Match against the code with comments blanked out (same offsets), so
999
+ // e.g. `// run(App)` or a commented-out import is never matched.
1000
+ const noComments = blankOut(code, false);
1001
+ // Find: import { run, ... } from 'sygnal'
1002
+ const runImportRe = /import\s+\{[^}]*\brun\b[^}]*\}\s+from\s+['"]sygnal['"]/;
1003
+ if (!runImportRe.test(noComments)) {
1004
+ return disableHmr || isVitest ? null : elementHmr(code, noComments, id);
1005
+ }
1006
+ // Dev snippet: injected into every file that imports run() — also when
1007
+ // HMR wiring below is skipped. Inserted after any shebang line and
1008
+ // directive prologue, without adding a line. Nothing under Vitest: a
1009
+ // global flag set by one test file would leak dev/strict mode into the
1010
+ // later test files of the same worker; there the checks come from
1011
+ // test.setupFiles and renderComponent() manages the modes.
1012
+ const inserts = [];
1013
+ if (devInject && !isVitest) {
1014
+ inserts.push(flagInsertion(code, devSnippet));
1015
+ if (wrapRun)
1016
+ runtimeImporters.add(cleanId(id));
1017
+ }
1018
+ const done = (tail = '') => (inserts.length || tail ? withSourcemap(code, inserts, tail, id) : null);
1019
+ // Skip HMR wiring if disabled, in tests, or already manually wired
1020
+ if (disableHmr || isVitest || /\.(test|spec)\.[jt]sx?$/.test(id))
1021
+ return done();
1022
+ if (noComments.includes('import.meta.hot'))
1023
+ return done();
1024
+ // Strings and template literals blanked out too: a statement-level match only
1025
+ const runCall = RUN_CALL_RE.exec(blankOut(code, true));
1026
+ if (!runCall)
1027
+ return done();
1028
+ const [, binding, componentName] = runCall;
1029
+ // Find the import path for this component
1030
+ // Handles: import App from './App.jsx'
1031
+ // import App from "./App"
1032
+ const componentImportRe = new RegExp(`import\\s+${componentName.replace(/\$/g, '\\$')}\\s+from\\s+['"]([^'"]+)['"]`);
1033
+ const componentImportMatch = noComments.match(componentImportRe);
1034
+ if (!componentImportMatch)
1035
+ return done();
1036
+ const componentPath = componentImportMatch[1];
1037
+ // Pattern 3: bare run(App, ...) — no result captured → const __sygnal = run(
1038
+ if (!binding) {
1039
+ inserts.push([runCall.index, 'const __sygnal = ']);
1040
+ return done(hmrBlock(componentPath, '__sygnal.hmr', '__sygnal.dispose'));
1041
+ }
1042
+ // Pattern 2: const app = run(App, ...)
1043
+ if (binding[0] !== '{') {
1044
+ return done(hmrBlock(componentPath, `${binding}.hmr`, `${binding}.dispose`));
1045
+ }
1046
+ // Pattern 1: const { hmr, dispose, ... } = run(App, ...) — only when both
1047
+ // are bound under their own names (a rename would leave them undefined)
1048
+ const names = binding.slice(1, -1).split(',').map(s => s.trim());
1049
+ if (names.includes('hmr') && names.includes('dispose')) {
1050
+ return done(hmrBlock(componentPath, 'hmr', 'dispose'));
1051
+ }
1052
+ return done();
1053
+ }
1054
+ }
1055
+ // PLAN-5 W-2 (D209): the adapter entries and the optional peer dependencies each one imports
1056
+ // (the Zag packages pinned together: they depend on each other's exact versions)
1057
+ const ZAG = '~1.45.0';
1058
+ const ADAPTER_PEERS = {
1059
+ react: ['react', 'react-dom'],
1060
+ zag: ['@zag-js/vanilla'],
1061
+ // D211: one subpath per Zag part, each needing only its own machine
1062
+ 'ui/menu': ['@zag-js/vanilla', '@zag-js/menu'],
1063
+ 'ui/select': ['@zag-js/vanilla', '@zag-js/select'],
1064
+ 'ui/combobox': ['@zag-js/vanilla', '@zag-js/combobox'],
1065
+ };
1066
+ // G-440: a dynamic import's specifier may be a template literal without substitutions
1067
+ const ADAPTER_RE = /(?:\bfrom|\bimport)\s*\(?\s*(['"`])sygnal\/(react|zag|ui\/(?:menu|select|combobox))\1/g;
1068
+ const ADAPTER_ID = /^sygnal\/(react|zag|ui\/(?:menu|select|combobox))$/;
1069
+ /**
1070
+ * The adapter entries an app module imports (statically, dynamically or in a re-export), or null.
1071
+ * G-415: real imports only. The module's AST from the plugin context's parse() (Vite and Rollup
1072
+ * provide it; the code is plain JS by then); when there is none, or the code doesn't parse, a
1073
+ * scan of the code with comments blanked whose `from` / `import` keyword isn't inside a string
1074
+ * or template literal. A literal that mentions an entry (a docs snippet) is never an import.
1075
+ */
1076
+ function adapterImports(ctx, code, id) {
1077
+ if (!code.includes('sygnal/') || id.includes('node_modules') || !/\.[cm]?[jt]sx?$/.test(cleanId(id)))
1078
+ return null;
1079
+ const noComments = blankOut(code, false);
1080
+ if (!ADAPTER_RE.test(noComments))
1081
+ return null;
1082
+ ADAPTER_RE.lastIndex = 0;
1083
+ const found = new Set();
1084
+ let ast = null;
1085
+ try {
1086
+ ast = typeof ctx?.parse == 'function' ? ctx.parse(code) : null;
1087
+ }
1088
+ catch (_) { }
1089
+ if (ast) {
1090
+ const walk = (n) => {
1091
+ if (!n || typeof n != 'object')
1092
+ return;
1093
+ if (Array.isArray(n))
1094
+ return n.forEach(walk);
1095
+ if (/^(Import|Export(Named|All))Declaration$|^ImportExpression$/.test(n.type)) {
1096
+ // G-440: import(`sygnal/zag`): a template literal without substitutions is a known specifier
1097
+ const src = n.source, q = src?.type == 'TemplateLiteral' && !src.expressions?.length ? src.quasis?.[0]?.value?.cooked : src?.value;
1098
+ const m = ADAPTER_ID.exec(q ?? '');
1099
+ if (m)
1100
+ found.add(m[1]);
338
1101
  }
339
- // Pattern 1: const { hmr, dispose, ... } = run(App, ...) — only when both
340
- // are bound under their own names (a rename would leave them undefined)
341
- const names = binding.slice(1, -1).split(',').map(s => s.trim());
342
- if (names.includes('hmr') && names.includes('dispose')) {
343
- return done(hmrBlock(componentPath, 'hmr', 'dispose'));
1102
+ for (const k in n)
1103
+ if (k != 'type' && typeof n[k] == 'object')
1104
+ walk(n[k]);
1105
+ };
1106
+ walk(ast);
1107
+ }
1108
+ else {
1109
+ // strings and templates blanked too: a keyword there is text, not an import
1110
+ const noStrings = blankOut(code, true);
1111
+ for (const m of noComments.matchAll(ADAPTER_RE)) {
1112
+ if (noStrings.startsWith(m[0].slice(0, m[0][0] == 'f' ? 4 : 6), m.index))
1113
+ found.add(m[2]);
1114
+ }
1115
+ }
1116
+ return found.size ? [...found] : null;
1117
+ }
1118
+ /** SYG666: resolves each entry's peers from the importing module; reports the missing ones */
1119
+ async function checkPeers(ctx, entries, id) {
1120
+ for (const e of entries) {
1121
+ const missing = [];
1122
+ for (const peer of ADAPTER_PEERS[e]) {
1123
+ let r = null;
1124
+ try {
1125
+ r = await ctx.resolve(peer, id, { skipSelf: true });
344
1126
  }
345
- return done();
346
- },
347
- };
1127
+ catch (_) { }
1128
+ if (!r)
1129
+ missing.push(peer);
1130
+ }
1131
+ if (!missing.length)
1132
+ continue;
1133
+ const install = missing.map(m => (m.startsWith('@zag-js/') ? `${m}@${ZAG}` : m)).join(' ');
1134
+ ctx.error(`[Sygnal SYG666] 'sygnal/${e}' needs ${missing.join(', ')}, which ${missing.length > 1 ? "aren't" : "isn't"} installed: npm install ${install}.` +
1135
+ (e == 'react' ? " (For Preact: alias react, react-dom and react-dom/client to preact/compat.)" : '') +
1136
+ ' https://sygnal.js.org/reference/errors#syg666');
1137
+ }
348
1138
  }
349
1139
  /**
350
1140
  * Major version of the running Vite: from the plugin context (this.meta,
@@ -439,6 +1229,16 @@ function sygnalPackageDir(root) {
439
1229
  catch (_) { }
440
1230
  return undefined;
441
1231
  }
1232
+ /** The version of the 'sygnal' package the project resolves */
1233
+ function sygnalVersion(root) {
1234
+ const dir = sygnalPackageDir(root);
1235
+ try {
1236
+ return dir ? JSON.parse(fs.readFileSync(path.join(dir, 'package.json'), 'utf8')).version : undefined;
1237
+ }
1238
+ catch (_) {
1239
+ return undefined;
1240
+ }
1241
+ }
442
1242
  /** Real paths of sygnal's 'astro/client' ESM file. */
443
1243
  function astroClientFiles(root) {
444
1244
  const files = new Set();
@@ -547,6 +1347,8 @@ async function startChecker(server, root, opts, defaults, explicit) {
547
1347
  const include = checkInclude(root, opts.include, (m) => logger.info(m));
548
1348
  const ignore = opts.ignore || defaults.ignore;
549
1349
  const strict = opts.strict === undefined ? defaults.strict : !!opts.strict;
1350
+ // D144: the a11y lane is a warning unless asked for as an error, under strict too
1351
+ const a11y = opts.a11y === 'error' ? 'error' : 'warn';
550
1352
  // Only error-severity findings open Vite's overlay: while an overlay is open
551
1353
  // Vite's client reloads the page on the first HMR update, so warnings stay
552
1354
  // in the terminal and the browser console. overlay: 'warn' is treated as
@@ -577,12 +1379,16 @@ async function startChecker(server, root, opts, defaults, explicit) {
577
1379
  const run = (initial = false) => {
578
1380
  let diags;
579
1381
  try {
580
- diags = mod.check(include, { cwd: root, strict, ignore });
1382
+ diags = mod.check(include, { cwd: root, strict, ignore, a11y });
581
1383
  }
582
1384
  catch (err) {
583
1385
  logger.warn(`[sygnal] sygnal-check failed: ${err?.message || err}`, { timestamp: true });
584
1386
  return;
585
1387
  }
1388
+ // A sygnal-check from before D144 reports SYG7xx as errors under strict: keep them warnings
1389
+ if (a11y !== 'error') {
1390
+ diags = diags.map(d => d && d.severity === 'error' && /^SYG7\d\d$/.test(d.code) ? { ...d, severity: 'warn' } : d);
1391
+ }
586
1392
  const shown = diags.filter(d => d.severity !== 'info');
587
1393
  const lines = shown.map(formatLine);
588
1394
  const key = lines.join('\n');
@@ -735,6 +1541,29 @@ function withSourcemap(code, inserts, tail, id) {
735
1541
  map: { version: 3, sources: [id], sourcesContent: [code], names: [], mappings },
736
1542
  };
737
1543
  }
1544
+ // A top-level (column 0) defineElement(...) call, as a statement or a declaration's value
1545
+ const DEFINE_ELEMENT_CALL_RE = /^(?:(?:export\s+)?(?:const|let|var)\s+[\w$]+\s*=\s*)?defineElement\s*\(/m;
1546
+ const ELEMENT_IMPORT_RE = /import\s+\{[^}]*\bdefineElement\b[^}]*\}\s+from\s+['"]sygnal\/element['"]/;
1547
+ /**
1548
+ * PLAN-4 GS-13: a module that defines custom elements with 'sygnal/element' accepts its own
1549
+ * hot updates. Re-running it calls defineElement again for the same tags, which swaps the
1550
+ * component in every live element and keeps each one's state; an edited component module it
1551
+ * imports reaches it the same way. Only for a top-level defineElement call, outside test
1552
+ * files, when the module has no HMR code of its own and doesn't import run() (an entry's
1553
+ * run() wiring decides there).
1554
+ */
1555
+ function elementHmr(code, noComments, id) {
1556
+ if (/\.(test|spec)\.[jt]sx?$/.test(id))
1557
+ return null;
1558
+ if (!ELEMENT_IMPORT_RE.test(noComments) || noComments.includes('import.meta.hot'))
1559
+ return null;
1560
+ if (!DEFINE_ELEMENT_CALL_RE.test(blankOut(code, true)))
1561
+ return null;
1562
+ return withSourcemap(code, [], ELEMENT_HMR_BLOCK, id);
1563
+ }
1564
+ const ELEMENT_HMR_BLOCK = `
1565
+ if (import.meta.hot) import.meta.hot.accept()
1566
+ `;
738
1567
  function hmrBlock(componentPath, hmrRef, disposeRef) {
739
1568
  return `
740
1569
  if (import.meta.hot) {
@@ -745,11 +1574,32 @@ if (import.meta.hot) {
745
1574
  }
746
1575
 
747
1576
  const SYGNAL_RENDERER_NAME = '@sygnal/astro';
1577
+ // PLAN-4 GS-11 / D120: both island entries import this; it re-exports the default export of the
1578
+ // module the `onError` option names (undefined without it)
1579
+ const ON_ERROR_ID = 'virtual:sygnal/astro-on-error';
1580
+ /** The Vite plugin serving ON_ERROR_ID; `file` is absolute (undefined: no hook) */
1581
+ function onErrorPlugin(file) {
1582
+ return {
1583
+ name: 'sygnal:astro-on-error',
1584
+ resolveId: (id) => id === ON_ERROR_ID ? '\0' + ON_ERROR_ID : undefined,
1585
+ load: (id) => id === '\0' + ON_ERROR_ID
1586
+ ? (file ? `export { default } from ${JSON.stringify(file)}` : 'export default undefined')
1587
+ : undefined,
1588
+ // Vite 6+ (Astro 6 renders in its own 'prerender' / 'ssr' environments): the island server
1589
+ // entry imports the virtual module, so Vite must load it (not Node). `ssr.noExternal`
1590
+ // below covers the 'ssr' environment and older Vite
1591
+ configEnvironment: (name) => name === 'client' ? undefined : { resolve: { noExternal: ['sygnal'] } },
1592
+ };
1593
+ }
1594
+ /** The project root as a directory path (Astro gives a file: URL) */
1595
+ const rootDir = (root) =>
1596
+ // @ts-ignore — Node's process
1597
+ !root ? process.cwd() : typeof root === 'string' ? root : fileURLToPath(root);
748
1598
  function sygnalAstroIntegration(options = {}) {
749
1599
  return {
750
1600
  name: SYGNAL_RENDERER_NAME,
751
1601
  hooks: {
752
- 'astro:config:setup': ({ addRenderer, updateConfig, command }) => {
1602
+ 'astro:config:setup': ({ addRenderer, updateConfig, command, config }) => {
753
1603
  addRenderer({
754
1604
  name: SYGNAL_RENDERER_NAME,
755
1605
  clientEntrypoint: 'sygnal/astro/client',
@@ -760,11 +1610,16 @@ function sygnalAstroIntegration(options = {}) {
760
1610
  jsx: 'automatic',
761
1611
  jsxImportSource: 'sygnal',
762
1612
  },
1613
+ // D120: the island entries import the virtual onError module, so they stay on Vite:
1614
+ // not pre-bundled with it, and not externalized (loaded by Node) during SSR
1615
+ optimizeDeps: { exclude: [ON_ERROR_ID] },
1616
+ ssr: { noExternal: ['sygnal'] },
763
1617
  };
1618
+ const hook = options.onError ? path.resolve(rootDir(config?.root), options.onError) : undefined;
764
1619
  // Dev mode (G-014): islands are started by sygnal/astro/client, which
765
1620
  // user code never imports, so the sygnal Vite plugin wraps that entry
766
- // in dev to set the dev flag and load the runtime checks first. It
767
- // also runs sygnal-check. Nothing is added to `astro build`.
1621
+ // in dev to install DevTools, set the dev flag and load the runtime checks first. It
1622
+ // also runs sygnal-check. `astro build` only gets the `globalthis` alias.
768
1623
  if (command === 'dev') {
769
1624
  vite.plugins = [sygnal({
770
1625
  disableJsx: true,
@@ -772,8 +1627,18 @@ function sygnalAstroIntegration(options = {}) {
772
1627
  vitestSetup: false,
773
1628
  diagnostics: options.diagnostics,
774
1629
  check: options.check,
1630
+ nativeGlobalThis: options.nativeGlobalThis,
1631
+ devtools: options.devtools,
775
1632
  })];
776
1633
  }
1634
+ else if (options.nativeGlobalThis !== false) {
1635
+ // G-099: the same `globalthis` alias the plugin adds in dev (R2-7: unless the
1636
+ // user's vite config already aliases `globalthis`)
1637
+ const alias = globalThisAlias(config?.vite?.resolve?.alias);
1638
+ if (alias.length)
1639
+ vite.resolve = { alias };
1640
+ }
1641
+ vite.plugins = [...(vite.plugins || []), onErrorPlugin(hook)];
777
1642
  updateConfig({ vite });
778
1643
  },
779
1644
  },