sygnal 5.3.6 → 5.4.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 (226) hide show
  1. package/README.md +53 -38
  2. package/dist/astro/client.cjs.js +18 -8106
  3. package/dist/astro/client.cjs.js.map +1 -0
  4. package/dist/astro/client.mjs +17 -8105
  5. package/dist/astro/client.mjs.map +1 -0
  6. package/dist/astro/index.cjs.js +768 -9
  7. package/dist/astro/index.cjs.js.map +1 -0
  8. package/dist/astro/index.mjs +768 -9
  9. package/dist/astro/index.mjs.map +1 -0
  10. package/dist/astro/server.cjs.js +4 -1
  11. package/dist/astro/server.cjs.js.map +1 -0
  12. package/dist/astro/server.mjs +4 -1
  13. package/dist/astro/server.mjs.map +1 -0
  14. package/dist/diagnostics.cjs.js +1297 -0
  15. package/dist/diagnostics.cjs.js.map +1 -0
  16. package/dist/diagnostics.esm.js +1267 -0
  17. package/dist/diagnostics.esm.js.map +1 -0
  18. package/dist/index.cjs.js +2981 -1386
  19. package/dist/index.cjs.js.map +1 -0
  20. package/dist/index.d.ts +848 -111
  21. package/dist/index.esm.js +2997 -1411
  22. package/dist/index.esm.js.map +1 -0
  23. package/dist/jsx-dev-runtime.cjs.js +15 -9
  24. package/dist/jsx-dev-runtime.cjs.js.map +1 -0
  25. package/dist/jsx-dev-runtime.esm.js +15 -9
  26. package/dist/jsx-dev-runtime.esm.js.map +1 -0
  27. package/dist/jsx-runtime.cjs.js +15 -9
  28. package/dist/jsx-runtime.cjs.js.map +1 -0
  29. package/dist/jsx-runtime.esm.js +15 -9
  30. package/dist/jsx-runtime.esm.js.map +1 -0
  31. package/dist/jsx.cjs.js +15 -9
  32. package/dist/jsx.cjs.js.map +1 -0
  33. package/dist/jsx.esm.js +15 -9
  34. package/dist/jsx.esm.js.map +1 -0
  35. package/dist/sygnal.min.js +2 -1
  36. package/dist/sygnal.min.js.map +1 -0
  37. package/dist/vike/+config.cjs.js +1 -0
  38. package/dist/vike/+config.cjs.js.map +1 -0
  39. package/dist/vike/+config.js +1 -0
  40. package/dist/vike/+config.js.map +1 -0
  41. package/dist/vike/ClientOnly.cjs.js +1 -0
  42. package/dist/vike/ClientOnly.cjs.js.map +1 -0
  43. package/dist/vike/ClientOnly.mjs +1 -0
  44. package/dist/vike/ClientOnly.mjs.map +1 -0
  45. package/dist/vike/onRenderClient.cjs.js +1 -0
  46. package/dist/vike/onRenderClient.cjs.js.map +1 -0
  47. package/dist/vike/onRenderClient.mjs +1 -0
  48. package/dist/vike/onRenderClient.mjs.map +1 -0
  49. package/dist/vike/onRenderHtml.cjs.js +1 -0
  50. package/dist/vike/onRenderHtml.cjs.js.map +1 -0
  51. package/dist/vike/onRenderHtml.mjs +1 -0
  52. package/dist/vike/onRenderHtml.mjs.map +1 -0
  53. package/dist/vite/plugin.cjs.js +680 -47
  54. package/dist/vite/plugin.cjs.js.map +1 -0
  55. package/dist/vite/plugin.mjs +680 -47
  56. package/dist/vite/plugin.mjs.map +1 -0
  57. package/llms.txt +250 -0
  58. package/package.json +15 -6
  59. package/src/astro/client.ts +13 -2
  60. package/src/astro/index.d.ts +24 -1
  61. package/src/astro/index.ts +40 -9
  62. package/src/astro/server.ts +3 -1
  63. package/src/collection.ts +5 -2
  64. package/src/component.ts +375 -330
  65. package/src/cycle/dom/MainDOMSource.ts +4 -0
  66. package/src/cycle/dom/classNameModule.ts +74 -0
  67. package/src/cycle/dom/controlledInputModule.ts +33 -0
  68. package/src/cycle/dom/enrichEventStream.ts +9 -3
  69. package/src/cycle/dom/makeDOMDriver.ts +1 -2
  70. package/src/cycle/dom/mockDOMSource.ts +62 -8
  71. package/src/cycle/dom/modules.ts +5 -1
  72. package/src/cycle/state/Collection.ts +13 -3
  73. package/src/cycle/state/StateSource.ts +1 -1
  74. package/src/cycle/state/pickCombine.ts +35 -1
  75. package/src/cycle/state/withState.ts +1 -1
  76. package/src/extra/devtools.ts +8 -0
  77. package/src/extra/diagnostics/checks/collections.ts +67 -0
  78. package/src/extra/diagnostics/checks/dom.ts +241 -0
  79. package/src/extra/diagnostics/checks/events.ts +68 -0
  80. package/src/extra/diagnostics/checks/index.ts +109 -0
  81. package/src/extra/diagnostics/checks/inspect.ts +319 -0
  82. package/src/extra/diagnostics/checks/props.ts +51 -0
  83. package/src/extra/diagnostics/checks/public.d.ts +211 -0
  84. package/src/extra/diagnostics/checks/rxjsHints.ts +88 -0
  85. package/src/extra/diagnostics/checks/shared.ts +119 -0
  86. package/src/extra/diagnostics/checks/state.ts +55 -0
  87. package/src/extra/diagnostics/checks/strict.ts +112 -0
  88. package/src/extra/diagnostics/checks/wiring.ts +65 -0
  89. package/src/extra/diagnostics/codes.ts +232 -0
  90. package/src/extra/diagnostics/index.ts +328 -0
  91. package/src/extra/diagnostics/legacy.ts +59 -0
  92. package/src/extra/driverFactories.ts +106 -58
  93. package/src/extra/eventDriver.ts +4 -0
  94. package/src/extra/flatten.ts +75 -0
  95. package/src/extra/reducers.ts +12 -5
  96. package/src/extra/run.ts +11 -0
  97. package/src/extra/testing.ts +890 -180
  98. package/src/extra/xstreamExtras.ts +269 -0
  99. package/src/index.d.ts +428 -17
  100. package/src/index.ts +7 -6
  101. package/src/pragma/index.ts +14 -9
  102. package/src/switchable.ts +10 -8
  103. package/src/vike/types.ts +21 -4
  104. package/src/vite/plugin.d.ts +95 -2
  105. package/src/vite/plugin.ts +730 -55
  106. package/dist/astro/astro/client.d.ts +0 -5
  107. package/dist/astro/astro/index.d.ts +0 -16
  108. package/dist/astro/astro/server.d.ts +0 -12
  109. package/dist/astro/client.d.ts +0 -5
  110. package/dist/astro/client.esm.js +0 -4665
  111. package/dist/astro/collection.d.ts +0 -12
  112. package/dist/astro/component.d.ts +0 -22
  113. package/dist/astro/cycle/dom/BodyDOMSource.d.ts +0 -10
  114. package/dist/astro/cycle/dom/DOMSource.d.ts +0 -11
  115. package/dist/astro/cycle/dom/DocumentDOMSource.d.ts +0 -12
  116. package/dist/astro/cycle/dom/ElementFinder.d.ts +0 -8
  117. package/dist/astro/cycle/dom/EventDelegator.d.ts +0 -34
  118. package/dist/astro/cycle/dom/IsolateModule.d.ts +0 -23
  119. package/dist/astro/cycle/dom/MainDOMSource.d.ts +0 -32
  120. package/dist/astro/cycle/dom/PriorityQueue.d.ts +0 -7
  121. package/dist/astro/cycle/dom/ScopeChecker.d.ts +0 -9
  122. package/dist/astro/cycle/dom/SymbolTree.d.ts +0 -9
  123. package/dist/astro/cycle/dom/VNodeWrapper.d.ts +0 -8
  124. package/dist/astro/cycle/dom/enrichEventStream.d.ts +0 -24
  125. package/dist/astro/cycle/dom/fromEvent.d.ts +0 -6
  126. package/dist/astro/cycle/dom/index.d.ts +0 -8
  127. package/dist/astro/cycle/dom/isolate.d.ts +0 -9
  128. package/dist/astro/cycle/dom/makeDOMDriver.d.ts +0 -11
  129. package/dist/astro/cycle/dom/mockDOMSource.d.ts +0 -17
  130. package/dist/astro/cycle/dom/modules.d.ts +0 -5
  131. package/dist/astro/cycle/dom/snabbdom.d.ts +0 -22
  132. package/dist/astro/cycle/dom/styleModule.d.ts +0 -13
  133. package/dist/astro/cycle/dom/thunk.d.ts +0 -11
  134. package/dist/astro/cycle/dom/utils.d.ts +0 -8
  135. package/dist/astro/cycle/isolate/index.d.ts +0 -42
  136. package/dist/astro/cycle/run/adapt.d.ts +0 -6
  137. package/dist/astro/cycle/run/index.d.ts +0 -36
  138. package/dist/astro/cycle/run/internals.d.ts +0 -8
  139. package/dist/astro/cycle/run/types.d.ts +0 -49
  140. package/dist/astro/cycle/state/Collection.d.ts +0 -29
  141. package/dist/astro/cycle/state/StateSource.d.ts +0 -20
  142. package/dist/astro/cycle/state/index.d.ts +0 -5
  143. package/dist/astro/cycle/state/pickCombine.d.ts +0 -3
  144. package/dist/astro/cycle/state/pickMerge.d.ts +0 -3
  145. package/dist/astro/cycle/state/types.d.ts +0 -18
  146. package/dist/astro/cycle/state/withState.d.ts +0 -17
  147. package/dist/astro/extra/classes.d.ts +0 -7
  148. package/dist/astro/extra/devtools.d.ts +0 -78
  149. package/dist/astro/extra/dragDriver.d.ts +0 -20
  150. package/dist/astro/extra/driverFactories.d.ts +0 -12
  151. package/dist/astro/extra/eventDriver.d.ts +0 -9
  152. package/dist/astro/extra/exactState.d.ts +0 -1
  153. package/dist/astro/extra/hmr.d.ts +0 -17
  154. package/dist/astro/extra/logDriver.d.ts +0 -2
  155. package/dist/astro/extra/processDrag.d.ts +0 -19
  156. package/dist/astro/extra/processForm.d.ts +0 -15
  157. package/dist/astro/extra/run.d.ts +0 -13
  158. package/dist/astro/extra/xstreamCompat.d.ts +0 -5
  159. package/dist/astro/index.d.ts +0 -19
  160. package/dist/astro/index.esm.js +0 -27
  161. package/dist/astro/jsx-dev-runtime.d.ts +0 -1
  162. package/dist/astro/jsx-runtime.d.ts +0 -4
  163. package/dist/astro/jsx.d.ts +0 -2
  164. package/dist/astro/pragma/fn.d.ts +0 -7
  165. package/dist/astro/pragma/index.d.ts +0 -7
  166. package/dist/astro/pragma/is.d.ts +0 -10
  167. package/dist/astro/server.d.ts +0 -12
  168. package/dist/astro/server.esm.js +0 -25
  169. package/dist/astro/switchable.d.ts +0 -7
  170. package/dist/collection.d.ts +0 -12
  171. package/dist/component.d.ts +0 -22
  172. package/dist/cycle/dom/BodyDOMSource.d.ts +0 -10
  173. package/dist/cycle/dom/DOMSource.d.ts +0 -11
  174. package/dist/cycle/dom/DocumentDOMSource.d.ts +0 -12
  175. package/dist/cycle/dom/ElementFinder.d.ts +0 -8
  176. package/dist/cycle/dom/EventDelegator.d.ts +0 -34
  177. package/dist/cycle/dom/IsolateModule.d.ts +0 -23
  178. package/dist/cycle/dom/MainDOMSource.d.ts +0 -32
  179. package/dist/cycle/dom/PriorityQueue.d.ts +0 -7
  180. package/dist/cycle/dom/ScopeChecker.d.ts +0 -9
  181. package/dist/cycle/dom/SymbolTree.d.ts +0 -9
  182. package/dist/cycle/dom/VNodeWrapper.d.ts +0 -8
  183. package/dist/cycle/dom/enrichEventStream.d.ts +0 -24
  184. package/dist/cycle/dom/fromEvent.d.ts +0 -6
  185. package/dist/cycle/dom/index.d.ts +0 -8
  186. package/dist/cycle/dom/isolate.d.ts +0 -9
  187. package/dist/cycle/dom/makeDOMDriver.d.ts +0 -11
  188. package/dist/cycle/dom/mockDOMSource.d.ts +0 -17
  189. package/dist/cycle/dom/modules.d.ts +0 -5
  190. package/dist/cycle/dom/snabbdom.d.ts +0 -22
  191. package/dist/cycle/dom/styleModule.d.ts +0 -13
  192. package/dist/cycle/dom/thunk.d.ts +0 -11
  193. package/dist/cycle/dom/utils.d.ts +0 -8
  194. package/dist/cycle/isolate/index.d.ts +0 -42
  195. package/dist/cycle/run/adapt.d.ts +0 -6
  196. package/dist/cycle/run/index.d.ts +0 -36
  197. package/dist/cycle/run/internals.d.ts +0 -8
  198. package/dist/cycle/run/types.d.ts +0 -49
  199. package/dist/cycle/state/Collection.d.ts +0 -29
  200. package/dist/cycle/state/StateSource.d.ts +0 -20
  201. package/dist/cycle/state/index.d.ts +0 -5
  202. package/dist/cycle/state/pickCombine.d.ts +0 -3
  203. package/dist/cycle/state/pickMerge.d.ts +0 -3
  204. package/dist/cycle/state/types.d.ts +0 -18
  205. package/dist/cycle/state/withState.d.ts +0 -17
  206. package/dist/extra/classes.d.ts +0 -7
  207. package/dist/extra/devtools.d.ts +0 -78
  208. package/dist/extra/dragDriver.d.ts +0 -20
  209. package/dist/extra/driverFactories.d.ts +0 -12
  210. package/dist/extra/eventDriver.d.ts +0 -9
  211. package/dist/extra/exactState.d.ts +0 -1
  212. package/dist/extra/hmr.d.ts +0 -17
  213. package/dist/extra/logDriver.d.ts +0 -2
  214. package/dist/extra/processDrag.d.ts +0 -19
  215. package/dist/extra/processForm.d.ts +0 -15
  216. package/dist/extra/run.d.ts +0 -13
  217. package/dist/extra/xstreamCompat.d.ts +0 -5
  218. package/dist/jsx-dev-runtime.d.ts +0 -1
  219. package/dist/jsx-dev-runtime.js +0 -224
  220. package/dist/jsx-runtime.d.ts +0 -4
  221. package/dist/jsx-runtime.js +0 -224
  222. package/dist/jsx.d.ts +0 -2
  223. package/dist/pragma/fn.d.ts +0 -7
  224. package/dist/pragma/index.d.ts +0 -7
  225. package/dist/pragma/is.d.ts +0 -10
  226. package/dist/switchable.d.ts +0 -7
@@ -1,25 +1,784 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ import { createRequire } from 'node:module';
4
+ import { pathToFileURL } from 'node:url';
5
+
6
+ /**
7
+ * Sygnal Vite Plugin
8
+ *
9
+ * Auto-configures JSX, wires up HMR with state preservation and, in dev,
10
+ * turns on Sygnal's diagnostics (runtime checks and the static checker).
11
+ * Nothing it adds in dev reaches a production build.
12
+ *
13
+ * Usage:
14
+ * import sygnal from 'sygnal/vite'
15
+ * export default defineConfig({ plugins: [sygnal()] })
16
+ *
17
+ * What it does:
18
+ * 1. Configures the automatic JSX transform with sygnal as the import source:
19
+ * `oxc` (Vite 8), plus `esbuild` under Vite 7 and older
20
+ * 2. Detects files that call `run()` from sygnal and auto-injects HMR wiring
21
+ * 3. Dev mode (`vite` / `vite dev` only; never `vite build`). Into every
22
+ * file that imports `run` from sygnal (including entries with manual HMR
23
+ * wiring or `disableHmr`) it inserts, on an existing line:
24
+ *
25
+ * if (globalThis.__SYGNAL_DEV__ === undefined) globalThis.__SYGNAL_DEV__ = true;
26
+ * import 'sygnal/diagnostics';import 'virtual:sygnal/dev';
27
+ *
28
+ * The flag turns on runtime diagnostics in 'warn' mode; 'sygnal/diagnostics'
29
+ * registers the runtime checks (SYG101-106, 201, 202, 301, 401, ...);
30
+ * 'virtual:sygnal/dev' logs static-check results in the browser console
31
+ * (see 5). With `diagnostics: { strict: true }` the snippet also sets
32
+ * `globalThis.__SYGNAL_STRICT__ = true` (same guard), which turns on the
33
+ * strict (SYG5xx) runtime checks of 'sygnal/diagnostics'. The snippet goes
34
+ * after any shebang line and directive prologue ('use strict',
35
+ * 'use client'); line numbers are unchanged and the transform returns a
36
+ * sourcemap. Opt out per app with `run(App, drivers, { diagnostics: 'off' })`
37
+ * or for the whole dev server with `sygnal({ diagnostics: 'off' })`.
38
+ * 4. `diagnostics` option. The runtime core only understands
39
+ * `__SYGNAL_DEV__ === true` ('warn'), so another mode or an ignore list
40
+ * is passed as run()'s own `diagnostics` option: imports of 'sygnal'
41
+ * from the entry files above resolve to a dev-only wrapper module
42
+ * ('\0sygnal-dev:runtime') that re-exports sygnal with a run() that adds
43
+ * `diagnostics: { mode, ignore }` unless the call sets `diagnostics`
44
+ * itself. With the default ('warn', no ignore list) there is no wrapper.
45
+ * 5. `check` option: runs sygnal-check (an optional dependency, loaded
46
+ * lazily from the project; `strict` defaults to `diagnostics.strict`)
47
+ * over `include` (default: the existing ones of src/, pages/ and
48
+ * renderer/, else the project root, with a notice) when the dev
49
+ * server starts and again after every source file change. Results go to
50
+ * the terminal in sygnal-check's format, and to the browser as a
51
+ * 'sygnal:check' HMR event that the dev client ('virtual:sygnal/dev')
52
+ * logs with console.warn (non-disruptive). The dev client asks for the
53
+ * current findings when the page loads ('sygnal:check:request'), and only
54
+ * that client is answered; after a source change the new findings go to
55
+ * 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
59
+ * one is open Vite's client reloads the page on the next HMR update
60
+ * (`overlay: 'warn'` is treated as 'error', with a notice). The dev
61
+ * client closes a sygnal-check overlay before each update, and the
62
+ * server sends it again after the re-check, so it never causes a reload
63
+ * and doesn't go stale. A missing sygnal-check is skipped silently; a
64
+ * checker that throws only logs a warning.
65
+ * 6. Vitest (process.env.VITEST): appends the package's 'sygnal/diagnostics'
66
+ * ESM file to `test.setupFiles` (merged with a string or array value;
67
+ * not added twice), so renderComponent tests get the runtime checks.
68
+ * Its directory is added to the resolved `server.fs.allow` (G-050):
69
+ * in jsdom / happy-dom environments Vitest loads setup files through
70
+ * Vite's /@fs/ URLs, which a linked sygnal outside the workspace would
71
+ * otherwise fail. Opt out with `vitestSetup: false`. Under Vitest the transform adds
72
+ * nothing (no flags, HMR wiring, run() wrapper, dev client or checker):
73
+ * a __SYGNAL_DEV__ / __SYGNAL_STRICT__ flag set by one test file would
74
+ * leak into later test files of the same worker, and renderComponent()
75
+ * manages the diagnostics modes itself.
76
+ * 7. Vike and Astro (G-014): the app is started by sygnal's own client
77
+ * entry, which user code doesn't import. Client-side imports of
78
+ * 'sygnal/vike/onRenderClient' resolve to a dev wrapper that sets the
79
+ * flag and loads the checks first. Astro resolves its renderer entry on
80
+ * the server and the browser loads the file itself, so the same snippet
81
+ * is added to sygnal's 'astro/client' file by the transform. That file
82
+ * imports the public 'sygnal' entry (one shared core, B-019), so its
83
+ * 'sygnal' import gets the run() wrapper too: every `diagnostics` mode
84
+ * and ignore list works for islands. The sygnal/astro integration adds
85
+ * this plugin in `astro dev`.
86
+ *
87
+ * Why not Vite's `define`? Vite's dependency optimizer does not apply user
88
+ * `define` replacements to pre-bundled dependencies (only process.env.NODE_ENV),
89
+ * so a `define` would never reach sygnal's own code when sygnal is pre-bundled.
90
+ * Vite's client does copy `define` entries onto globalThis at runtime, but only
91
+ * when `/@vite/client` is loaded (not under SSR or Vitest, where it would also
92
+ * switch diagnostics on for every test run). Injecting the flag into the
93
+ * entry file that calls run() is deterministic and scoped to the dev app; it
94
+ * runs before run() is called, which is when the diagnostics mode is resolved.
95
+ *
96
+ * The HMR transform finds the pattern:
97
+ * import { run } from 'sygnal'
98
+ * import App from './App.jsx'
99
+ * run(App)
100
+ *
101
+ * And appends:
102
+ * if (import.meta.hot) {
103
+ * import.meta.hot.accept('./App.jsx', __sygnal.hmr)
104
+ * import.meta.hot.dispose(__sygnal.dispose)
105
+ * }
106
+ *
107
+ * HMR wiring is only added for a recognized top-level (column 0) run()
108
+ * statement whose result reference is actually defined (see RUN_CALL_RE). It
109
+ * is skipped — the dev flag is still injected — for any other shape (e.g.
110
+ * `app = run(App)`, nested or indented calls), for test files (*.test.*,
111
+ * *.spec.*) and under Vitest (process.env.VITEST).
112
+ */
113
+ // Node built-ins (the plugin runs in Node). The package has no @types/node.
114
+ // @ts-ignore
115
+ const nodeProcess = globalThis.process;
116
+ // Virtual modules (dev server only)
117
+ const DEV_CLIENT = 'virtual:sygnal/dev';
118
+ const DEV_CLIENT_ID = '\0' + DEV_CLIENT;
119
+ const RUNTIME_ID = '\0sygnal-dev:runtime';
120
+ const VIKE_CLIENT = 'sygnal/vike/onRenderClient';
121
+ const VIKE_CLIENT_ID = '\0sygnal-dev:vike-client';
122
+ const CHECK_EVENT = 'sygnal:check';
123
+ // Sent by the dev client when it loads: the server answers that client only
124
+ const CHECK_REQUEST = 'sygnal:check:request';
125
+ const OVERLAY_PLUGIN = 'sygnal-check';
126
+ // Register the runtime checks with the core that loaded last (see the Vike wrapper)
127
+ const REINSTALL_IMPORT = `import { installChecks as __sygnalInstallChecks } from 'sygnal/diagnostics';`;
128
+ const REINSTALL_CALL = 'try { __sygnalInstallChecks() } catch (e) { console.warn(e) }\n';
129
+ function sygnal(options = {}) {
130
+ const { disableJsx = false, disableHmr = false, vitestSetup = true } = options;
131
+ const diagnostics = normalizeDiagnostics(options.diagnostics);
132
+ const devOn = diagnostics.mode !== 'off';
133
+ // A mode other than the flag's 'warn', or an ignore list, needs run()'s option
134
+ const wrapRun = devOn && (diagnostics.mode !== 'warn' || diagnostics.ignore.length > 0);
135
+ let isServe = false;
136
+ let isVitest = false;
137
+ let root = nodeProcess.cwd();
138
+ // Files whose `import ... from 'sygnal'` resolves to the run() wrapper
139
+ const runtimeImporters = new Set();
140
+ // Statements run before the app starts: dev flag (+ strict flag)
141
+ const flags = DEV_FLAG + (diagnostics.strict ? STRICT_FLAG : '');
142
+ const devImports = `import 'sygnal/diagnostics';import '${DEV_CLIENT}';`;
143
+ let astroClient;
144
+ return {
145
+ name: 'vite-plugin-sygnal',
146
+ config(config, env) {
147
+ isServe = env.command === 'serve';
148
+ isVitest = !!nodeProcess?.env?.VITEST;
149
+ root = config?.root ? path.resolve(config.root) : nodeProcess.cwd();
150
+ const result = {
151
+ // Ensure sygnal is bundled for SSR rather than externalized.
152
+ // Without this, Node fails to resolve sygnal's exports from
153
+ // Vike's server chunks in production builds.
154
+ ssr: {
155
+ noExternal: ['sygnal'],
156
+ },
157
+ };
158
+ if (!disableJsx) {
159
+ result.oxc = {
160
+ jsx: {
161
+ runtime: 'automatic',
162
+ importSource: 'sygnal',
163
+ },
164
+ };
165
+ // Vite 7 and older (Astro 6, Vitest on Vite 7) compile JSX with
166
+ // esbuild and ignore `oxc` (B-027); Vite 8 warns about `esbuild`
167
+ // from a plugin, so it is only set below Vite 8.
168
+ if (viteMajor(this, root) < 8) {
169
+ result.esbuild = { jsx: 'automatic', jsxImportSource: 'sygnal' };
170
+ }
171
+ // Vite 8's dependency scanner doesn't use the `oxc` options: without
172
+ // this it compiles JSX for React, fails to resolve
173
+ // react/jsx-dev-runtime and skips pre-bundling (a reload on first load).
174
+ if (isServe && !isVitest) {
175
+ result.optimizeDeps = { rolldownOptions: { transform: { jsx: { runtime: 'automatic', importSource: 'sygnal' } } } };
176
+ }
177
+ }
178
+ if (isVitest) {
179
+ if (vitestSetup) {
180
+ const setup = diagnosticsSetupFile(root);
181
+ const existing = [].concat(config?.test?.setupFiles || []);
182
+ const loaded = existing.some(f => typeof f === 'string' &&
183
+ (f === 'sygnal/diagnostics' || (!!setup && path.resolve(root, f) === setup)));
184
+ // Vite merges arrays (and a string with an array) by concatenation
185
+ if (setup && !loaded)
186
+ result.test = { setupFiles: [setup] };
187
+ }
188
+ }
189
+ else if (isServe && devOn && sygnalInNodeModules(root)) {
190
+ // 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'] };
196
+ }
197
+ return result;
198
+ },
199
+ configResolved(config) {
200
+ if (config?.root)
201
+ root = config.root;
202
+ // G-050: Vitest loads setup files by URL (/@fs/...) in browser-like
203
+ // environments (jsdom, happy-dom), and Vite refuses files outside
204
+ // server.fs.allow, which is the project's workspace by default. A linked
205
+ // (or hoisted) sygnal lives outside it, so allow its setup file's
206
+ // directory. The resolved list already holds Vite's defaults.
207
+ if (isVitest) {
208
+ const setup = diagnosticsSetupFile(root);
209
+ const allow = config?.server?.fs?.allow;
210
+ if (setup && Array.isArray(allow)) {
211
+ const dir = path.dirname(setup);
212
+ const inside = (base) => {
213
+ const rel = path.relative(path.resolve(base), dir);
214
+ return rel === '' || (!rel.startsWith('..') && !path.isAbsolute(rel));
215
+ };
216
+ if (!allow.some(inside))
217
+ allow.push(dir);
218
+ }
219
+ }
220
+ },
221
+ resolveId: {
222
+ order: 'pre',
223
+ async handler(source, importer, opts) {
224
+ if (!isServe || isVitest)
225
+ return null;
226
+ if (source === DEV_CLIENT)
227
+ return DEV_CLIENT_ID;
228
+ if (source === 'sygnal' && importer && wrapRun && runtimeImporters.has(cleanId(importer))) {
229
+ return RUNTIME_ID;
230
+ }
231
+ if (source === VIKE_CLIENT && devOn && !opts?.ssr) {
232
+ if (importer !== VIKE_CLIENT_ID)
233
+ return VIKE_CLIENT_ID;
234
+ // The wrapper's own import of the real entry: resolve it normally.
235
+ // The real Vike client's run() then gets the run() wrapper too, when
236
+ // it is served unbundled (a pre-bundled copy stays in 'warn' mode).
237
+ const real = await this.resolve(source, importer, { ...opts, skipSelf: true });
238
+ if (real && wrapRun)
239
+ runtimeImporters.add(cleanId(real.id));
240
+ return real;
241
+ }
242
+ return null;
243
+ },
244
+ },
245
+ load(id) {
246
+ if (id === DEV_CLIENT_ID)
247
+ return devClientModule();
248
+ if (id === RUNTIME_ID)
249
+ return runtimeModule(diagnostics);
250
+ // The checks register again once the real entry has loaded: a
251
+ // pre-bundled copy of it can carry its own copy of the Sygnal core
252
+ // (e.g. with a linked sygnal), which then holds the diagnostics bridge.
253
+ if (id === VIKE_CLIENT_ID) {
254
+ return `${devImports}${REINSTALL_IMPORT}\nexport * from '${VIKE_CLIENT}';\n${flags}\n${REINSTALL_CALL}`;
255
+ }
256
+ return null;
257
+ },
258
+ configureServer(server) {
259
+ if (isVitest || options.check === false)
260
+ return;
261
+ const checkOptions = typeof options.check === 'object' && options.check ? options.check : {};
262
+ // Deferred: the dev server doesn't wait for the first check
263
+ const checkDefaults = { strict: diagnostics.strict, ignore: diagnostics.ignore };
264
+ setTimeout(() => {
265
+ startChecker(server, root, checkOptions, checkDefaults, options.check !== undefined)
266
+ .catch(err => server?.config?.logger?.warn?.(`[sygnal] sygnal-check could not start: ${err?.message || err}`));
267
+ }, 0);
268
+ },
269
+ 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));
308
+ if (wrapRun)
309
+ runtimeImporters.add(cleanId(id));
310
+ }
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`));
338
+ }
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'));
344
+ }
345
+ return done();
346
+ },
347
+ };
348
+ }
349
+ /**
350
+ * Major version of the running Vite: from the plugin context (this.meta,
351
+ * Vite 7+), else from the vite package the project resolves. Infinity when
352
+ * unknown (treated as Vite 8+: no `esbuild` option).
353
+ */
354
+ function viteMajor(ctx, root) {
355
+ const fromMeta = ctx?.meta?.viteVersion;
356
+ if (typeof fromMeta === 'string')
357
+ return parseInt(fromMeta, 10);
358
+ if (ctx?.meta?.rolldownVersion)
359
+ return 8;
360
+ try {
361
+ const req = createRequire(path.join(root, 'package.json'));
362
+ const v = JSON.parse(fs.readFileSync(req.resolve('vite/package.json'), 'utf8')).version;
363
+ const major = parseInt(v, 10);
364
+ if (major > 0)
365
+ return major;
366
+ }
367
+ catch (_) { }
368
+ return Infinity;
369
+ }
370
+ const MODES = ['off', 'collect', 'warn', 'error'];
371
+ function normalizeDiagnostics(value) {
372
+ const o = typeof value === 'string' ? { mode: value } : value || {};
373
+ const mode = o.mode === undefined ? 'warn' : o.mode;
374
+ if (!MODES.includes(mode)) {
375
+ throw new Error(`[vite-plugin-sygnal] diagnostics mode must be one of ${MODES.map(m => `'${m}'`).join(', ')}; got ${JSON.stringify(mode)}`);
376
+ }
377
+ return { mode, strict: !!o.strict, ignore: Array.isArray(o.ignore) ? o.ignore.map(String) : [] };
378
+ }
379
+ /** Module id without a query or hash. */
380
+ function cleanId(id) {
381
+ return id.replace(/[?#].*$/, '');
382
+ }
383
+ /** 'virtual:sygnal/dev': logs sygnal-check results in the browser console. */
384
+ function devClientModule() {
385
+ // Vite's client reloads the page on the first HMR update while an error
386
+ // overlay is open. A sygnal-check overlay is closed before each update (the
387
+ // server sends it again after the re-check), so it never causes a reload.
388
+ return `if (import.meta.hot) {
389
+ let shown = 0;
390
+ let ours = false;
391
+ const closeOurs = () => {
392
+ if (!ours || typeof document === 'undefined') return;
393
+ document.querySelectorAll('vite-error-overlay').forEach((n) => n.close ? n.close() : n.remove());
394
+ ours = false;
395
+ };
396
+ import.meta.hot.on('vite:error', (payload) => {
397
+ ours = !!(payload && payload.err && payload.err.plugin === '${OVERLAY_PLUGIN}');
398
+ });
399
+ import.meta.hot.on('vite:beforeUpdate', closeOurs);
400
+ import.meta.hot.on('${CHECK_EVENT}', (payload) => {
401
+ const list = (payload && payload.diagnostics) || [];
402
+ if (!list.some((d) => d.severity === 'error')) closeOurs();
403
+ if (!list.length) {
404
+ if (shown) console.info('[sygnal-check] all findings resolved');
405
+ shown = 0;
406
+ return;
407
+ }
408
+ shown = list.length;
409
+ for (const d of list) console[d.severity === 'error' ? 'error' : 'warn']('[sygnal-check] ' + d.text);
410
+ console.info('[sygnal-check] ' + payload.summary);
411
+ });
412
+ import.meta.hot.send('${CHECK_REQUEST}');
413
+ }
414
+ `;
415
+ }
416
+ /** '\0sygnal-dev:runtime': sygnal with a run() that adds the plugin's diagnostics option. */
417
+ function runtimeModule(d) {
418
+ const option = JSON.stringify({ mode: d.mode, ignore: d.ignore });
419
+ return `import { run as __run } from 'sygnal';
420
+ export * from 'sygnal';
421
+ export function run(app, drivers, options) {
422
+ if (options && options.diagnostics !== undefined) return __run(app, drivers, options);
423
+ return __run(app, drivers, Object.assign({}, options, { diagnostics: ${option} }));
424
+ }
425
+ `;
426
+ }
427
+ /** Directory of the 'sygnal' package the project resolves, or undefined. */
428
+ function sygnalPackageDir(root) {
429
+ try {
430
+ const req = createRequire(path.join(root, 'package.json'));
431
+ let dir = path.dirname(req.resolve('sygnal'));
432
+ while (dir !== path.dirname(dir)) {
433
+ const pkgFile = path.join(dir, 'package.json');
434
+ if (fs.existsSync(pkgFile) && JSON.parse(fs.readFileSync(pkgFile, 'utf8')).name === 'sygnal')
435
+ return dir;
436
+ dir = path.dirname(dir);
437
+ }
438
+ }
439
+ catch (_) { }
440
+ return undefined;
441
+ }
442
+ /** Real paths of sygnal's 'astro/client' ESM file. */
443
+ function astroClientFiles(root) {
444
+ const files = new Set();
445
+ const dir = sygnalPackageDir(root);
446
+ if (!dir)
447
+ return files;
448
+ try {
449
+ const pkg = JSON.parse(fs.readFileSync(path.join(dir, 'package.json'), 'utf8'));
450
+ const entry = pkg.exports?.['./astro/client'];
451
+ const rel = typeof entry === 'string' ? entry : entry?.import;
452
+ if (typeof rel !== 'string')
453
+ return files;
454
+ const file = path.resolve(dir, rel);
455
+ files.add(file.split(path.sep).join('/'));
456
+ files.add(fs.realpathSync(file).split(path.sep).join('/'));
457
+ }
458
+ catch (_) { }
459
+ return files;
460
+ }
461
+ function sygnalInNodeModules(root) {
462
+ const dir = sygnalPackageDir(root);
463
+ if (!dir)
464
+ return false;
465
+ try {
466
+ return fs.realpathSync(dir).split(path.sep).includes('node_modules');
467
+ }
468
+ catch (_) {
469
+ return false;
470
+ }
471
+ }
472
+ /**
473
+ * Absolute path of the ESM build of 'sygnal/diagnostics' (its "import"
474
+ * condition), so the checks share the core instance the tests import.
475
+ */
476
+ function diagnosticsSetupFile(root) {
477
+ const dir = sygnalPackageDir(root);
478
+ if (!dir)
479
+ return undefined;
480
+ try {
481
+ const pkg = JSON.parse(fs.readFileSync(path.join(dir, 'package.json'), 'utf8'));
482
+ const entry = pkg.exports?.['./diagnostics'];
483
+ const rel = typeof entry === 'string' ? entry : entry?.import?.default || entry?.import || entry?.default;
484
+ if (typeof rel !== 'string')
485
+ return undefined;
486
+ const file = path.resolve(dir, rel);
487
+ return fs.existsSync(file) ? file : undefined;
488
+ }
489
+ catch (_) {
490
+ return undefined;
491
+ }
492
+ }
493
+ /** Load sygnal-check from the project (optional dependency); undefined when it is missing. */
494
+ async function loadSygnalCheck(root) {
495
+ try {
496
+ const file = createRequire(path.join(root, 'package.json')).resolve('sygnal-check');
497
+ return await import(/* @vite-ignore */ pathToFileURL(file).href);
498
+ }
499
+ catch (_) { }
500
+ try {
501
+ const name = 'sygnal-check';
502
+ return await import(/* @vite-ignore */ name);
503
+ }
504
+ catch (_) {
505
+ return undefined;
506
+ }
507
+ }
508
+ const SOURCE_RE = /\.[cm]?[jt]sx?$/;
509
+ /** sygnal-check's one-line format: `file:line:col CODE [severity] Component: message (fix)` */
510
+ function formatLine(d) {
511
+ const where = d.file ? `${d.file}:${d.line}:${d.column}` : '<sygnal-check>';
512
+ const sev = d.severity === 'warn' ? '' : ` [${d.severity}]`;
513
+ return `${where} ${d.code}${sev} ${d.component ? d.component + ': ' : ''}${d.message}${d.fix ? ` (${d.fix})` : ''}`;
514
+ }
515
+ // Source directories checked by default, those that exist (Vike apps use
516
+ // pages/ and renderer/, often without src/)
517
+ const DEFAULT_INCLUDE = ['src', 'pages', 'renderer'];
518
+ /**
519
+ * What sygnal-check checks: `include` when given, else the existing default
520
+ * directories, else the project root (sygnal-check skips node_modules, dist
521
+ * and other build output). Logs one notice when the default finds no
522
+ * directory, or when none of the given paths exists, so an empty check is
523
+ * never a silent all-clear.
524
+ */
525
+ function checkInclude(root, include, notice) {
526
+ const exists = (p) => /[*?[{]/.test(p) || fs.existsSync(path.resolve(root, p));
527
+ if (include && include.length) {
528
+ if (!include.some(exists))
529
+ notice(`[sygnal] sygnal-check: none of check.include (${include.join(', ')}) exists under ${root}, so nothing is checked`);
530
+ return include;
531
+ }
532
+ const dirs = DEFAULT_INCLUDE.filter(exists);
533
+ if (dirs.length)
534
+ return dirs;
535
+ notice(`[sygnal] sygnal-check: no ${DEFAULT_INCLUDE.join('/, ')}/ directory under ${root}; checking the project root (set check.include to choose)`);
536
+ return ['.'];
537
+ }
538
+ /** Run sygnal-check now and after source changes; report to the terminal and the browser. */
539
+ async function startChecker(server, root, opts, defaults, explicit) {
540
+ const mod = await loadSygnalCheck(root);
541
+ const logger = server?.config?.logger || console;
542
+ if (!mod || typeof mod.check !== 'function') {
543
+ if (explicit)
544
+ logger.info('[sygnal] sygnal-check is not installed, so static checks are off (npm i -D sygnal-check)');
545
+ return;
546
+ }
547
+ const include = checkInclude(root, opts.include, (m) => logger.info(m));
548
+ const ignore = opts.ignore || defaults.ignore;
549
+ const strict = opts.strict === undefined ? defaults.strict : !!opts.strict;
550
+ // Only error-severity findings open Vite's overlay: while an overlay is open
551
+ // Vite's client reloads the page on the first HMR update, so warnings stay
552
+ // in the terminal and the browser console. overlay: 'warn' is treated as
553
+ // 'error' (with a one-time notice).
554
+ if (opts.overlay === 'warn') {
555
+ logger.info("[sygnal] check.overlay: 'warn' is treated as 'error': warnings go to the browser console, not Vite's error overlay (an open overlay makes Vite reload the page on the next update)");
556
+ }
557
+ const overlay = opts.overlay !== false;
558
+ let lastKey;
559
+ let payload = null;
560
+ let overlayErr = null;
561
+ const event = () => ({ type: 'custom', event: CHECK_EVENT, data: payload });
562
+ const errorMessage = () => ({ type: 'error', err: overlayErr });
563
+ // Every connected client (after a source change). An error with no client
564
+ // connected would be buffered by Vite and shown on the next page load.
565
+ const broadcast = (findingsChanged) => {
566
+ const ws = server.ws;
567
+ if (!ws || typeof ws.send !== 'function')
568
+ return;
569
+ try {
570
+ if (findingsChanged && payload)
571
+ ws.send(event());
572
+ if (overlayErr && !(ws.clients && ws.clients.size === 0))
573
+ ws.send(errorMessage());
574
+ }
575
+ catch (_) { }
576
+ };
577
+ const run = (initial = false) => {
578
+ let diags;
579
+ try {
580
+ diags = mod.check(include, { cwd: root, strict, ignore });
581
+ }
582
+ catch (err) {
583
+ logger.warn(`[sygnal] sygnal-check failed: ${err?.message || err}`, { timestamp: true });
584
+ return;
585
+ }
586
+ const shown = diags.filter(d => d.severity !== 'info');
587
+ const lines = shown.map(formatLine);
588
+ const key = lines.join('\n');
589
+ const changed = key !== lastKey;
590
+ if (changed) {
591
+ lastKey = key;
592
+ const text = typeof mod.formatDiagnostics === 'function'
593
+ ? mod.formatDiagnostics(diags)
594
+ : lines.concat(`sygnal-check: ${shown.length} finding(s)`).join('\n');
595
+ const summary = text.split('\n').pop() || '';
596
+ if (shown.length)
597
+ logger.warn(text, { timestamp: true });
598
+ else
599
+ logger.info(summary, { timestamp: true });
600
+ payload = {
601
+ summary,
602
+ diagnostics: shown.map((d, i) => ({ code: d.code, severity: d.severity, file: d.file, line: d.line, column: d.column, text: lines[i] })),
603
+ };
604
+ const forOverlay = overlay ? shown.filter(d => d.severity === 'error') : [];
605
+ const first = forOverlay[0];
606
+ overlayErr = first ? {
607
+ plugin: OVERLAY_PLUGIN,
608
+ message: forOverlay.map(formatLine).join('\n'),
609
+ stack: '',
610
+ id: path.resolve(root, first.file || ''),
611
+ loc: { file: path.resolve(root, first.file || ''), line: first.line, column: first.column },
612
+ } : null;
613
+ }
614
+ // The first check runs before any page is open; pages ask for the
615
+ // findings when they load (CHECK_REQUEST). After a change the overlay is
616
+ // sent again even when the findings are the same: the HMR update closed it.
617
+ if (!initial)
618
+ broadcast(changed);
619
+ };
620
+ run(true);
621
+ // A page that loads (or reloads) asks for the current findings: answer
622
+ // that client only, never every client.
623
+ try {
624
+ server.ws?.on?.(CHECK_REQUEST, (_data, client) => {
625
+ try {
626
+ if (payload)
627
+ client?.send?.(event());
628
+ if (overlayErr)
629
+ client?.send?.(errorMessage());
630
+ }
631
+ catch (_) { }
632
+ });
633
+ }
634
+ catch (_) { }
635
+ let timer;
636
+ const onChange = (file) => {
637
+ if (!SOURCE_RE.test(file) || file.split(/[\\/]/).includes('node_modules'))
638
+ return;
639
+ clearTimeout(timer);
640
+ timer = setTimeout(run, 100);
641
+ };
642
+ const watcher = server?.watcher;
643
+ if (watcher && typeof watcher.on === 'function') {
644
+ watcher.on('change', onChange);
645
+ watcher.on('add', onChange);
646
+ watcher.on('unlink', onChange);
647
+ }
648
+ try {
649
+ server.httpServer?.once?.('close', () => clearTimeout(timer));
650
+ }
651
+ catch (_) { }
652
+ }
653
+ const DEV_FLAG = 'if (globalThis.__SYGNAL_DEV__ === undefined) globalThis.__SYGNAL_DEV__ = true;';
654
+ const STRICT_FLAG = 'if (globalThis.__SYGNAL_STRICT__ === undefined) globalThis.__SYGNAL_STRICT__ = true;';
655
+ // A top-level (column 0) run(Component, ...) statement: bare, or declaring a
656
+ // new binding. Assignments to existing variables, nested calls and indented
657
+ // calls (e.g. inside a function or test callback) do not match (B-007). It is
658
+ // matched against the code with comments and strings blanked out.
659
+ const RUN_CALL_RE = /^(?:(?:const|let|var)\s+(\{[^}]*\}|[\w$]+)\s*=\s*)?run\s*\(\s*([A-Z][\w$]*)/m;
660
+ // Comments, string literals and template literals (a regex literal containing
661
+ // a quote or `//` can over-blank; that only ever skips HMR wiring).
662
+ const COMMENT_OR_STRING_RE = /\/\/[^\n]*|\/\*[\s\S]*?(?:\*\/|$)|(['"])(?:\\.|(?!\1)[^\\\n])*\1?|`(?:\\[\s\S]|[^\\`])*`?/g;
663
+ /** Replace comments (and, with `strings`, string/template literals) by spaces, keeping offsets and newlines. */
664
+ function blankOut(code, strings) {
665
+ return code.replace(COMMENT_OR_STRING_RE, m => !strings && m[0] !== '/' ? m : m.replace(/[^\n]/g, ' '));
666
+ }
667
+ // One directive ('use strict', "use client", ...) with any leading whitespace
668
+ // and comments. It must end with `;` (group 2) or at the end of its line.
669
+ const DIRECTIVE_RE = /(?:\s|\/\/[^\n]*|\/\*[\s\S]*?\*\/)*(['"])(?:\\.|(?!\1)[^\\\n])*\1(?:[ \t]*(;)|(?=[ \t]*(?:\/\/[^\n]*|\/\*[^\n]*?\*\/)?[ \t]*(?:\r?\n|$)))/y;
670
+ /** Insert `text` (the dev snippet) after a shebang line and the directive prologue. */
671
+ function flagInsertion(code, text) {
672
+ let at = code.startsWith('#!') ? (code.indexOf('\n') + 1 || code.length) : 0;
673
+ let semicolon = true;
674
+ DIRECTIVE_RE.lastIndex = at;
675
+ let m;
676
+ while ((m = DIRECTIVE_RE.exec(code))) {
677
+ at = DIRECTIVE_RE.lastIndex;
678
+ semicolon = !!m[2];
679
+ }
680
+ return [at, (semicolon ? '' : ';') + text];
681
+ }
682
+ const B64 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
683
+ function vlq(n) {
684
+ let v = n < 0 ? (-n << 1) | 1 : n << 1;
685
+ let out = '';
686
+ do {
687
+ let digit = v & 31;
688
+ v >>>= 5;
689
+ if (v)
690
+ digit |= 32;
691
+ out += B64[digit];
692
+ } while (v);
693
+ return out;
694
+ }
695
+ /**
696
+ * Apply single-line insertions (at offsets in the original code) plus an
697
+ * appended tail, and build a v3 sourcemap without extra dependencies. No line
698
+ * is added before the tail, so every original line maps to itself; on a line
699
+ * with an insertion, the text after it maps back to its original column.
700
+ */
701
+ function withSourcemap(code, inserts, tail, id) {
702
+ inserts.sort((a, b) => a[0] - b[0]);
703
+ let out = '';
704
+ let last = 0;
705
+ for (const [at, text] of inserts) {
706
+ out += code.slice(last, at) + text;
707
+ last = at;
708
+ }
709
+ out += code.slice(last) + tail;
710
+ let offset = 0;
711
+ let k = 0;
712
+ let prevLine = 0;
713
+ let prevCol = 0;
714
+ const mappings = code.split('\n').map((line, i) => {
715
+ const segments = [[0, 0]]; // [generated column, original column]
716
+ let shift = 0;
717
+ while (k < inserts.length && inserts[k][0] <= offset + line.length) {
718
+ const col = inserts[k][0] - offset;
719
+ shift += inserts[k][1].length;
720
+ segments.push([col + shift, col]);
721
+ k++;
722
+ }
723
+ offset += line.length + 1;
724
+ let genCol = 0;
725
+ return segments.map(([gen, col]) => {
726
+ const seg = vlq(gen - genCol) + 'A' + vlq(i - prevLine) + vlq(col - prevCol);
727
+ genCol = gen;
728
+ prevLine = i;
729
+ prevCol = col;
730
+ return seg;
731
+ }).join(',');
732
+ }).join(';');
733
+ return {
734
+ code: out,
735
+ map: { version: 3, sources: [id], sourcesContent: [code], names: [], mappings },
736
+ };
737
+ }
738
+ function hmrBlock(componentPath, hmrRef, disposeRef) {
739
+ return `
740
+ if (import.meta.hot) {
741
+ import.meta.hot.accept('${componentPath}', ${hmrRef})
742
+ import.meta.hot.dispose(${disposeRef})
743
+ }
744
+ `;
745
+ }
746
+
1
747
  const SYGNAL_RENDERER_NAME = '@sygnal/astro';
2
- function sygnalAstroIntegration() {
748
+ function sygnalAstroIntegration(options = {}) {
3
749
  return {
4
750
  name: SYGNAL_RENDERER_NAME,
5
751
  hooks: {
6
- 'astro:config:setup': ({ addRenderer, updateConfig }) => {
752
+ 'astro:config:setup': ({ addRenderer, updateConfig, command }) => {
7
753
  addRenderer({
8
754
  name: SYGNAL_RENDERER_NAME,
9
755
  clientEntrypoint: 'sygnal/astro/client',
10
756
  serverEntrypoint: 'sygnal/astro/server',
11
757
  });
12
- updateConfig({
13
- vite: {
14
- esbuild: {
15
- jsx: 'automatic',
16
- jsxImportSource: 'sygnal',
17
- },
758
+ const vite = {
759
+ esbuild: {
760
+ jsx: 'automatic',
761
+ jsxImportSource: 'sygnal',
18
762
  },
19
- });
763
+ };
764
+ // Dev mode (G-014): islands are started by sygnal/astro/client, which
765
+ // 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`.
768
+ if (command === 'dev') {
769
+ vite.plugins = [sygnal({
770
+ disableJsx: true,
771
+ disableHmr: true,
772
+ vitestSetup: false,
773
+ diagnostics: options.diagnostics,
774
+ check: options.check,
775
+ })];
776
+ }
777
+ updateConfig({ vite });
20
778
  },
21
779
  },
22
780
  };
23
781
  }
24
782
 
25
783
  export { sygnalAstroIntegration as default };
784
+ //# sourceMappingURL=index.mjs.map