@hydranium/cli 1.0.0-next.38 → 1.0.0-next.381

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 (339) hide show
  1. package/README.md +102 -204
  2. package/bin/hydranium-cli.js +13 -0
  3. package/heap-analysis/heap/core/load.mjs +2 -2
  4. package/heap-analysis/heap/langium/langium.classifier.mjs +22 -11
  5. package/lib/cli-version.js.map +1 -1
  6. package/lib/cli.js +7 -2
  7. package/lib/cli.js.map +1 -1
  8. package/lib/commands/analyze-heap-args.d.ts.map +1 -1
  9. package/lib/commands/analyze-heap-args.js +1 -2
  10. package/lib/commands/analyze-heap-args.js.map +1 -1
  11. package/lib/commands/analyze-heap.d.ts +3 -0
  12. package/lib/commands/analyze-heap.d.ts.map +1 -1
  13. package/lib/commands/analyze-heap.js +2 -1
  14. package/lib/commands/analyze-heap.js.map +1 -1
  15. package/lib/commands/ast-ground-truth-args.d.ts +3 -2
  16. package/lib/commands/ast-ground-truth-args.d.ts.map +1 -1
  17. package/lib/commands/ast-ground-truth-args.js +11 -9
  18. package/lib/commands/ast-ground-truth-args.js.map +1 -1
  19. package/lib/commands/ast-ground-truth-driver.js +4 -2
  20. package/lib/commands/ast-ground-truth-driver.js.map +1 -1
  21. package/lib/commands/ast-ground-truth.js +1 -1
  22. package/lib/commands/ast-ground-truth.js.map +1 -1
  23. package/lib/commands/client-session.d.ts +17 -0
  24. package/lib/commands/client-session.d.ts.map +1 -0
  25. package/lib/commands/client-session.js +27 -0
  26. package/lib/commands/client-session.js.map +1 -0
  27. package/lib/commands/create-args.d.ts +17 -0
  28. package/lib/commands/create-args.d.ts.map +1 -0
  29. package/lib/commands/create-args.js +53 -0
  30. package/lib/commands/create-args.js.map +1 -0
  31. package/lib/commands/create.d.ts +38 -0
  32. package/lib/commands/create.d.ts.map +1 -0
  33. package/lib/commands/create.js +43 -0
  34. package/lib/commands/create.js.map +1 -0
  35. package/lib/commands/delete-args.d.ts +17 -0
  36. package/lib/commands/delete-args.d.ts.map +1 -0
  37. package/lib/commands/delete-args.js +49 -0
  38. package/lib/commands/delete-args.js.map +1 -0
  39. package/lib/commands/delete.d.ts +30 -0
  40. package/lib/commands/delete.d.ts.map +1 -0
  41. package/lib/commands/delete.js +32 -0
  42. package/lib/commands/delete.js.map +1 -0
  43. package/lib/commands/generate-ast-builder.d.ts.map +1 -1
  44. package/lib/commands/generate-ast-builder.js +1 -10
  45. package/lib/commands/generate-ast-builder.js.map +1 -1
  46. package/lib/commands/generate-languages.d.ts +35 -0
  47. package/lib/commands/generate-languages.d.ts.map +1 -0
  48. package/lib/commands/generate-languages.js +105 -0
  49. package/lib/commands/generate-languages.js.map +1 -0
  50. package/lib/commands/generate-transfer-builder.d.ts +33 -0
  51. package/lib/commands/generate-transfer-builder.d.ts.map +1 -0
  52. package/lib/commands/generate-transfer-builder.js +86 -0
  53. package/lib/commands/generate-transfer-builder.js.map +1 -0
  54. package/lib/commands/generate-transfer-model-args.d.ts.map +1 -1
  55. package/lib/commands/generate-transfer-model-args.js +20 -5
  56. package/lib/commands/generate-transfer-model-args.js.map +1 -1
  57. package/lib/commands/generate-transfer-model-config.d.ts.map +1 -1
  58. package/lib/commands/generate-transfer-model-config.js +8 -3
  59. package/lib/commands/generate-transfer-model-config.js.map +1 -1
  60. package/lib/commands/generate-transfer-model.d.ts +40 -9
  61. package/lib/commands/generate-transfer-model.d.ts.map +1 -1
  62. package/lib/commands/generate-transfer-model.js +219 -67
  63. package/lib/commands/generate-transfer-model.js.map +1 -1
  64. package/lib/commands/generated-module-path.d.ts +16 -0
  65. package/lib/commands/generated-module-path.d.ts.map +1 -0
  66. package/lib/commands/generated-module-path.js +21 -0
  67. package/lib/commands/generated-module-path.js.map +1 -0
  68. package/lib/commands/harness-args.d.ts +44 -42
  69. package/lib/commands/harness-args.d.ts.map +1 -1
  70. package/lib/commands/harness-args.js +109 -27
  71. package/lib/commands/harness-args.js.map +1 -1
  72. package/lib/commands/headless-harness.d.ts +37 -20
  73. package/lib/commands/headless-harness.d.ts.map +1 -1
  74. package/lib/commands/headless-harness.js +71 -19
  75. package/lib/commands/headless-harness.js.map +1 -1
  76. package/lib/commands/init-args.d.ts +2 -0
  77. package/lib/commands/init-args.d.ts.map +1 -1
  78. package/lib/commands/init-args.js +74 -31
  79. package/lib/commands/init-args.js.map +1 -1
  80. package/lib/commands/init-hosts.d.ts +24 -0
  81. package/lib/commands/init-hosts.d.ts.map +1 -0
  82. package/lib/commands/init-hosts.js +37 -0
  83. package/lib/commands/init-hosts.js.map +1 -0
  84. package/lib/commands/init-prompt.d.ts +3 -3
  85. package/lib/commands/init-prompt.d.ts.map +1 -1
  86. package/lib/commands/init-prompt.js +4 -5
  87. package/lib/commands/init-prompt.js.map +1 -1
  88. package/lib/commands/init-templates.d.ts +26 -14
  89. package/lib/commands/init-templates.d.ts.map +1 -1
  90. package/lib/commands/init-templates.js +2989 -746
  91. package/lib/commands/init-templates.js.map +1 -1
  92. package/lib/commands/init-wizard.d.ts +3 -0
  93. package/lib/commands/init-wizard.d.ts.map +1 -1
  94. package/lib/commands/init-wizard.js +46 -31
  95. package/lib/commands/init-wizard.js.map +1 -1
  96. package/lib/commands/init-workspace.d.ts +13 -11
  97. package/lib/commands/init-workspace.d.ts.map +1 -1
  98. package/lib/commands/init-workspace.js +21 -7
  99. package/lib/commands/init-workspace.js.map +1 -1
  100. package/lib/commands/init.d.ts +58 -22
  101. package/lib/commands/init.d.ts.map +1 -1
  102. package/lib/commands/init.js +206 -48
  103. package/lib/commands/init.js.map +1 -1
  104. package/lib/commands/kebab.d.ts +15 -0
  105. package/lib/commands/kebab.d.ts.map +1 -0
  106. package/lib/commands/kebab.js +17 -0
  107. package/lib/commands/kebab.js.map +1 -0
  108. package/lib/commands/lint-grammar-args.d.ts +3 -2
  109. package/lib/commands/lint-grammar-args.d.ts.map +1 -1
  110. package/lib/commands/lint-grammar-args.js +13 -10
  111. package/lib/commands/lint-grammar-args.js.map +1 -1
  112. package/lib/commands/lint-grammar-driver.js +2 -1
  113. package/lib/commands/lint-grammar-driver.js.map +1 -1
  114. package/lib/commands/lint-grammar-report.js.map +1 -1
  115. package/lib/commands/lint-grammar.js +1 -1
  116. package/lib/commands/lint-grammar.js.map +1 -1
  117. package/lib/commands/measure-memory-args.d.ts +3 -2
  118. package/lib/commands/measure-memory-args.d.ts.map +1 -1
  119. package/lib/commands/measure-memory-args.js +22 -11
  120. package/lib/commands/measure-memory-args.js.map +1 -1
  121. package/lib/commands/measure-memory-driver.js +5 -3
  122. package/lib/commands/measure-memory-driver.js.map +1 -1
  123. package/lib/commands/measure-memory.js +1 -1
  124. package/lib/commands/measure-memory.js.map +1 -1
  125. package/lib/commands/model-docs-args.d.ts +4 -3
  126. package/lib/commands/model-docs-args.d.ts.map +1 -1
  127. package/lib/commands/model-docs-args.js +12 -10
  128. package/lib/commands/model-docs-args.js.map +1 -1
  129. package/lib/commands/model-docs-driver.js +2 -1
  130. package/lib/commands/model-docs-driver.js.map +1 -1
  131. package/lib/commands/model-docs.js +1 -1
  132. package/lib/commands/model-docs.js.map +1 -1
  133. package/lib/commands/projects-args.d.ts.map +1 -1
  134. package/lib/commands/projects-args.js +5 -5
  135. package/lib/commands/projects-args.js.map +1 -1
  136. package/lib/commands/projects.d.ts +3 -4
  137. package/lib/commands/projects.d.ts.map +1 -1
  138. package/lib/commands/projects.js +2 -2
  139. package/lib/commands/projects.js.map +1 -1
  140. package/lib/commands/query-args.d.ts.map +1 -1
  141. package/lib/commands/query-args.js +6 -5
  142. package/lib/commands/query-args.js.map +1 -1
  143. package/lib/commands/query.d.ts +6 -5
  144. package/lib/commands/query.d.ts.map +1 -1
  145. package/lib/commands/query.js +5 -4
  146. package/lib/commands/query.js.map +1 -1
  147. package/lib/commands/reflect-args.d.ts +3 -2
  148. package/lib/commands/reflect-args.d.ts.map +1 -1
  149. package/lib/commands/reflect-args.js +13 -10
  150. package/lib/commands/reflect-args.js.map +1 -1
  151. package/lib/commands/reflect-driver.js +2 -1
  152. package/lib/commands/reflect-driver.js.map +1 -1
  153. package/lib/commands/reflect-report.js.map +1 -1
  154. package/lib/commands/reflect.js +1 -1
  155. package/lib/commands/reflect.js.map +1 -1
  156. package/lib/commands/save-args.d.ts.map +1 -1
  157. package/lib/commands/save-args.js +7 -4
  158. package/lib/commands/save-args.js.map +1 -1
  159. package/lib/commands/save.d.ts +8 -4
  160. package/lib/commands/save.d.ts.map +1 -1
  161. package/lib/commands/save.js +12 -23
  162. package/lib/commands/save.js.map +1 -1
  163. package/lib/commands/validate-args.d.ts +3 -2
  164. package/lib/commands/validate-args.d.ts.map +1 -1
  165. package/lib/commands/validate-args.js +13 -10
  166. package/lib/commands/validate-args.js.map +1 -1
  167. package/lib/commands/validate-driver.js +2 -1
  168. package/lib/commands/validate-driver.js.map +1 -1
  169. package/lib/commands/validate-report.js.map +1 -1
  170. package/lib/commands/validate.js +1 -1
  171. package/lib/commands/validate.js.map +1 -1
  172. package/lib/commands/watch-args.d.ts.map +1 -1
  173. package/lib/commands/watch-args.js +6 -4
  174. package/lib/commands/watch-args.js.map +1 -1
  175. package/lib/commands/watch.d.ts +3 -4
  176. package/lib/commands/watch.d.ts.map +1 -1
  177. package/lib/commands/watch.js +20 -2
  178. package/lib/commands/watch.js.map +1 -1
  179. package/lib/driver-heap.d.ts +52 -0
  180. package/lib/driver-heap.d.ts.map +1 -0
  181. package/lib/driver-heap.js +51 -0
  182. package/lib/driver-heap.js.map +1 -0
  183. package/lib/index.d.ts +2 -0
  184. package/lib/index.d.ts.map +1 -1
  185. package/lib/index.js +2 -0
  186. package/lib/index.js.map +1 -1
  187. package/lib/log-level.d.ts +21 -11
  188. package/lib/log-level.d.ts.map +1 -1
  189. package/lib/log-level.js +25 -14
  190. package/lib/log-level.js.map +1 -1
  191. package/lib/spawn-data-server.d.ts +9 -4
  192. package/lib/spawn-data-server.d.ts.map +1 -1
  193. package/lib/spawn-data-server.js +5 -4
  194. package/lib/spawn-data-server.js.map +1 -1
  195. package/lib/stderr-connection-logger.d.ts +12 -0
  196. package/lib/stderr-connection-logger.d.ts.map +1 -0
  197. package/lib/stderr-connection-logger.js +16 -0
  198. package/lib/stderr-connection-logger.js.map +1 -0
  199. package/lib/testing/echo-server.js +9 -1
  200. package/lib/testing/echo-server.js.map +1 -1
  201. package/package.json +90 -39
  202. package/src/cli.ts +7 -2
  203. package/src/commands/analyze-heap-args.ts +1 -2
  204. package/src/commands/analyze-heap.ts +4 -1
  205. package/src/commands/ast-ground-truth-args.ts +15 -12
  206. package/src/commands/ast-ground-truth-driver.ts +4 -2
  207. package/src/commands/ast-ground-truth.ts +1 -1
  208. package/src/commands/client-session.ts +33 -0
  209. package/src/commands/create-args.ts +68 -0
  210. package/src/commands/create.ts +83 -0
  211. package/src/commands/delete-args.ts +64 -0
  212. package/src/commands/delete.ts +61 -0
  213. package/src/commands/generate-ast-builder.ts +1 -11
  214. package/src/commands/generate-languages.ts +132 -0
  215. package/src/commands/generate-transfer-builder.ts +101 -0
  216. package/src/commands/generate-transfer-model-args.ts +20 -5
  217. package/src/commands/generate-transfer-model-config.ts +8 -3
  218. package/src/commands/generate-transfer-model.ts +291 -65
  219. package/src/commands/generated-module-path.ts +22 -0
  220. package/src/commands/harness-args.ts +99 -31
  221. package/src/commands/headless-harness.ts +89 -28
  222. package/src/commands/init-args.ts +76 -31
  223. package/src/commands/init-hosts.ts +51 -0
  224. package/src/commands/init-prompt.ts +5 -6
  225. package/src/commands/init-templates.ts +3161 -759
  226. package/src/commands/init-wizard.ts +55 -31
  227. package/src/commands/init-workspace.ts +31 -16
  228. package/src/commands/init.ts +266 -63
  229. package/src/commands/kebab.ts +17 -0
  230. package/src/commands/lint-grammar-args.ts +17 -13
  231. package/src/commands/lint-grammar-driver.ts +2 -1
  232. package/src/commands/lint-grammar.ts +1 -1
  233. package/src/commands/measure-memory-args.ts +27 -14
  234. package/src/commands/measure-memory-driver.ts +5 -3
  235. package/src/commands/measure-memory.ts +1 -1
  236. package/src/commands/model-docs-args.ts +16 -13
  237. package/src/commands/model-docs-driver.ts +2 -1
  238. package/src/commands/model-docs.ts +1 -1
  239. package/src/commands/projects-args.ts +5 -4
  240. package/src/commands/projects.ts +4 -6
  241. package/src/commands/query-args.ts +6 -4
  242. package/src/commands/query.ts +9 -9
  243. package/src/commands/reflect-args.ts +17 -13
  244. package/src/commands/reflect-driver.ts +2 -1
  245. package/src/commands/reflect.ts +1 -1
  246. package/src/commands/save-args.ts +7 -3
  247. package/src/commands/save.ts +24 -27
  248. package/src/commands/validate-args.ts +17 -13
  249. package/src/commands/validate-driver.ts +2 -1
  250. package/src/commands/validate.ts +1 -1
  251. package/src/commands/watch-args.ts +6 -3
  252. package/src/commands/watch.ts +28 -7
  253. package/src/driver-heap.ts +65 -0
  254. package/src/index.ts +2 -0
  255. package/src/log-level.ts +42 -14
  256. package/src/spawn-data-server.ts +17 -5
  257. package/src/stderr-connection-logger.ts +18 -0
  258. package/src/testing/echo-server.ts +11 -2
  259. package/templates/client/gitignore +3 -0
  260. package/templates/client/src/__GRAMMAR_ID__-diagram-module.ts +82 -0
  261. package/templates/editorconfig +15 -0
  262. package/templates/gitignore +1 -0
  263. package/templates/host-browser/esbuild.mjs +82 -0
  264. package/templates/host-browser/gitignore +4 -0
  265. package/templates/host-browser/hydranium-mark.svg +40 -0
  266. package/templates/host-browser/index.html +287 -0
  267. package/templates/host-browser/playwright.config.mts +24 -0
  268. package/templates/host-browser/src/data-status.ts +15 -0
  269. package/templates/host-browser/src/diagram-save.ts +60 -0
  270. package/templates/host-browser/src/diagram.ts +118 -0
  271. package/templates/host-browser/src/editor.ts +102 -0
  272. package/templates/host-browser/src/log.ts +14 -0
  273. package/templates/host-browser/src/monaco-editor-core-worker.d.ts +7 -0
  274. package/templates/host-browser/src/monaco-editor-worker.ts +10 -0
  275. package/templates/host-browser/src/posix-path-shim.ts +23 -0
  276. package/templates/host-browser/src/shown-file.ts +61 -0
  277. package/templates/host-browser/src/workspace.ts +5 -0
  278. package/templates/host-browser/tsconfig.e2e.json +16 -0
  279. package/templates/host-browser/tsconfig.page.json +16 -0
  280. package/templates/host-browser/tsconfig.worker.json +16 -0
  281. package/templates/host-theia-browser/esbuild.mjs +24 -0
  282. package/templates/host-theia-browser/gitignore +9 -0
  283. package/templates/host-theia-browser/playwright.config.mts +42 -0
  284. package/templates/host-theia-browser/start.mjs +50 -0
  285. package/templates/host-theia-browser/tsconfig.e2e.json +16 -0
  286. package/templates/host-theia-electron/esbuild.mjs +27 -0
  287. package/templates/host-theia-electron/gitignore +8 -0
  288. package/templates/host-theia-electron/playwright.config.mts +12 -0
  289. package/templates/host-theia-electron/start.mjs +47 -0
  290. package/templates/host-theia-electron/tsconfig.e2e.json +16 -0
  291. package/templates/host-vscode/esbuild.mjs +38 -0
  292. package/templates/host-vscode/gitignore +7 -0
  293. package/templates/host-vscode/playwright.config.mts +14 -0
  294. package/templates/host-vscode/src/__GRAMMAR_ID__-diagram-editor.ts +19 -0
  295. package/templates/host-vscode/src/show-model-command.ts +24 -0
  296. package/templates/host-vscode/src/webview/__GRAMMAR_ID__-diagram.ts +18 -0
  297. package/templates/host-vscode/src/webview/diagram.css +40 -0
  298. package/templates/host-vscode/start.mjs +22 -0
  299. package/templates/host-vscode/test/install-vscode.mts +21 -0
  300. package/templates/host-vscode/test/vscode-version.mts +10 -0
  301. package/templates/host-vscode/tsconfig.e2e.json +17 -0
  302. package/templates/host-vscode/tsconfig.json +19 -0
  303. package/templates/host-vscode/tsconfig.webview.json +17 -0
  304. package/templates/oxlintrc.json +4 -0
  305. package/templates/protocol/gitignore +3 -0
  306. package/templates/protocol/src/__GRAMMAR_ID__-diagram-types.ts +47 -0
  307. package/templates/server/gitignore +6 -0
  308. package/templates/server/src/glsp/__GRAMMAR_ID__/create-node-operation-handler.ts +62 -0
  309. package/templates/server/src/glsp/__GRAMMAR_ID__/delete-operation-handler.ts +63 -0
  310. package/templates/server/src/glsp/__GRAMMAR_ID__/gmodel-factory.ts +144 -0
  311. package/templates/server/src/glsp/__GRAMMAR_ID__/state.ts +18 -0
  312. package/templates/server/src/glsp/__GRAMMAR_ID__/storage.ts +16 -0
  313. package/templates/server/src/glsp/__GRAMMAR_ID__/submission-handler.ts +24 -0
  314. package/templates/server/src/grammar/common.langium +12 -0
  315. package/templates/server/src/language-server/__GRAMMAR_ID__-serializer.ts +53 -0
  316. package/templates/server/src/language-server/__GRAMMAR_ID__-validation.ts +30 -0
  317. package/templates/server/src/language-server/ast.ts +23 -0
  318. package/templates/server/src/node/services.ts +16 -0
  319. package/templates/server/test/__GRAMMAR_ID__-diagram.test.ts +388 -0
  320. package/templates/server/test/tsconfig.json +4 -0
  321. package/templates/server/tsconfig.test.json +10 -0
  322. package/templates/server/vitest.config.ts +14 -0
  323. package/templates/theia/gitignore +3 -0
  324. package/templates/theia/src/browser/__GRAMMAR_ID__-diagram-frontend-module.ts +65 -0
  325. package/templates/theia/src/browser/__PROJECT_ID__-connection-preload-module.ts +15 -0
  326. package/templates/theia/src/browser/__PROJECT_ID__-data-connection.ts +15 -0
  327. package/templates/theia/src/browser/__PROJECT_ID__-data-port.ts +11 -0
  328. package/templates/theia/src/browser/__PROJECT_ID__-glsp-client-contribution.ts +13 -0
  329. package/templates/theia/src/browser/__PROJECT_ID__-show-model-command.ts +51 -0
  330. package/templates/theia/src/common/__PROJECT_ID__-glsp-contribution.ts +3 -0
  331. package/templates/theia/src/node/__PROJECT_ID__-connection-backend-module.ts +12 -0
  332. package/templates/theia/src/node/__PROJECT_ID__-data-backend-module.ts +15 -0
  333. package/templates/theia/src/node/__PROJECT_ID__-glsp-backend-module.ts +16 -0
  334. package/templates/theia/style/diagram.css +20 -0
  335. package/templates/theia/tsconfig.json +24 -0
  336. package/templates/vscode-servers/gitignore +4 -0
  337. package/templates/vscode-servers/tsconfig.json +19 -0
  338. package/templates/workspace/nodes.__EXTENSION__ +5 -0
  339. package/templates/workspace/references.__EXTENSION__ +2 -0
@@ -22,6 +22,12 @@
22
22
  * `bin` key, the DI module filename, and the data-server port command.
23
23
  * - `__CONFIG_ROOT_CONST__` — SCREAMING_SNAKE project id, naming the
24
24
  * `lsp.configurationRoot` constant a multi-grammar project binds.
25
+ * - `__PROTOCOL_PACKAGE__` — the protocol member's package name, scope
26
+ * included, which the server and every client import ids and wire types
27
+ * from.
28
+ * - `__SERVER_PACKAGE__` / `__CLIENT_PACKAGE__` — the server and client
29
+ * members' package names, which a host imports the language and the diagram
30
+ * definition from.
25
31
  *
26
32
  * GRAMMAR tokens, substituted once per grammar:
27
33
  *
@@ -29,6 +35,10 @@
29
35
  * Drives the PER-LANGUAGE generated symbols (`<grammar>GeneratedModule`,
30
36
  * `<grammar>LanguageMetaData`).
31
37
  * - `__GRAMMAR_ID__` — kebab grammar id: the `.langium` filename.
38
+ * - `__GRAMMAR_ID_CONST__` — SCREAMING_SNAKE grammar id, prefixing the
39
+ * diagram's type-id constants.
40
+ * - `__GRAMMAR_CAMEL__` — lowerCamelCase grammar name, naming the client's
41
+ * diagram module constant.
32
42
  * - `__LANGUAGE_ID__` — kebab routing key: the `langium-config` entry id and
33
43
  * its TextMate output.
34
44
  * - `__EXTENSION__` — the grammar's FIRST file extension, without the dot.
@@ -49,10 +59,22 @@
49
59
  * generator emits `interface <projectName>Element` as the base type every rule
50
60
  * extends, which a rule of that name would collide with.
51
61
  *
52
- * Kept as in-source strings (not on-disk assets) so no build-time copy step
53
- * is needed and the substitution is unit-testable. The `.ts` / `.langium` / JSON
54
- * templates are derived from the in-repo reference example so the generated project
55
- * compiles against the real `@hydranium/*` API once `langium generate` has run.
62
+ * The project is its packages and a starter workspace, each in its own
63
+ * directory: `server/` (the grammar, the language and its heads), `protocol/`
64
+ * (what the server and its clients both import, so a client never installs
65
+ * Langium), `client/` with a diagram (its host-neutral client side),
66
+ * `host-<name>/` per host, `vscode-servers/` with the VS Code host (the server
67
+ * launch it shares with a Theia app), and `workspace/` (starter model files
68
+ * every host and the CLI open). A standalone project adds a root manifest
69
+ * naming them as npm workspaces; a workspace member joins the surrounding root
70
+ * instead.
71
+ *
72
+ * A file that is fixed text with tokens lives in the `templates/` tree the
73
+ * package ships beside `lib`, at the path it is emitted at, tokens included
74
+ * (each ignore file without its dot); one computed from the composition is
75
+ * built here. The tree is read synchronously, so `runInit` stays synchronous,
76
+ * and it is neither formatted with the repo's settings nor given a license
77
+ * header, since either would change what `init` emits.
56
78
  *
57
79
  * Two conventions the templates follow deliberately:
58
80
  *
@@ -72,8 +94,10 @@
72
94
  * over; the adopter's own formatter settles it.
73
95
  */
74
96
 
97
+ import { readFileSync } from 'node:fs';
75
98
  import { readCliVersion } from '../cli-version.js';
76
- import type { InitComposition, InitFile, InitGrammarNames, InitHead } from './init.js';
99
+ import { type InitComposition, type InitFile, type InitGrammarNames, type InitHead, type InitMember, initMembers } from './init.js';
100
+ import { isTheiaHost } from './init-hosts.js';
77
101
  import type { JsonValue } from './init-workspace.js';
78
102
 
79
103
  /** One template file: its path (tokens allowed) and its content (tokens allowed). */
@@ -82,16 +106,6 @@ export interface InitTemplate {
82
106
  content: string;
83
107
  }
84
108
 
85
- /**
86
- * The version every framework package carries before the first release.
87
- *
88
- * A scaffold made by a CLI still at this version pins a range the registry
89
- * cannot serve, so the emitted README keeps its yalc note and `init` keeps its
90
- * install warning while — and only while — it holds: from a published CLI the
91
- * derived pins resolve and either note would be false as printed.
92
- */
93
- export const UNPUBLISHED_FRAMEWORK_VERSION = '0.0.0';
94
-
95
109
  /**
96
110
  * The version `init` pins every `@hydranium/*` dependency at: the scaffolding
97
111
  * CLI's own.
@@ -122,12 +136,55 @@ function screamingSnake(projectId: string): string {
122
136
  return projectId.replace(/-/g, '_').toUpperCase();
123
137
  }
124
138
 
139
+ const VSCODE_EXTENSION_MEMBERS: readonly InitMember[] = ['vscode-servers', 'host-vscode'];
140
+
141
+ /**
142
+ * A member's package name: `<id>-<member>`, under the scope when there is one,
143
+ * except for the VS Code extensions, whose scoped name `vsce` refuses to
144
+ * package.
145
+ *
146
+ * Suffixed even for the server, because a project of several packages has no
147
+ * member entitled to the bare id, and a later client or host would otherwise
148
+ * read as a part of the server.
149
+ */
150
+ export function memberPackageName(composition: InitComposition, member: InitMember): string {
151
+ const { scope } = composition.packaging;
152
+ const name = `${composition.projectId}-${member}`;
153
+ return scope === undefined || VSCODE_EXTENSION_MEMBERS.includes(member) ? name : `${scope}/${name}`;
154
+ }
155
+
156
+ /**
157
+ * The composition as one member sees it: inside a workspace, its placement
158
+ * sits one directory below the project's, so its `extends` and its lint
159
+ * config path reach one level further up.
160
+ */
161
+ function forMember(composition: InitComposition, member: InitMember): InitComposition {
162
+ const workspace = composition.packaging.workspace;
163
+ if (workspace === undefined) {
164
+ return composition;
165
+ }
166
+ return {
167
+ ...composition,
168
+ packaging: {
169
+ ...composition.packaging,
170
+ workspace: {
171
+ ...workspace,
172
+ targetPath: `${workspace.targetPath}/${member}`,
173
+ baseTsconfig: workspace.baseTsconfig === undefined ? undefined : `../${workspace.baseTsconfig}`
174
+ }
175
+ }
176
+ };
177
+ }
178
+
125
179
  /** Substitute the project-tier tokens. */
126
180
  function project(text: string, composition: InitComposition): string {
127
181
  return text
128
182
  .replace(/__NAME__/g, composition.name)
129
183
  .replace(/__PROJECT_ID__/g, composition.projectId)
130
- .replace(/__CONFIG_ROOT_CONST__/g, screamingSnake(composition.projectId));
184
+ .replace(/__CONFIG_ROOT_CONST__/g, screamingSnake(composition.projectId))
185
+ .replace(/__PROTOCOL_PACKAGE__/g, memberPackageName(composition, 'protocol'))
186
+ .replace(/__SERVER_PACKAGE__/g, memberPackageName(composition, 'server'))
187
+ .replace(/__CLIENT_PACKAGE__/g, memberPackageName(composition, 'client'));
131
188
  }
132
189
 
133
190
  /**
@@ -140,7 +197,9 @@ function project(text: string, composition: InitComposition): string {
140
197
  */
141
198
  function grammarTier(text: string, grammar: InitGrammarNames): string {
142
199
  return text
200
+ .replace(/__GRAMMAR_ID_CONST__/g, screamingSnake(grammar.grammarId))
143
201
  .replace(/__GRAMMAR_ID__/g, grammar.grammarId)
202
+ .replace(/__GRAMMAR_CAMEL__/g, grammar.grammar.charAt(0).toLowerCase() + grammar.grammar.slice(1))
144
203
  .replace(/__GRAMMAR__/g, grammar.grammar)
145
204
  .replace(/__LANGUAGE_ID__/g, grammar.languageId)
146
205
  .replace(/__EXTENSION__/g, grammar.extensions[0])
@@ -153,6 +212,30 @@ function render(text: string, composition: InitComposition, grammar: InitGrammar
153
212
  return grammarTier(project(text, composition), grammar);
154
213
  }
155
214
 
215
+ /** The template tree, the same two levels up from `src/commands` and `lib/commands`. */
216
+ const TEMPLATES = new URL('../../templates/', import.meta.url);
217
+
218
+ /** One template file's text. */
219
+ function template(path: string): string {
220
+ return readFileSync(new URL(path, TEMPLATES), 'utf-8');
221
+ }
222
+
223
+ /** A template emitted once per project at its own path, rendered with the project tokens. */
224
+ function projectTemplate(path: string, composition: InitComposition): InitFile {
225
+ return { path, content: project(template(path), composition) };
226
+ }
227
+
228
+ /** A template emitted once per grammar, its path rendered like its content. */
229
+ function grammarTemplate(path: string, composition: InitComposition, grammar: InitGrammarNames): InitFile {
230
+ return { path: render(path, composition, grammar), content: render(template(path), composition, grammar) };
231
+ }
232
+
233
+ /** An ignore file, stored without its dot because `npm pack` drops a nested `.gitignore` and applies it as an ignore file. */
234
+ function ignoreFile(directory: string): InitFile {
235
+ const prefix = directory === '' ? '' : `${directory}/`;
236
+ return { path: `${prefix}.gitignore`, content: template(`${prefix}gitignore`) };
237
+ }
238
+
156
239
  /** A comma-separated list of single-quoted TypeScript/JS string literals. */
157
240
  function quotedList(values: readonly string[]): string {
158
241
  return values.map(value => `'${value}'`).join(', ');
@@ -161,14 +244,15 @@ function quotedList(values: readonly string[]): string {
161
244
  /**
162
245
  * The column budget the emitted sources wrap at when nothing better is known.
163
246
  *
164
- * **Not "prettier's default"** — that is 80. 120 is a choice, and stating it as
165
- * a default was wrong in a way that mattered: no single width is stable for an
247
+ * **Not "prettier's default"** — that is 80. No single width is stable for an
166
248
  * unknown repo, so emitted code only passes a formatter check relative to a
167
249
  * config. A workspace scaffold detects the surrounding repo's `printWidth` and
168
250
  * uses it (see {@link columnsFor}); a standalone one has no config to read and
169
- * falls back here.
251
+ * falls back here. It is the framework's own width, so a fixed template, which
252
+ * wraps at no budget, reads the same in a standalone scaffold as in the
253
+ * examples this repo formats.
170
254
  */
171
- const DEFAULT_COLUMNS = 120;
255
+ const DEFAULT_COLUMNS = 140;
172
256
 
173
257
  /** The width THIS composition wraps at: the detected workspace one, else {@link DEFAULT_COLUMNS}. */
174
258
  function columnsFor(composition: InitComposition): number {
@@ -177,7 +261,7 @@ function columnsFor(composition: InitComposition): number {
177
261
 
178
262
  /**
179
263
  * A named import on one line while it fits the column budget, else one symbol
180
- * per line. Emitted files are supposed to pass a prettier check as-is, and the
264
+ * per line. Emitted files are supposed to pass a format check as-is, and the
181
265
  * generated-module import grows by one symbol per grammar.
182
266
  */
183
267
  function importList(symbols: readonly string[], from: string, columns: number, typeOnly = false): string {
@@ -198,9 +282,13 @@ function arrayLiteral(elements: readonly string[], indent: string, columns: numb
198
282
  * The FRAMEWORK packages each head adds, carrying no version: every
199
283
  * `@hydranium/*` pin is derived at scaffold time from {@link frameworkPin}, so
200
284
  * none of them can name a version its siblings were not published at.
285
+ *
286
+ * `base` is every head set's: the services every head serves from are composed
287
+ * the same with or without an LSP head.
201
288
  */
202
- const HEAD_FRAMEWORK_DEPENDENCIES: Record<InitHead, readonly string[]> = {
203
- lsp: ['@hydranium/core', '@hydranium/langium', '@hydranium/protocol'],
289
+ const HEAD_FRAMEWORK_DEPENDENCIES: Record<InitHead | 'base', readonly string[]> = {
290
+ base: ['@hydranium/core', '@hydranium/langium', '@hydranium/protocol'],
291
+ lsp: [],
204
292
  data: ['@hydranium/data-server'],
205
293
  glsp: ['@hydranium/glsp-server']
206
294
  };
@@ -221,46 +309,213 @@ const HEAD_FRAMEWORK_DEPENDENCIES: Record<InitHead, readonly string[]> = {
221
309
  * `overrides` block exists to prevent — so a repo gate holds each entry here
222
310
  * against the manifest that declares it.
223
311
  *
224
- * `langium` is required by `lsp` even though hand-written code goes through the
312
+ * `langium` is required even though hand-written code goes through the
225
313
  * `@hydranium/langium` chokepoint, because `langium-cli` emits direct imports
226
- * into the generated files and regenerates them on every build.
314
+ * into the generated files and regenerates them on every build. The `vscode-*`
315
+ * packages are required peers of `@hydranium/core`, so they are `base` too.
227
316
  */
228
- const HEAD_THIRD_PARTY_DEPENDENCIES: Record<InitHead, Readonly<Record<string, string>>> = {
229
- lsp: {
317
+ const HEAD_THIRD_PARTY_DEPENDENCIES: Record<InitHead | 'base', Readonly<Record<string, string>>> = {
318
+ base: {
230
319
  langium: '4.3.1',
231
- 'vscode-languageserver': '~10.0.1'
320
+ // Exact, as are the protocol and transport it pins, so Langium and the
321
+ // framework share their copies; across copies, an error a handler throws
322
+ // or returns loses its code, and a later patch can pin another protocol.
323
+ 'vscode-languageserver': '10.0.1',
324
+ 'vscode-jsonrpc': '9.0.0',
325
+ 'vscode-languageserver-protocol': '3.18.1',
326
+ // The copy that protocol pins; a root without it takes the one Theia pins.
327
+ 'vscode-languageserver-types': '3.18.0'
232
328
  },
329
+ lsp: {},
233
330
  data: {},
234
331
  glsp: {
235
- '@eclipse-glsp/graph': '2.7.0',
236
- '@eclipse-glsp/server': '2.7.0',
237
- // `^6.1.3` and NOT `^6.0.0`: `@eclipse-glsp/server@2.7.0` requires it, and
332
+ '@eclipse-glsp/graph': '2.8.0',
333
+ '@eclipse-glsp/server': '2.8.0',
334
+ // `^6.1.3` and NOT `^6.0.0`: `@eclipse-glsp/server` requires it, and
238
335
  // `^6.0.0` resolved only because the hoisted copy happened to satisfy it.
239
336
  inversify: '^6.1.3',
240
337
  'reflect-metadata': '~0.2.2'
241
338
  }
242
339
  };
243
340
 
244
- /** The dependency block for a head set, merged and sorted as npm writes it. */
341
+ /**
342
+ * What each head adds to the protocol member, which carries only what a
343
+ * client may install. Keyed by head because the `glsp` head implies a diagram,
344
+ * whose element ids extend GLSP's default type names.
345
+ */
346
+ const PROTOCOL_THIRD_PARTY_DEPENDENCIES: Record<InitHead, Readonly<Record<string, string>>> = {
347
+ lsp: {},
348
+ data: {},
349
+ glsp: { '@eclipse-glsp/protocol': '2.8.0' }
350
+ };
351
+
352
+ /** The client member's packages: the diagram definition and what it registers its elements with. */
353
+ const CLIENT_FRAMEWORK_DEPENDENCIES: readonly string[] = ['@hydranium/glsp-client'];
354
+ const CLIENT_THIRD_PARTY_DEPENDENCIES: Readonly<Record<string, string>> = {
355
+ '@eclipse-glsp/client': '2.8.0',
356
+ inversify: '^6.1.3'
357
+ };
358
+
359
+ /**
360
+ * What each head adds to the browser host, which bundles the server into its
361
+ * worker and the head's client into its page. `base` is what every page needs.
362
+ *
363
+ * `monaco-editor-core` is exact for the reason `langium` is: Monaco's models
364
+ * live in one copy, and `@hydranium/client-browser` must reach the page's.
365
+ */
366
+ const HOST_BROWSER_FRAMEWORK_DEPENDENCIES: Record<InitHead | 'base', readonly string[]> = {
367
+ base: ['@hydranium/client-browser', '@hydranium/core', '@hydranium/protocol'],
368
+ lsp: [],
369
+ data: ['@hydranium/data-server'],
370
+ glsp: ['@hydranium/glsp-client', '@hydranium/glsp-server']
371
+ };
372
+ const HOST_BROWSER_THIRD_PARTY_DEPENDENCIES: Record<InitHead | 'base', Readonly<Record<string, string>>> = {
373
+ base: { 'vscode-jsonrpc': '9.0.0', 'vscode-languageserver-protocol': '3.18.1' },
374
+ lsp: { 'monaco-editor-core': '0.56.0' },
375
+ data: {},
376
+ glsp: { '@eclipse-glsp/server': '2.8.0', 'reflect-metadata': '~0.2.2' }
377
+ };
378
+
379
+ /** The browser host's tools: the bundler, the smoke tier and the type check. */
380
+ const HOST_BROWSER_DEV_DEPENDENCIES: Readonly<Record<string, string>> = {
381
+ '@playwright/test': '^1.55.0',
382
+ '@types/node': '^22.0.0',
383
+ esbuild: '^0.28.0',
384
+ rimraf: '^5.0.0',
385
+ typescript: '^7.0.2'
386
+ };
387
+
388
+ /** The language client both VS Code extensions start the server with. */
389
+ const VSCODE_LANGUAGE_CLIENT: Readonly<Record<string, string>> = { 'vscode-languageclient': '^9.0.1' };
390
+
391
+ /** The VS Code API's types, at the oldest VS Code both extensions run in, which `engines` names too. */
392
+ const VSCODE_ENGINE = '^1.101.0';
393
+
394
+ /**
395
+ * What the GLSP head adds to the VS Code extension: the connector in the
396
+ * extension host and the diagram webview's starter, which bundles the client
397
+ * member.
398
+ */
399
+ const HOST_VSCODE_GLSP_FRAMEWORK_DEPENDENCIES: readonly string[] = [
400
+ '@hydranium/client-vscode',
401
+ '@hydranium/glsp-client',
402
+ '@hydranium/glsp-client-vscode',
403
+ '@hydranium/protocol'
404
+ ];
405
+ const HOST_VSCODE_GLSP_THIRD_PARTY_DEPENDENCIES: Readonly<Record<string, string>> = {
406
+ '@eclipse-glsp/client': '2.8.0',
407
+ '@eclipse-glsp/vscode-integration': '2.8.0',
408
+ '@eclipse-glsp/vscode-integration-webview': '2.8.0',
409
+ inversify: '^6.1.3',
410
+ 'vscode-jsonrpc': '9.0.0'
411
+ };
412
+
413
+ /** What the data head adds to the VS Code extension: the Show Model command's socket to it. */
414
+ const HOST_VSCODE_DATA_FRAMEWORK_DEPENDENCIES: readonly string[] = [
415
+ '@hydranium/client-vscode',
416
+ '@hydranium/data-client-vscode',
417
+ '@hydranium/protocol'
418
+ ];
419
+ // Exact, as the server's is: the socket's connection and the framework's must be one copy.
420
+ const HOST_VSCODE_DATA_THIRD_PARTY_DEPENDENCIES: Readonly<Record<string, string>> = { 'vscode-jsonrpc': '9.0.0' };
421
+
422
+ /** The VS Code extension's tools: the smoke tier, the download it runs in, the type check and the watch. */
423
+ const HOST_VSCODE_DEV_DEPENDENCIES: Readonly<Record<string, string>> = {
424
+ '@playwright/test': '^1.55.0',
425
+ '@types/node': '^22.0.0',
426
+ '@types/vscode': VSCODE_ENGINE,
427
+ '@vscode/test-electron': '^3.1.0',
428
+ concurrently: '^9.0.0',
429
+ rimraf: '^5.0.0',
430
+ typescript: '^7.0.2'
431
+ };
432
+
433
+ /**
434
+ * The Node major a standalone scaffold's `.nvmrc` and printed steps name.
435
+ * `langium generate` from the pinned `langium-cli` fails on Node 24.20 and
436
+ * later, which `engines` still admits.
437
+ */
438
+ export const SCAFFOLD_NODE_MAJOR = '22';
439
+
440
+ /**
441
+ * The exact pins of every member the composition emits, for a workspace root
442
+ * to declare too. npm installs a root's own dependencies at the top of the
443
+ * tree, so another member's version of one nests beneath that member instead of
444
+ * taking the place of the copy this package shares with the framework.
445
+ */
446
+ export function workspaceRootPins(composition: InitComposition): ReadonlyArray<readonly [string, string]> {
447
+ const { heads } = composition;
448
+ const members = initMembers(heads, composition.hosts);
449
+ const pins = new Map([
450
+ ...Object.entries(HEAD_THIRD_PARTY_DEPENDENCIES.base),
451
+ ...heads.flatMap(head => [
452
+ ...Object.entries(HEAD_THIRD_PARTY_DEPENDENCIES[head]),
453
+ ...Object.entries(PROTOCOL_THIRD_PARTY_DEPENDENCIES[head])
454
+ ]),
455
+ ...(members.includes('client') ? Object.entries(CLIENT_THIRD_PARTY_DEPENDENCIES) : []),
456
+ ...(members.includes('host-browser')
457
+ ? (['base', ...heads] as const).flatMap(head => Object.entries(HOST_BROWSER_THIRD_PARTY_DEPENDENCIES[head]))
458
+ : []),
459
+ ...(members.includes('host-vscode') && heads.includes('glsp') ? Object.entries(HOST_VSCODE_GLSP_THIRD_PARTY_DEPENDENCIES) : []),
460
+ ...(members.includes('host-vscode') && heads.includes('data') ? Object.entries(HOST_VSCODE_DATA_THIRD_PARTY_DEPENDENCIES) : []),
461
+ ...(members.includes('theia') ? theiaThirdPartyDependencies(heads) : []),
462
+ ...(members.includes('host-theia-browser') ? hostTheiaBrowserTheiaDependencies() : []),
463
+ ...(members.includes('host-theia-electron') ? hostTheiaElectronPins() : [])
464
+ ]);
465
+ return [...pins].filter(([, version]) => /^\d+\.\d+\.\d+$/.test(version)).sort(([left], [right]) => left.localeCompare(right));
466
+ }
467
+
468
+ /** Whether an npm version is 11.6.0 or later, the first that installs `vitest` 4.1's peer set; `11.6.0-rc.1` is earlier. */
469
+ function installsVitest41(npmVersion: string | undefined): boolean {
470
+ const [release, prerelease] = (npmVersion ?? '0.0.0').split('-', 2);
471
+ const [major, minor, patch] = release.split('.').map(Number);
472
+ return major > 11 || (major === 11 && (minor > 6 || (minor === 6 && (patch > 0 || prerelease === undefined))));
473
+ }
474
+
475
+ /**
476
+ * Whether the scaffold holds `vitest` below 4.1, whose peer set crashes npm
477
+ * before 11.6 (every npm a Node 22 release bundles) on the first install. Only a
478
+ * workspace root declaring a newer npm lifts it, and only when `init` runs under
479
+ * an npm known to be newer: npm does not enforce `packageManager`.
480
+ */
481
+ function pinsVitest(composition: InitComposition): boolean {
482
+ const workspace = composition.packaging.workspace;
483
+ return !(installsVitest41(workspace?.packageManagerNpm) && installsVitest41(workspace?.npmVersion));
484
+ }
485
+
486
+ /**
487
+ * The version a member pins a sibling member at: exact, at the version every
488
+ * member starts with. npm links a sibling only when the range admits its local
489
+ * version, and otherwise looks for it in the registry, where it was never
490
+ * published.
491
+ */
492
+ const MEMBER_PIN = '0.0.0';
493
+
494
+ /** A dependency block, sorted as npm writes it. */
495
+ function sortedBlock(dependencies: Readonly<Record<string, string>>, indent: string): string {
496
+ return Object.keys(dependencies)
497
+ .sort()
498
+ .map(name => `${indent}"${name}": "${dependencies[name]}"`)
499
+ .join(',\n');
500
+ }
501
+
502
+ /** The server's dependency block: the base and head set's packages and the protocol member. */
245
503
  function dependencyBlock(composition: InitComposition, indent: string): string {
246
- const merged: Record<string, string> = {};
247
- for (const head of composition.heads) {
504
+ const merged: Record<string, string> = { [memberPackageName(composition, 'protocol')]: MEMBER_PIN };
505
+ for (const head of ['base', ...composition.heads] as const) {
248
506
  Object.assign(merged, HEAD_THIRD_PARTY_DEPENDENCIES[head]);
249
507
  for (const framework of HEAD_FRAMEWORK_DEPENDENCIES[head]) {
250
508
  merged[framework] = frameworkPin(composition);
251
509
  }
252
510
  }
253
- return Object.keys(merged)
254
- .sort()
255
- .map(name => `${indent}"${name}": "${merged[name]}"`)
256
- .join(',\n');
511
+ return sortedBlock(merged, indent);
257
512
  }
258
513
 
259
514
  // JSON at two-space indent, not the three the `.ts` templates use: that is the
260
515
  // npm convention, and `npm install` rewrites `package.json` at two spaces
261
516
  // regardless — so three would not survive the adopter's first install.
262
517
  //
263
- // The KEY ORDER is `prettier-plugin-packagejson`'s canonical one, `private`
518
+ // The KEY ORDER is the one Oxfmt's `sortPackageJson` canonicalises to, `private`
264
519
  // before `license` included. Any other order is rewritten by the scaffolded
265
520
  // project's own first `format` run — a diff on a file the adopter never touched
266
521
  // — and it makes a byte-compare against a formatted copy of this emission
@@ -280,6 +535,11 @@ function dependencyBlock(composition: InitComposition, indent: string): string {
280
535
  // from this package's own grammar and can reach a consumer from nowhere else; a
281
536
  // listed path that does not exist yet is inert.
282
537
  //
538
+ // `exports` puts `createServices`, the one module reading the real filesystem,
539
+ // behind `./node`, so the root loads in a browser worker that has no `node:fs`.
540
+ // `./lib/*` and `./package.json` stay reachable for a host that resolves
541
+ // `<server>/lib/main.js` to spawn the server.
542
+ //
283
543
  // `repository` is deliberately NOT emitted while `author` is emitted empty. An
284
544
  // empty `author` is the form `npm init` itself writes and asserts nothing, but
285
545
  // `repository` is CONSUMED — the registry page, `npm repo` and publish
@@ -291,16 +551,9 @@ const PACKAGE_JSON = `{
291
551
  "version": "0.0.0",
292
552
  __PRIVATE__ "description": "__NAME__ language server, built with the Hydranium framework.",
293
553
  "keywords": [
294
- "hydranium",
295
- "langium",
296
- "language-server",
297
- "__PROJECT_ID__"
298
- ],
554
+ __KEYWORDS__ ],
299
555
  "license": "UNLICENSED",
300
556
  "author": "",
301
- "type": "module",
302
- "main": "lib/index.js",
303
- "types": "lib/index.d.ts",
304
557
  "bin": {
305
558
  __BIN__ },
306
559
  "files": [
@@ -308,17 +561,32 @@ __BIN__ },
308
561
  "src",
309
562
  "syntaxes"
310
563
  ],
564
+ "type": "module",
565
+ "main": "lib/index.js",
566
+ "types": "lib/index.d.ts",
567
+ "exports": {
568
+ ".": {
569
+ "types": "./lib/index.d.ts",
570
+ "default": "./lib/index.js"
571
+ },
572
+ "./node": {
573
+ "types": "./lib/node/services.d.ts",
574
+ "default": "./lib/node/services.js"
575
+ },
576
+ "./lib/*": "./lib/*",
577
+ "./package.json": "./package.json"
578
+ },
311
579
  "scripts": {
312
- "build": "npm run generate && tsc",
313
- "clean": "rimraf lib syntaxes src/language-server/generated src/language-server/generated-hydranium tsconfig.tsbuildinfo",
580
+ "build": "npm run generate && tsc -b",
581
+ "clean": "rimraf lib syntaxes src/language-server/generated src/language-server/generated-hydranium test/generated-hydranium tsconfig.tsbuildinfo",
314
582
  "generate": "npm run langium:generate && npm run generate:transfer-model",
315
- "generate:transfer-model": "hydranium-cli generate-transfer-model --ast-file src/language-server/generated/ast.ts --augmentation-file src/language-server/ast.ts --out-file src/language-server/generated-hydranium/transfer-model.ts --ast-builder-file src/language-server/generated-hydranium/ast-builder.ts --element-type-name __NAME__Element --terminals-name __NAME__Terminals --regen-command \\"Run: __NPM_RUN__ generate:transfer-model\\"",
583
+ "generate:transfer-model": "hydranium-cli generate-transfer-model --ast-file src/language-server/generated/ast.ts --augmentation-file src/language-server/ast.ts --out-file ../protocol/src/generated-hydranium/transfer-model.ts --ast-builder-file src/language-server/generated-hydranium/ast-builder.ts --transfer-builder-file test/generated-hydranium/transfer-builder.ts --languages-file ../protocol/src/generated-hydranium/languages.ts --element-type-name __NAME__Element --terminals-name __NAME__Terminals --regen-command \\"Run: __NPM_RUN__ generate:transfer-model\\"",
316
584
  "langium:generate": "langium generate",
317
585
  "langium:watch": "langium generate --watch",
318
- __LINT__ "start": "node lib/main.js --stdio",
586
+ __LINT__ "start": "node lib/main.js__START_ARGS__",
319
587
  "test": "npm run typecheck:test && vitest run",
320
588
  "typecheck:test": "tsc --noEmit -p tsconfig.test.json",
321
- "watch": "tsc --watch"
589
+ "watch": "concurrently --kill-others --names langium,transfer-model,tsc \\"npm run langium:watch\\" \\"npm run generate:transfer-model -- --watch\\" \\"tsc -b --watch\\""
322
590
  },
323
591
  "dependencies": {
324
592
  __DEPENDENCIES__
@@ -326,10 +594,11 @@ __DEPENDENCIES__
326
594
  "devDependencies": {
327
595
  "@hydranium/cli": "__FRAMEWORK_PIN__",
328
596
  "@types/node": "^22.0.0",
597
+ "concurrently": "^9.0.0",
329
598
  "langium-cli": "4.3.0",
330
599
  "rimraf": "^5.0.0",
331
- "typescript": "^5.8.0",
332
- "vitest": "^4.0.0"
600
+ "typescript": "^7.0.2",
601
+ "vitest": "__VITEST__"
333
602
  },
334
603
  "engines": {
335
604
  "node": ">=22.13"
@@ -338,16 +607,17 @@ __DEPENDENCIES__
338
607
  `;
339
608
 
340
609
  /**
341
- * How the scaffold names `npm run` when talking about itself.
610
+ * How the scaffold names `npm run` for one member's script.
342
611
  *
343
- * A workspace member's scripts are routinely invoked from the repo root, where
344
- * a bare `npm run` reaches the ROOT manifest and fails — so the regen hint a
345
- * generated file prints has to name the package, or it sends every reader who
346
- * follows it to the wrong place.
612
+ * Always with `--prefix`, from the directory commands are run in: the
613
+ * workspace root for a member, the project root for a standalone project. A
614
+ * bare `npm run` there reaches the ROOT manifest and fails, and the regen hint
615
+ * a generated file prints is read in `protocol/` as well, where the script it
616
+ * names does not exist.
347
617
  */
348
- function npmRun(composition: InitComposition): string {
618
+ function npmRun(composition: InitComposition, member: InitMember): string {
349
619
  const workspace = composition.packaging.workspace;
350
- return workspace === undefined ? 'npm run' : `npm --prefix ${workspace.targetPath} run`;
620
+ return `npm --prefix ${workspace === undefined ? member : `${workspace.targetPath}/${member}`} run`;
351
621
  }
352
622
 
353
623
  /**
@@ -359,7 +629,7 @@ function npmRun(composition: InitComposition): string {
359
629
  * name. Without the second key a scaffolded project has no command line that
360
630
  * reaches its own data head at all.
361
631
  *
362
- * Alphabetical, because `prettier-plugin-packagejson` sorts `bin` and any other
632
+ * Alphabetical, because Oxfmt's `sortPackageJson` sorts `bin` and any other
363
633
  * order is rewritten by the scaffolded project's first `format` run.
364
634
  */
365
635
  function binBlock(composition: InitComposition): string {
@@ -370,21 +640,39 @@ function binBlock(composition: InitComposition): string {
370
640
  return entries.map(([name, target]) => ` "${name}": "${target}"`).join(',\n') + '\n';
371
641
  }
372
642
 
373
- /** `package.json` with the name, the private flag and the dependency block all derived. */
643
+ /**
644
+ * A member's `lint` script line, over `directories`, or nothing.
645
+ *
646
+ * Emitted only where a root lint config says the repo lints. The absence is
647
+ * the dangerous direction: a task runner runs a script only where one is
648
+ * declared, so a package with no `lint` is SKIPPED rather than reported, and
649
+ * that reads as a clean lint. A wrong invocation is one visible line to edit.
650
+ */
651
+ function lintScript(member: InitComposition, directories: string): string {
652
+ const workspace = member.packaging.workspace;
653
+ if (workspace?.oxlintConfig !== undefined) {
654
+ const config = `${'../'.repeat(workspace.targetPath.split('/').length)}${workspace.oxlintConfig}`;
655
+ return ` "lint": "oxlint --report-unused-disable-directives --format stylish --config ${config} ${directories} --max-warnings 0",\n`;
656
+ }
657
+ return workspace?.eslintConfig !== undefined ? ` "lint": "eslint ${directories} --max-warnings 0",\n` : '';
658
+ }
659
+
660
+ /** The server's `package.json`, with the name, the private flag and the dependency block all derived. */
374
661
  function packageJson(composition: InitComposition): string {
375
- const { scope } = composition.packaging;
376
- const packageName = scope === undefined ? composition.projectId : `${scope}/${composition.projectId}`;
377
- // Emitted only where a root eslint config says the repo lints. The absence is
378
- // the dangerous direction: a task runner runs a script only where one is
379
- // declared, so a package with no `lint` is SKIPPED rather than reported, and
380
- // that reads as a clean lint. A wrong invocation is one visible line to edit.
381
- const lint = composition.packaging.workspace?.eslintConfig === undefined ? '' : ' "lint": "eslint src test --max-warnings 0",\n';
662
+ const keywords =
663
+ ['hydranium', 'langium', 'language-server', composition.projectId]
664
+ .sort()
665
+ .map(keyword => ` ${JSON.stringify(keyword)}`)
666
+ .join(',\n') + '\n';
382
667
  return project(PACKAGE_JSON, composition)
383
- .replace('__PACKAGE_NAME__', packageName)
668
+ .replace('__PACKAGE_NAME__', memberPackageName(composition, 'server'))
669
+ .replace('__KEYWORDS__', keywords)
384
670
  .replace('__BIN__', binBlock(composition))
385
- .replace('__LINT__', lint)
671
+ .replace('__LINT__', lintScript(forMember(composition, 'server'), 'src test'))
672
+ .replace('__START_ARGS__', composition.heads.includes('lsp') ? ' --stdio' : ' ../workspace')
673
+ .replace('__VITEST__', pinsVitest(composition) ? '~4.0.18' : '^4.0.0')
386
674
  .replace('__PRIVATE__', composition.packaging.private ? ' "private": true,\n' : '')
387
- .replace('__NPM_RUN__', npmRun(composition))
675
+ .replace('__NPM_RUN__', npmRun(composition, 'server'))
388
676
  .replace('__FRAMEWORK_PIN__', frameworkPin(composition))
389
677
  .replace('__DEPENDENCIES__', dependencyBlock(composition, ' '));
390
678
  }
@@ -452,6 +740,24 @@ const TSCONFIG_COMPILER_OPTIONS: ReadonlyArray<readonly [string, JsonValue]> = [
452
740
  ['types', ['node']]
453
741
  ];
454
742
 
743
+ /** The protocol member's compiler options, pruned against a workspace base like the server's. */
744
+ const PROTOCOL_COMPILER_OPTIONS: ReadonlyArray<readonly [string, JsonValue]> = [
745
+ ['target', 'ES2022'],
746
+ ['lib', ['ES2022']],
747
+ ['module', 'NodeNext'],
748
+ ['moduleResolution', 'NodeNext'],
749
+ ['rootDir', 'src'],
750
+ ['outDir', 'lib'],
751
+ ['strict', true],
752
+ ['skipLibCheck', true],
753
+ ['declaration', true],
754
+ // The server's `tsc -b` builds this project through a reference, which
755
+ // `tsc` refuses unless the referenced project is composite.
756
+ ['composite', true],
757
+ // No ambient Node types: a browser client compiles against this package.
758
+ ['types', []]
759
+ ];
760
+
455
761
  /**
456
762
  * The options that describe where THIS package's own files live. Never pruned,
457
763
  * and emitted first in the workspace case: a base config that supplied them
@@ -460,9 +766,20 @@ const TSCONFIG_COMPILER_OPTIONS: ReadonlyArray<readonly [string, JsonValue]> = [
460
766
  */
461
767
  const PACKAGE_LOCAL_OPTIONS: readonly string[] = ['rootDir', 'outDir'];
462
768
 
463
- /** Compare two JSON option values. Sound here because compiler options are scalars and flat arrays. */
464
- function jsonEquals(left: JsonValue | undefined, right: JsonValue): boolean {
465
- return JSON.stringify(left) === JSON.stringify(right);
769
+ /**
770
+ * The enum-valued options of {@link TSCONFIG_COMPILER_OPTIONS}, whose values
771
+ * `tsc` reads case-insensitively, so `nodenext` and `NodeNext` are one value.
772
+ * An enum-valued option added there belongs here too.
773
+ */
774
+ const CASE_INSENSITIVE_OPTIONS: readonly string[] = ['target', 'lib', 'module', 'moduleResolution'];
775
+
776
+ /** Compare two option values. Sound here because compiler options are scalars and flat arrays. */
777
+ function optionEquals(key: string, left: JsonValue | undefined, right: JsonValue): boolean {
778
+ const normalise = (value: JsonValue | undefined) => {
779
+ const text = JSON.stringify(value);
780
+ return CASE_INSENSITIVE_OPTIONS.includes(key) ? text?.toLowerCase() : text;
781
+ };
782
+ return normalise(left) === normalise(right);
466
783
  }
467
784
 
468
785
  /**
@@ -472,112 +789,57 @@ function jsonEquals(left: JsonValue | undefined, right: JsonValue): boolean {
472
789
  * the same key: inheriting `"module": "CommonJS"` where the scaffold needs
473
790
  * `NodeNext` would break every emitted import, so a differing base value is a
474
791
  * reason to keep the override rather than to trust the parent.
792
+ *
793
+ * `member` is the composition as that member sees it, so `extends` reaches the
794
+ * workspace base from the member's own directory.
475
795
  */
476
- function tsconfigJson(composition: InitComposition): string {
477
- const workspace = composition.packaging.workspace;
796
+ function tsconfigJson(
797
+ member: InitComposition,
798
+ compilerOptions: ReadonlyArray<readonly [string, JsonValue]>,
799
+ include: string,
800
+ references = ''
801
+ ): string {
802
+ const workspace = member.packaging.workspace;
478
803
  const base = workspace?.baseTsconfig === undefined ? undefined : (workspace.baseCompilerOptions ?? {});
479
804
  const options =
480
805
  base === undefined
481
- ? TSCONFIG_COMPILER_OPTIONS
806
+ ? compilerOptions
482
807
  : [
483
- ...TSCONFIG_COMPILER_OPTIONS.filter(([key]) => PACKAGE_LOCAL_OPTIONS.includes(key)),
484
- ...TSCONFIG_COMPILER_OPTIONS.filter(([key, value]) => !PACKAGE_LOCAL_OPTIONS.includes(key) && !jsonEquals(base[key], value))
808
+ ...compilerOptions.filter(([key]) => PACKAGE_LOCAL_OPTIONS.includes(key)),
809
+ ...compilerOptions.filter(([key, value]) => !PACKAGE_LOCAL_OPTIONS.includes(key) && !optionEquals(key, base[key], value))
485
810
  ];
486
811
  const extendsLine = workspace?.baseTsconfig === undefined ? '' : ` "extends": "${workspace.baseTsconfig}",\n`;
487
- const body = options.map(([key, value]) => ` "${key}": ${JSON.stringify(value)}`).join(',\n');
488
- return `{\n${extendsLine} "compilerOptions": {\n${body}\n },\n "include": ["src", "src/**/*.json"]\n}\n`;
489
- }
490
-
491
- // `isolatedModules` is what makes this check agree with the transform that
492
- // actually runs the tests. `npm test` is `typecheck:test && vitest run`, and
493
- // vitest compiles through esbuild — a per-file transform with no type
494
- // information, which cannot tell a re-exported TYPE from a re-exported value.
495
- // Without the flag `tsc` accepts `export { SomeType } from './x'` that esbuild
496
- // then emits as a real import of a symbol that does not exist at runtime, so
497
- // the typecheck passes and the suite fails with a confusing missing-export.
498
- const TSCONFIG_TEST = `{
499
- "extends": "./tsconfig.json",
500
- "compilerOptions": {
501
- "rootDir": ".",
502
- "noEmit": true,
503
- "isolatedModules": true,
504
- "types": ["node"]
505
- },
506
- "include": ["src", "test", "src/**/*.json"]
812
+ // An array spaced as a formatter writes it, which `JSON.stringify` does not.
813
+ const json = (value: JsonValue): string => (Array.isArray(value) ? `[${value.map(json).join(', ')}]` : JSON.stringify(value));
814
+ const body = options.map(([key, value]) => ` "${key}": ${json(value)}`).join(',\n');
815
+ const referencesLine = references === '' ? '' : `,\n "references": ${references}`;
816
+ return `{\n${extendsLine} "compilerOptions": {\n${body}\n },\n "include": ${include}${referencesLine}\n}\n`;
507
817
  }
508
- `;
509
-
510
- const VITEST_CONFIG = `import { defineConfig } from 'vitest/config';
511
-
512
- // Vitest transforms TypeScript itself and resolves \`.js\` specifiers to their
513
- // \`.ts\` source, so tests import from \`../src/\` with the same specifiers the
514
- // compiled output uses. \`include\` is scoped to \`test/\` so \`lib/\` is never
515
- // scanned; \`npm test\` runs \`typecheck:test\` first, because the esbuild
516
- // transform strips types without checking them.
517
-
518
- export default defineConfig({
519
- test: {
520
- environment: 'node',
521
- include: ['test/**/*.{test,spec}.ts']
522
- }
523
- });
524
- `;
525
-
526
- const GITIGNORE = `node_modules/
527
- lib/
528
- *.tsbuildinfo
529
-
530
- # Langium-generated TextMate grammar (rewritten by every \`langium generate\`).
531
- syntaxes/
532
- `;
533
818
 
534
819
  /**
535
- * The workspace-member `.gitignore` — one entry, and the one entry a root
536
- * cannot be assumed to have.
537
- *
538
- * A member inherits the root's rules, and `node_modules/`, `lib/` and
539
- * `*.tsbuildinfo` are in every monorepo root already, so repeating them here
540
- * would be three lines to keep in step for no coverage. `syntaxes/` is not like
541
- * them: it is a Langium artefact, so a root that has never held a Langium
542
- * package has no rule for it, and the first `langium generate` then offers
543
- * generated output up for commit with nothing to warn the adopter. Dropping the
544
- * whole file rather than this subset is the mistake this template exists to
545
- * undo.
546
- */
547
- const GITIGNORE_WORKSPACE_MEMBER = `# The workspace root already covers \`node_modules/\`, \`lib/\` and \`*.tsbuildinfo\`.
548
- # It has no reason to know about this one: the TextMate grammar is a Langium
549
- # artefact, rewritten by every \`langium generate\`, so a root that has never held
550
- # a Langium package ignores nothing here and the generated file is offered for
551
- # commit.
552
- syntaxes/
553
- `;
554
-
555
- /** The terminals every grammar needs, shared verbatim by the fragment and the lone-grammar case. */
556
- const TERMINALS = `hidden terminal WS: /\\s+/;
557
- terminal ID: /[_a-zA-Z][\\w_]*/;
558
- hidden terminal SL_COMMENT: /\\/\\/[^\\n\\r]*/;
559
- hidden terminal ML_COMMENT: /\\/\\*[\\s\\S]*?\\*\\//;
560
- `;
820
+ * The server's `tsconfig.json`. It references the protocol member, so `tsc -b`
821
+ * compiles protocol first, after `generate` has written its generated modules.
822
+ */
823
+ function serverTsconfigJson(composition: InitComposition): string {
824
+ return tsconfigJson(
825
+ forMember(composition, 'server'),
826
+ TSCONFIG_COMPILER_OPTIONS,
827
+ '["src", "src/**/*.json"]',
828
+ '[{ "path": "../protocol" }]'
829
+ );
830
+ }
561
831
 
562
832
  /**
563
- * The shared lexical fragment, emitted only for a multi-grammar project.
564
- *
565
- * The alternative — every grammar declaring its own `WS` / `ID` — lets the token
566
- * sets drift apart.
833
+ * The terminals every grammar needs: the shared fragment's text after its
834
+ * leading comment run, so a lone grammar declares the same set.
567
835
  */
568
- const COMMON_GRAMMAR = `// Shared lexical basis for this project's grammars. Imported, never registered:
569
- // it has no entry rule and no \`langium-config.json\` entry, so it is a fragment
570
- // rather than a language.
571
- //
572
- // Keeping the tokens here rather than in one of the languages means a grammar
573
- // imports \`common\` for its TOKENS and another language only when it needs that
574
- // language's TYPES — separate reasons that are worth keeping separate.
575
-
576
- ${TERMINALS}`;
836
+ function terminals(): string {
837
+ return template('server/src/grammar/common.langium').replace(/^(\/\/.*\n)*\n/, '');
838
+ }
577
839
 
578
840
  /** One starter grammar. `shared` decides whether it imports the fragment or declares its own terminals. */
579
841
  function grammarFile(shared: boolean): string {
580
- const lexis = shared ? "import './common'\n" : `\n${TERMINALS}`;
842
+ const lexis = shared ? "import './common'\n" : `\n${terminals()}`;
581
843
  return `grammar __GRAMMAR__
582
844
  ${shared ? '\n' + lexis : ''}
583
845
  // A minimal starter grammar — replace with your own language. \`__NODE_RULE__\` is
@@ -641,7 +903,10 @@ export const __CONFIG_ROOT_CONST___CONFIGURATION_ROOT = '__PROJECT_ID__';
641
903
  : `const __NAME__SharedModule: Module<__NAME__SharedServices, PartialLangiumSharedServices> = {};`;
642
904
 
643
905
  const serializerImports = composition.grammars
644
- .map(grammar => `import { ${grammar.grammar}Serializer } from './${grammar.grammarId}-serializer.js';`)
906
+ .flatMap(grammar => [
907
+ `import { ${grammar.grammar}Serializer } from './${grammar.grammarId}-serializer.js';`,
908
+ `import { ${grammar.grammar}ValidationContribution } from './${grammar.grammarId}-validation.js';`
909
+ ])
645
910
  .join('\n');
646
911
 
647
912
  // Each language gets its own adopter module because `Serializer` is a
@@ -653,6 +918,11 @@ export const __CONFIG_ROOT_CONST___CONFIGURATION_ROOT = '__PROJECT_ID__';
653
918
  grammar => `const ${grammar.grammar}LanguageModule: Module<__NAME__Services, PartialLangiumServices & DeepPartial<ServerAddedServices>> = {
654
919
  serializer: {
655
920
  Serializer: services => new ${grammar.grammar}Serializer(services)
921
+ },
922
+ validation: {
923
+ checks: {
924
+ names: () => new ${grammar.grammar}ValidationContribution()
925
+ }
656
926
  }
657
927
  };`
658
928
  )
@@ -674,11 +944,11 @@ export const __CONFIG_ROOT_CONST___CONFIGURATION_ROOT = '__PROJECT_ID__';
674
944
 
675
945
  const text = `// DI bootstrap for __NAME__. Composes the framework defaults with adopter
676
946
  // overrides via Langium's \`inject()\` (through the framework's
677
- // \`createIntegrationServices\`). Each adopter module binds ONE slot — its
678
- // language's \`Serializer\`, which the framework cannot default because a
679
- // concrete syntax is grammar knowledge. Everything else (scope, naming, project
680
- // management, build pipeline) boots on the framework defaults; scope
681
- // computation, validation checks and AST extensions go in these same modules.
947
+ // \`createIntegrationServices\`). Each adopter module binds its language's
948
+ // \`Serializer\`, which the framework cannot default because a concrete syntax
949
+ // is grammar knowledge, and its validation checks. Everything else (scope,
950
+ // naming, project management, build pipeline) boots on the framework defaults;
951
+ // scope computation and AST extensions go in these same modules.
682
952
  //
683
953
  // Note which generated symbol comes from which name: the SHARED module is
684
954
  // \`__NAME__GeneratedSharedModule\` (from \`projectName\`) and there is one of it,
@@ -693,7 +963,11 @@ export const __CONFIG_ROOT_CONST___CONFIGURATION_ROOT = '__PROJECT_ID__';
693
963
  : `
694
964
  //
695
965
  // A second grammar goes in the \`additionalLanguages\` option of
696
- // \`createIntegrationServices\`, generated from this same \`langium-config.json\`.`
966
+ // \`createIntegrationServices\`, generated from this same \`langium-config.json\`.
967
+ // With several languages, bind \`lsp.configurationRoot\` in
968
+ // \`__NAME__SharedModule\`, or the framework warns and takes the first
969
+ // language's id. Type that module's second \`Module\` argument as
970
+ // \`PartialLangiumSharedServices & { lsp: { configurationRoot: string } }\`.`
697
971
  }
698
972
 
699
973
  ${importList(
@@ -766,185 +1040,135 @@ ${returnType}
766
1040
  return project(text, composition);
767
1041
  }
768
1042
 
769
- const SERVICES = `// Zero-arg service factory for the headless \`hydranium-cli\` tooling: the
770
- // \`reflect\` / \`lint-grammar\` / \`validate\` subcommands import this via
771
- // \`--services ./lib/services.js\`. The head wires its own filesystem here.
772
- //
773
- // The contract is language-count-agnostic — a second grammar needs no edit here.
774
-
775
- import { NodeFileSystem } from '@hydranium/core/node';
776
- import { create__NAME__Services } from './language-server/__PROJECT_ID__-module.js';
777
-
778
- export function createServices(): ReturnType<typeof create__NAME__Services> {
779
- return create__NAME__Services({ ...NodeFileSystem });
1043
+ /** One exported constant of the protocol member's `head-ports.ts`. */
1044
+ interface HeadPortConstant {
1045
+ readonly name: string;
1046
+ readonly value: string;
1047
+ readonly doc: string;
780
1048
  }
781
- `;
782
-
783
- const AST = `// The language's AST entry point: a re-export of what \`langium generate\`
784
- // emits, plus anywhere you augment those types.
785
- //
786
- // Import the AST from HERE rather than from \`./generated/ast.js\`, so any
787
- // augmentation below travels with every import. One \`langium-cli\` run over N
788
- // grammars emits ONE combined AST module sharing one reflection, so a further
789
- // grammar needs no change here.
790
- //
791
- // \`generate:transfer-model\` reads this file as its \`--augmentation-file\`: the
792
- // generated wire types are derived from the AST *as augmented*, not from the
793
- // raw generated module. Augment a type here and the transfer model follows.
794
- //
795
- // A \`@derived\` property is computed at build time rather than parsed, so it is
796
- // declared here and populated by an AST-extension contribution:
797
- //
798
- // declare module './generated/ast.js' {
799
- // interface __ENTRY_RULE__ {
800
- // /** @derived Populated by an \`ast.extensions.computedProperties\` contribution. */
801
- // readonly _summary?: string;
802
- // }
803
- // }
804
-
805
- export * from './generated/ast.js';
806
- `;
807
1049
 
808
1050
  /**
809
- * The starter serializer — the concrete-syntax emitter for ONE grammar.
1051
+ * How a host finds each socket head's port, in emission order: an LSP request
1052
+ * when the LSP head publishes the ports, else the environment variable
1053
+ * `main.ts` reads a port from.
810
1054
  *
811
- * Emitted per grammar, not per project, because `services.serializer.Serializer`
812
- * is a per-language slot and a serializer is grammar-shaped by definition. That
813
- * is also why the framework refuses to default it: its `UnboundSerializer`
814
- * throws, naming the binding to add, rather than guessing a syntax.
815
- */
816
- const SERIALIZER = `// Concrete-syntax emitter for __GRAMMAR__ — the parser's inverse, turning a
817
- // model back into text this grammar accepts. Derived from the starter grammar
818
- // exactly as \`generated/ast.ts\` is, so replacing the grammar replaces this too.
819
- //
820
- // Without it every structured write fails: the framework's default binding at
821
- // \`services.serializer.Serializer\` THROWS, because a concrete syntax is
822
- // language knowledge no framework can derive. \`ModelService.update\` / \`save\`,
823
- // the data head's \`saveModelDocument\` and a GLSP \`SaveModelAction\` all reach
824
- // it.
825
- //
826
- // \`AbstractSerializer\`'s generic property walk lays out FORMAT-structured
827
- // output — its YAML and JSON subclasses are what it exists for — and cannot
828
- // produce a keyword-delimited syntax like \`node a -> b\`. So \`serializeNode\` is
829
- // a per-\`$type\` emitter here and the two array hooks are unreachable.
830
-
831
- import { AbstractSerializer } from '@hydranium/core';
832
- import type { AstNode } from '@hydranium/langium';
833
- import { type __ENTRY_RULE__, type __NODE_RULE__, is__ENTRY_RULE__, is__NODE_RULE__ } from './ast.js';
834
-
835
- export class __GRAMMAR__Serializer extends AbstractSerializer<__ENTRY_RULE__> {
836
- protected override serializeNode(node: AstNode | Record<string, unknown>): string {
837
- if (is__ENTRY_RULE__(node)) {
838
- return node.nodes.map(child => this.emitNode(child)).join('\\n');
839
- }
840
- if (is__NODE_RULE__(node)) {
841
- return this.emitNode(node);
842
- }
843
- // Defensive: a rule added to the grammar with no emitter added here.
844
- throw new Error(\`__GRAMMAR__Serializer: no emitter for $type \${(node as AstNode).$type}\`);
845
- }
846
-
847
- /** Unreachable — this grammar's one list is emitted by its \`__ENTRY_RULE__\` parent. */
848
- protected override serializeArray(): string {
849
- throw new Error('__GRAMMAR__Serializer: arrays are emitted by the per-$type parent, not the generic dispatch.');
850
- }
1055
+ * Keyed by the PROJECT rather than by a language: one server of each kind per
1056
+ * process serves every registered grammar, so a language-derived name would tie
1057
+ * a project-level endpoint to whichever grammar was scaffolded first.
1058
+ */
1059
+ function headPortConstants(composition: InitComposition): HeadPortConstant[] {
1060
+ const upper = screamingSnake(composition.projectId);
1061
+ const lsp = composition.heads.includes('lsp');
1062
+ return socketHeads(composition).map(head =>
1063
+ lsp
1064
+ ? {
1065
+ name: `${upper}_${head.key}_PORT_COMMAND`,
1066
+ value: `${composition.projectId}/${head.path}/port`,
1067
+ doc: `LSP request the host queries to discover the ${head.label} socket port.`
1068
+ }
1069
+ : {
1070
+ name: `${upper}_${head.key}_PORT_ENV`,
1071
+ value: `${upper}_${head.key}_PORT`,
1072
+ doc: `Environment variable naming the ${head.label} socket port when no \`--${head.path}-port\` flag does.`
1073
+ }
1074
+ );
1075
+ }
851
1076
 
852
- /** Unreachable — same reasoning as {@link serializeArray}. */
853
- protected override serializeReferenceArray(): string {
854
- throw new Error('__GRAMMAR__Serializer: reference arrays are emitted by the per-$type parent, not the generic dispatch.');
855
- }
1077
+ /** The socket heads of the composition, as `head-ports.ts` names them. */
1078
+ function socketHeads(composition: InitComposition) {
1079
+ return [
1080
+ ...(composition.heads.includes('data')
1081
+ ? [{ key: 'DATA_SERVER', path: 'data-server', command: 'dataServer', label: 'data-server' }]
1082
+ : []),
1083
+ ...(composition.heads.includes('glsp') ? [{ key: 'GLSP_SERVER', path: 'glsp-server', command: 'glsp', label: 'GLSP' }] : [])
1084
+ ];
1085
+ }
856
1086
 
857
- /**
858
- * \`serializeReferenceText\` rather than \`node.target?.$refText\`: it is the one
859
- * read that spans BOTH input shapes. A transfer model reaching
860
- * \`serializeTransfer\` carries \`target\` as a plain string rather than a
861
- * \`Reference\`, and a serializer that reaches for \`$refText\` directly emits
862
- * the AST correctly and drops every reference on the transfer path.
863
- */
864
- private emitNode(node: __NODE_RULE__): string {
865
- const target = this.serializeReferenceText(node.target);
866
- return target === undefined ? \`node \${node.name}\` : \`node \${node.name} -> \${target}\`;
867
- }
1087
+ /** Whether the composition emits the servers-only extension, which VS Code starts the server through and a Theia app sideloads. */
1088
+ function emitsVscodeServers(composition: InitComposition): boolean {
1089
+ return initMembers(composition.heads, composition.hosts).includes('vscode-servers');
868
1090
  }
869
- `;
870
1091
 
871
1092
  /**
872
- * The exported constant names for the head set, in emission order. Both are
873
- * keyed by the PROJECT rather than by a language: one server of each kind per
874
- * process serves every registered grammar, so a language-derived name would tie
875
- * a project-level endpoint to whichever grammar was scaffolded first.
1093
+ * The host commands the servers extension answers each socket head's port
1094
+ * under, for a host without a language client of its own.
876
1095
  */
877
- function portCommandNames(composition: InitComposition): string[] {
1096
+ function hostCommandConstants(composition: InitComposition): HeadPortConstant[] {
1097
+ if (!emitsVscodeServers(composition)) {
1098
+ return [];
1099
+ }
878
1100
  const upper = screamingSnake(composition.projectId);
879
- return [
880
- ...(composition.heads.includes('data') ? [`${upper}_DATA_SERVER_PORT_COMMAND`] : []),
881
- ...(composition.heads.includes('glsp') ? [`${upper}_GLSP_PORT_COMMAND`] : [])
882
- ];
1101
+ return socketHeads(composition).map(head => ({
1102
+ name: `${upper}_${head.key}_HOST_COMMAND`,
1103
+ value: `${composition.projectId}.port.${head.command}`,
1104
+ doc: `Host command the servers extension answers with the ${head.label} socket port.`
1105
+ }));
883
1106
  }
884
1107
 
885
1108
  /**
886
- * The socket heads' discovery commands, as an importable module.
1109
+ * The socket heads' port commands or variables, in the protocol member.
887
1110
  *
888
- * Deliberately NOT declared in `main.ts`. A host shell has to name the same
889
- * string to reach the head, and `main.ts` opens a connection at module scope,
890
- * so importing a constant from it would start a server. A host that retypes the
891
- * literal instead gets no error when it drifts: the framework's port poll
892
- * defaults to `findPortAttempts = -1`, so a wrong command retries forever
893
- * rather than failing.
1111
+ * A host shell has to name the same string the server reads, and reaches it
1112
+ * here without depending on the server. A host that retypes the literal
1113
+ * instead gets no error when it drifts: the framework's port poll defaults to
1114
+ * `findPortAttempts = -1`, so a wrong command retries forever rather than
1115
+ * failing, and a wrong variable is never read.
894
1116
  */
895
1117
  function headPortsFile(composition: InitComposition): string {
896
- const upper = screamingSnake(composition.projectId);
897
- const data = composition.heads.includes('data');
898
- const glsp = composition.heads.includes('glsp');
899
- const blocks = [
900
- ...(data
901
- ? [
902
- `/** LSP request the host queries to discover the data-server socket port. */\nexport const ${upper}_DATA_SERVER_PORT_COMMAND = '${composition.projectId}/data-server/port';`
903
- ]
904
- : []),
905
- ...(glsp
906
- ? [
907
- `/** LSP request the host queries to discover the GLSP socket port. */\nexport const ${upper}_GLSP_PORT_COMMAND = '${composition.projectId}/glsp/port';`
908
- ]
909
- : [])
910
- ];
911
- return `// The LSP requests a host queries to discover this server's socket head${blocks.length > 1 ? 's' : ''}.
1118
+ const constants = [...headPortConstants(composition), ...hostCommandConstants(composition)];
1119
+ const blocks = constants.map(constant => `/** ${constant.doc} */\nexport const ${constant.name} = '${constant.value}';`);
1120
+ const socketHeadCount = socketHeads(composition).length;
1121
+ const heads = `socket head${socketHeadCount > 1 ? 's' : ''}`;
1122
+ const opening = composition.heads.includes('lsp')
1123
+ ? `// The LSP requests a host queries to discover this server's ${heads}.`
1124
+ : `// The environment variables that name the ports of this server's ${heads}.`;
1125
+ const usage = composition.heads.includes('lsp')
1126
+ ? `// The server publishes them and a host shell has to name the same string to
1127
+ // reach the head; both import them from here. A shell that retypes the literal
1128
+ // gets no error when it drifts: the framework's port poll retries indefinitely
1129
+ // by default.`
1130
+ : `// The server reads them and a process that starts it sets them; both import
1131
+ // them from here. A variable retyped with a typo is never read, and the head
1132
+ // then listens on whichever port is free.`;
1133
+ const hostCommands = emitsVscodeServers(composition)
1134
+ ? `
1135
+ //
1136
+ // The host commands are the same ports for a host with no language client,
1137
+ // such as a Theia app sideloading the servers extension: it runs the command
1138
+ // and the extension sends the request.`
1139
+ : '';
1140
+ return `${opening}
912
1141
  //
913
- // Both are keyed by the PROJECT, not the language: one server of each kind per
1142
+ // ${socketHeadCount > 1 ? 'Both are' : 'It is'} keyed by the PROJECT, not the language: one server of each kind per
914
1143
  // process serves every registered grammar, so a language-derived name would tie
915
1144
  // a project-level endpoint to whichever grammar was scaffolded first.
916
1145
  //
917
- // They live here rather than in \`main.ts\` because a host shell has to name the
918
- // same string to reach the head, and \`main.ts\` is an executable entry — nothing
919
- // can import from it. A shell that retypes the literal gets no error when it
920
- // drifts: the framework's port poll retries indefinitely by default. Import
921
- // these instead, and assert any host-side copy against them.
1146
+ ${usage}${hostCommands}
922
1147
 
923
1148
  ${blocks.join('\n\n')}
924
1149
  `;
925
1150
  }
926
1151
 
927
- const INDEX = `// Public surface of the __NAME__ language server: the DI factory, the generated
928
- // AST, and the headless \`createServices\` entry.
1152
+ /**
1153
+ * The server's root entry: the DI factory, the generated AST and each diagram
1154
+ * module, all loadable in a browser worker.
1155
+ */
1156
+ function indexFile(composition: InitComposition): string {
1157
+ const diagrams = composition.grammars.filter(grammar => grammar.diagram);
1158
+ const diagramPhrase = diagrams.length === 0 ? '' : diagrams.length === 1 ? ', plus the diagram module' : ', plus the diagram modules';
1159
+ const text = `// Public surface of the __NAME__ language server: the DI factory and the
1160
+ // generated AST${diagramPhrase}.
929
1161
  //
930
- // The entry points under \`src/\` are deliberately NOT re-exported. Each opens a
931
- // transport at module scope, so importing one starts a server as a side effect
932
- // — which is why they are \`bin\` targets and this file is \`main\`.
1162
+ // Everything here loads in a browser worker as well as in Node, so a host can
1163
+ // compose the language wherever it runs it. \`createServices\`, which reads the
1164
+ // real filesystem, is the package's \`./node\` entry instead. The entry points
1165
+ // under \`src/\` are not re-exported either: each opens a transport at module
1166
+ // scope, so importing one starts a server, which is why they are \`bin\` targets.
933
1167
 
934
1168
  export * from './language-server/__PROJECT_ID__-module.js';
935
1169
  export * from './language-server/ast.js';
936
- export { createServices } from './services.js';
937
- `;
938
-
939
- /**
940
- * The public surface, plus the head-port commands when there is a socket head.
941
- *
942
- * The commands belong here rather than only in `head-ports.ts` so a host shell
943
- * reaches them from the package root, the same way it reaches `createServices`.
944
- */
945
- function indexFile(composition: InitComposition): string {
946
- const base = project(INDEX, composition);
947
- return portCommandNames(composition).length ? `${base}export * from './head-ports.js';\n` : base;
1170
+ ${diagrams.map(grammar => `export * from './glsp/${grammar.grammarId}/diagram-module.js';\n`).join('')}`;
1171
+ return project(text, composition);
948
1172
  }
949
1173
 
950
1174
  /**
@@ -972,12 +1196,14 @@ const SHEBANG = '#!/usr/bin/env node\n';
972
1196
  */
973
1197
  function mainFile(composition: InitComposition): string {
974
1198
  const columns = columnsFor(composition);
975
- const roots = [...composition.grammars.map(grammar => grammar.entryRule)].sort();
1199
+ const roots = composition.grammars.map(grammar => grammar.entryRule).sort();
976
1200
  const upper = screamingSnake(composition.projectId);
1201
+ const lsp = composition.heads.includes('lsp');
977
1202
  const data = composition.heads.includes('data');
978
1203
  const glsp = composition.heads.includes('glsp');
979
1204
  const diagrams = composition.grammars.filter(grammar => grammar.diagram);
980
1205
  const plural = roots.length > 1 ? 's' : '';
1206
+ const portFlags = [...(data ? ['--data-server-port'] : []), ...(glsp ? ['--glsp-server-port'] : [])];
981
1207
 
982
1208
  const headNames = composition.heads.map(head =>
983
1209
  head === 'lsp' ? 'the Langium LSP head' : head === 'data' ? 'a socket data-server (model server) head' : 'a GLSP head'
@@ -991,7 +1217,7 @@ function mainFile(composition: InitComposition): string {
991
1217
  // `reflect-metadata` must be imported before anything that reads a
992
1218
  // decorator's emitted metadata, which inversify does at module scope.
993
1219
  const reflectImport = glsp ? "import 'reflect-metadata';\n" : '';
994
- const coreNodeSymbols = ['NodeFileSystem', ...(data ? ['publishPortOnLspConnection', 'startSocketServer'] : [])];
1220
+ const coreNodeSymbols = ['NodeFileSystem', ...(data ? [...(lsp ? ['publishPortOnLspConnection'] : []), 'startSocketServer'] : [])];
995
1221
  const glspImports = glsp
996
1222
  ? `import { ServerModule } from '@eclipse-glsp/server/node.js';
997
1223
  import { GlspClientLogger, HydraniumGlspAppModule } from '@hydranium/glsp-server';
@@ -1008,46 +1234,59 @@ import { startGlspServer } from '@hydranium/glsp-server/node';
1008
1234
  // \`TransferElement\` structurally, so naming the AST type here compiles fine and
1009
1235
  // silently tells every typed client that a reference is a resolvable object
1010
1236
  // rather than a name.
1011
- ${importList(roots, './language-server/generated-hydranium/transfer-model.js', columns, true)}
1237
+ ${importList(roots, memberPackageName(composition, 'protocol'), columns, true)}
1012
1238
  `
1013
1239
  : '';
1014
1240
 
1015
- // The commands live in `head-ports.ts`, not here: a host shell has to name
1016
- // the same string to reach the head, and this file is an executable entry, so
1017
- // nothing can import from it.
1018
- const portCommands = portCommandNames(composition).length
1019
- ? importList(portCommandNames(composition), './head-ports.js', columns) + '\n'
1020
- : '';
1021
-
1022
- const dataBlock = data
1023
- ? `
1241
+ // The names live in the protocol member, not here: a host shell has to name
1242
+ // the same string to reach the head, and this file is an executable entry,
1243
+ // so nothing can import from it.
1244
+ const portNames = headPortConstants(composition).map(constant => constant.name);
1245
+ const portImports = portNames.length ? importList(portNames, memberPackageName(composition, 'protocol'), columns) + '\n' : '';
1246
+
1247
+ const dataBlock = !data
1248
+ ? ''
1249
+ : !lsp
1250
+ ? `
1251
+ // Data-server head: each accepted client gets its own DataServer.
1252
+ const dataServer = startSocketServer(
1253
+ { shared, workspace, port: portFrom('data-server-port', ${upper}_DATA_SERVER_PORT_ENV), logTag: 'ModelServer', logger: shared.Logger },
1254
+ dataConnection => {
1255
+ new DataServer<${roots.join(' | ')}>(dataConnection, shared);
1256
+ return { dispose: () => undefined };
1257
+ }
1258
+ );
1259
+ `
1260
+ : `
1024
1261
  // Data-server head alongside LSP: binds an ephemeral port, published over the LSP
1025
1262
  // connection for the host to discover. Each accepted client gets its own DataServer.
1026
1263
  //
1027
1264
  // Neither the bind nor the publish may be swallowed: either failure leaves the LSP
1028
1265
  // head serving text edits while every data client waits on a port command that was
1029
1266
  // never registered, and the launcher reports a bind failure only if given a logger.
1030
- const dataServer = startSocketServer({ port: 0, logTag: 'ModelServer', logger: shared.Logger }, dataConnection => {
1267
+ const dataServer = startSocketServer({ shared, port: 0, logTag: 'ModelServer', logger: shared.Logger }, dataConnection => {
1031
1268
  new DataServer<${roots.join(' | ')}>(dataConnection, shared);
1032
1269
  return { dispose: () => undefined };
1033
1270
  });
1034
1271
  dataServer.started
1035
- .then(() => {
1036
- const { port } = dataServer;
1037
- if (port === undefined) {
1038
- // \`started\` resolves only once the address is resolved, so this is
1039
- // unreachable; a non-null assertion in its place would publish
1040
- // \`undefined\`, which the host cannot tell from an unreachable port.
1041
- throw new Error('the data head started without a resolved port');
1042
- }
1043
- publishPortOnLspConnection(shared.lsp.Connection, ${upper}_DATA_SERVER_PORT_COMMAND, port);
1044
- })
1272
+ .then(
1273
+ () => {
1274
+ const { port } = dataServer;
1275
+ if (port === undefined) {
1276
+ // \`started\` resolves only once the address is resolved, so this is
1277
+ // unreachable; a non-null assertion in its place would publish
1278
+ // \`undefined\`, which the host cannot tell from an unreachable port.
1279
+ throw new Error('the data head started without a resolved port');
1280
+ }
1281
+ publishPortOnLspConnection(shared.lsp.Connection, ${upper}_DATA_SERVER_PORT_COMMAND, port);
1282
+ },
1283
+ // The launcher logged its own bind failure; the rejection is control flow.
1284
+ () => undefined
1285
+ )
1045
1286
  .catch((error: unknown) => {
1046
- const reason = error instanceof Error ? error.message : String(error);
1047
- shared.Logger.error(\`[ModelServer] Could not publish the data-server port: \${reason}\`);
1287
+ shared.Logger.error(\`[ModelServer] Could not publish the data-server port: \${describeErrorWithStack(error)}\`);
1048
1288
  });
1049
- `
1050
- : '';
1289
+ `;
1051
1290
 
1052
1291
  const glspBlock = glsp
1053
1292
  ? `
@@ -1056,55 +1295,115 @@ dataServer.started
1056
1295
  // grammar a request concerns, so nothing per-language belongs there — each
1057
1296
  // diagram module declares its own language instead.
1058
1297
  //
1059
- // GLSP framework logs route through the LSP connection rather than stdout, which
1060
- // IS the LSP transport in stdio mode; writing there corrupts the protocol stream.
1298
+ ${
1299
+ lsp
1300
+ ? `// GLSP framework logs route through the LSP connection rather than stdout, which
1301
+ // IS the LSP transport in stdio mode; writing there corrupts the protocol stream.`
1302
+ : `// GLSP framework logs route through the framework's logger to stderr. GLSP's
1303
+ // own startup line goes to stdout, beside the ports line below.`
1304
+ }
1061
1305
  const glspServer = startGlspServer({
1062
1306
  // The GLSP log threshold lives on the logger, not beside it: the framework
1063
1307
  // replaces GLSP's own \`Logger\` binding, so a launcher-level \`logLevel\` would
1064
1308
  // be discarded. The logger tracks the framework's process-wide threshold, so
1065
- // \`HYDRANIUM_LOG_LEVEL\` and the LSP log-level setting govern GLSP output too;
1309
+ // \`HYDRANIUM_LOG_LEVEL\` ${lsp ? 'and the LSP log-level setting govern' : 'governs'} GLSP output too;
1066
1310
  // pass \`logLevel\` only to make GLSP quieter than the rest of the server.
1067
1311
  createLogger: caller => new GlspClientLogger(shared, { component: caller }),
1068
1312
  serverModule: new ServerModule()${diagrams.map(grammar => `.configureDiagramModule(new ${grammar.grammar}DiagramModule())`).join('')},
1069
1313
  appModules: [new HydraniumGlspAppModule({ shared })],
1070
- lspConnection: shared.lsp.Connection,
1071
- portCommand: ${upper}_GLSP_PORT_COMMAND
1314
+ ${
1315
+ lsp
1316
+ ? ` lspConnection: shared.lsp.Connection,
1317
+ portCommand: ${upper}_GLSP_SERVER_PORT_COMMAND`
1318
+ : ` workspace,
1319
+ port: portFrom('glsp-server-port', ${upper}_GLSP_SERVER_PORT_ENV),
1320
+ logger: shared.Logger`
1321
+ }
1072
1322
  });
1073
- void glspServer;
1074
- `
1323
+ ${lsp ? 'void glspServer;\n' : ''}`
1075
1324
  : '';
1076
1325
 
1077
- const text = `${SHEBANG}// Standalone entry point: starts ${headSummary} in the same
1078
- // process, so every head shares one model store.
1079
- // Invocation: \`node lib/main.js --stdio\`, or the package's \`__PROJECT_ID__\` bin
1080
- // script.${
1081
- data
1082
- ? `
1083
- //
1084
- // NOT the entry \`hydranium-cli query\` / \`save\` / \`projects\` / \`watch\` speak to:
1085
- // stdio here carries LSP, and the data head is a socket whose port is published
1086
- // over the LSP connection. Those subcommands spawn \`data-server-main.js\`.`
1087
- : ''
1088
- }
1089
- //
1090
- // Everything here runs at module scope, so this file is an executable rather
1091
- // than a library entry — import \`./index.js\` instead to compose the language.
1092
-
1093
- ${reflectImport}${glspImports}${importList(coreNodeSymbols, '@hydranium/core/node', columns)}
1094
- ${data ? "import { DataServer } from '@hydranium/data-server';\n" : ''}// The framework's entry point, NOT Langium's \`@hydranium/langium/lsp\` one. It is
1326
+ const lspImports = `// The framework's entry point, NOT Langium's \`@hydranium/langium/lsp\` one. It is
1095
1327
  // signature-compatible and delegates straight through; what it adds first is
1096
1328
  // \`assertLspHeadComposed\`, which fails the start if the LSP head's SHARED module
1097
1329
  // was never composed. Reaching for Langium's is the natural mistake and it is
1098
1330
  // silent: the server boots, links and completes, while echo suppression, the
1099
1331
  // didChangeContent debounce and the last-client-close rebuild are all inert.
1100
- import { startLanguageServer } from '@hydranium/core/lsp';
1332
+ import { startLanguageServer, withHydraniumLspFeatures } from '@hydranium/core/lsp';
1101
1333
  import { ProposedFeatures, createConnection } from 'vscode-languageserver/node';
1102
- ${diagramImports}${transferImports}import { create__NAME__Services } from './language-server/__PROJECT_ID__-module.js';
1103
- ${portCommands === '' ? '' : '\n' + portCommands}
1104
- const connection = createConnection(ProposedFeatures.all);
1334
+ `;
1335
+
1336
+ const lspStart = `
1337
+ const connection = createConnection(withHydraniumLspFeatures(ProposedFeatures.all));
1105
1338
  const { shared } = create__NAME__Services({ connection, ...NodeFileSystem });
1106
1339
  startLanguageServer(shared);
1107
- ${dataBlock}${glspBlock}`;
1340
+ `;
1341
+
1342
+ // No LSP client names the workspace or asks for the ports here, so the
1343
+ // command line does, and the ports go to stdout once every head listens.
1344
+ const servers = [...(data ? ['dataServer'] : []), ...(glsp ? ['glspServer'] : [])];
1345
+ const socketStart = `
1346
+ const { values, positionals } = parseArgs({
1347
+ options: { ${portFlags.map(flag => `'${flag.slice(2)}': { type: 'string' }`).join(', ')} },
1348
+ allowPositionals: true
1349
+ });
1350
+ // The workspace root: the first argument, else the process cwd.
1351
+ const workspace = positionals[0] ?? process.cwd();
1352
+
1353
+ /** A head's port: its flag, else its environment variable, else 0 for any free port. */
1354
+ function portFrom(flag: keyof typeof values, variable: string): number {
1355
+ const text = values[flag] ?? process.env[variable] ?? '0';
1356
+ const port = Number(text);
1357
+ // Decimal digits only: \`Number\` also reads '' as 0 and takes '1e3' or '0x10'.
1358
+ if (!/^\\d+$/.test(text) || port > 65_535) {
1359
+ throw new Error(\`--\${flag} or \${variable} is '\${text}', not a port\`);
1360
+ }
1361
+ return port;
1362
+ }
1363
+
1364
+ const { shared } = create__NAME__Services({ ...NodeFileSystem });
1365
+ `;
1366
+ const portsLine = `
1367
+ // One JSON line on stdout once every head listens, for the process that started
1368
+ // this one to read the ports from: the one line that starts with \`{\`. Each
1369
+ // head brings the workspace up before it listens; a head that fails to start
1370
+ // has logged why and ends the process, which would otherwise serve without it.
1371
+ ${servers.length === 1 ? `${servers[0]}.started` : `Promise.all([${servers.map(server => `${server}.started`).join(', ')}])`}.then(
1372
+ () => process.stdout.write(\`\${JSON.stringify({ ${servers.map(server => `${server}: ${server}.port`).join(', ')} })}\\n\`),
1373
+ () => process.exit(1)
1374
+ );
1375
+ `;
1376
+
1377
+ const invocation = lsp
1378
+ ? `// Invocation: \`node lib/main.js --stdio\`, or the package's \`__PROJECT_ID__\` bin
1379
+ // script.`
1380
+ : `// Invocation: \`node lib/main.js [<workspace-path>] ${portFlags.map(flag => `[${flag} <port>]`).join(' ')}\`,
1381
+ // or the package's \`__PROJECT_ID__\` bin script. Each port falls back to its
1382
+ // environment variable, then to any free port.`;
1383
+ const dataNote = !data
1384
+ ? ''
1385
+ : lsp
1386
+ ? `
1387
+ //
1388
+ // NOT the entry the data-server subcommands of \`hydranium-cli\` speak to: stdio
1389
+ // here carries LSP, and the data head is a socket whose port is published over
1390
+ // the LSP connection. Those subcommands spawn \`data-server-main.js\`.`
1391
+ : `
1392
+ //
1393
+ // NOT the entry the data-server subcommands of \`hydranium-cli\` speak to: they
1394
+ // drive the data protocol over a child's stdio, and the data head here is a
1395
+ // socket. Those subcommands spawn \`data-server-main.js\`.`;
1396
+
1397
+ const text = `${SHEBANG}// Standalone entry point: starts ${headSummary} in the same
1398
+ // process, so every head shares one model store.
1399
+ ${invocation}${dataNote}
1400
+ //
1401
+ // Everything here runs at module scope, so this file is an executable rather
1402
+ // than a library entry — import \`./index.js\` instead to compose the language.
1403
+
1404
+ ${reflectImport}${glspImports}${importList(coreNodeSymbols, '@hydranium/core/node', columns)}
1405
+ ${data ? "import { DataServer } from '@hydranium/data-server';\n" : ''}${data && lsp ? "import { describeErrorWithStack } from '@hydranium/protocol';\n" : ''}${lsp ? lspImports : "import { parseArgs } from 'node:util';\n"}${diagramImports}${transferImports}import { create__NAME__Services } from './language-server/__PROJECT_ID__-module.js';
1406
+ ${portImports === '' ? '' : '\n' + portImports}${lsp ? lspStart : socketStart}${dataBlock}${glspBlock}${lsp ? '' : portsLine}`;
1108
1407
  return project(text, composition);
1109
1408
  }
1110
1409
 
@@ -1112,38 +1411,43 @@ ${dataBlock}${glspBlock}`;
1112
1411
  * The second executable entry: the data head alone, on stdio.
1113
1412
  *
1114
1413
  * Emitted with the `data` head because it is the ONLY command line that reaches
1115
- * that head from outside the editor. `main.ts` gives stdio to LSP and publishes
1116
- * the data head's socket port over the LSP connection, so a client that is not
1117
- * an LSP client cannot discover it — which is every one of `hydranium-cli`'s
1118
- * `query` / `save` / `projects` / `watch`, all of which drive the data protocol
1119
- * over a spawned child's stdin/stdout. Without this file a scaffolded project
1120
- * has no `--server` value, and the closest guess — the LSP entry — fails as an
1121
- * unrecognised method rather than as a missing head.
1414
+ * that head from outside the editor. `main.ts` serves the data head on a
1415
+ * socket, so a client driving the data protocol over a spawned child's
1416
+ * stdin/stdout cannot reach it — which is every data-server subcommand of
1417
+ * `hydranium-cli`. Without this file a scaffolded project has no `--server`
1418
+ * value, and the closest guess, `main.ts`, fails as an unrecognised method or
1419
+ * an unknown flag rather than as a missing head.
1122
1420
  *
1123
1421
  * A separate process rather than a flag on `main.ts`: only one protocol can own
1124
1422
  * stdio, so the two entries are mutually exclusive by construction.
1125
1423
  */
1126
1424
  function dataServerMainFile(composition: InitComposition): string {
1127
1425
  const columns = columnsFor(composition);
1128
- const roots = [...composition.grammars.map(grammar => grammar.entryRule)].sort();
1426
+ const roots = composition.grammars.map(grammar => grammar.entryRule).sort();
1129
1427
  const plural = roots.length > 1 ? 's' : '';
1130
1428
 
1131
1429
  const text = `${SHEBANG}// Standalone entry point: a data-server head on **stdio**, with no LSP head in
1132
- // the process. This is the transport \`hydranium-cli\` speaks — \`query\`, \`save\`,
1133
- // \`projects\` and \`watch\` all spawn a server command and drive JSON-RPC over its
1134
- // stdin/stdout — so it is what makes those subcommands usable against this
1135
- // language.
1430
+ // the process. This is the transport \`hydranium-cli\` speaks — its data-server
1431
+ // subcommands spawn a server command and drive JSON-RPC over its stdin/stdout —
1432
+ // so it is what makes those subcommands usable against this language.
1136
1433
  //
1137
1434
  // Invocation: \`node lib/data-server-main.js [<workspace-path>]\`, or the
1138
1435
  // package's \`__PROJECT_ID__-data-server\` bin script. The workspace path defaults to
1139
1436
  // the process cwd, which is what the CLI's \`--cwd\` sets on the child.
1140
1437
  //
1141
- // Contrast with \`main.ts\`, the editor entry: there the LSP head owns stdio and
1438
+ ${
1439
+ composition.heads.includes('lsp')
1440
+ ? `// Contrast with \`main.ts\`, the editor entry: there the LSP head owns stdio and
1142
1441
  // the data head is a socket published over the LSP connection. Here there is no
1143
1442
  // LSP connection at all, so the workspace initialization an
1144
1443
  // \`initialize\`/\`initialized\` pair would otherwise drive has to happen here —
1145
1444
  // which is why this entry uses \`startStdioServer\` rather than wiring a
1146
- // connection directly.
1445
+ // connection directly.`
1446
+ : `// Contrast with \`main.ts\`, where the data head is a socket whose port it
1447
+ // prints. Here it owns stdio, and as there, no LSP connection drives the
1448
+ // workspace initialization, so \`startStdioServer\` brings the workspace up
1449
+ // before it listens.`
1450
+ }
1147
1451
  //
1148
1452
  // Everything here runs at module scope, so this file is an executable rather
1149
1453
  // than a library entry — import \`./index.js\` instead to compose the language.
@@ -1151,7 +1455,7 @@ function dataServerMainFile(composition: InitComposition): string {
1151
1455
  ${importList(['NodeFileSystem', 'startStdioServer'], '@hydranium/core/node', columns)}
1152
1456
  import { DataServer } from '@hydranium/data-server';
1153
1457
  // The TRANSFER root${plural}, not the AST one${plural} — same reasoning as \`main.ts\`.
1154
- ${importList(roots, './language-server/generated-hydranium/transfer-model.js', columns, true)}
1458
+ ${importList(roots, memberPackageName(composition, 'protocol'), columns, true)}
1155
1459
  import { create__NAME__Services } from './language-server/__PROJECT_ID__-module.js';
1156
1460
 
1157
1461
  const { shared } = create__NAME__Services({ ...NodeFileSystem });
@@ -1200,7 +1504,7 @@ function servicesTest(composition: InitComposition): string {
1200
1504
  // is missing from the composition.
1201
1505
 
1202
1506
  import { describe, expect, it } from 'vitest';
1203
- import { createServices } from '../src/services.js';
1507
+ import { createServices } from '../src/node/services.js';
1204
1508
 
1205
1509
  describe('__NAME__ services', () => {
1206
1510
  it('composes the DI tree and registers ${title}', () => {
@@ -1242,13 +1546,9 @@ const SERIALIZATION_SUITE = `describe('__GRAMMAR__ serialization', () => {
1242
1546
 
1243
1547
  it('emits the same text from a transfer model, whose references are plain strings', async () => {
1244
1548
  const { __GRAMMAR__ } = createServices();
1245
- const model: Transfer__ENTRY_RULE__ = {
1246
- $type: '__ENTRY_RULE__',
1247
- nodes: [
1248
- { $type: '__NODE_RULE__', name: 'first', target: 'second' },
1249
- { $type: '__NODE_RULE__', name: 'second' }
1250
- ]
1251
- };
1549
+ const model = transferNode(Transfer__ENTRY_RULE__, {
1550
+ nodes: __TRANSFER_NODES__
1551
+ });
1252
1552
 
1253
1553
  expect(await __GRAMMAR__.serializer.Serializer.serializeTransfer(model)).toBe(source);
1254
1554
  });
@@ -1267,11 +1567,24 @@ const SERIALIZATION_SUITE = `describe('__GRAMMAR__ serialization', () => {
1267
1567
  function serializationTest(composition: InitComposition): string {
1268
1568
  const columns = columnsFor(composition);
1269
1569
  const astTypes = composition.grammars.map(grammar => grammar.entryRule);
1270
- const transferTypes = composition.grammars.map(grammar => `${grammar.entryRule} as Transfer${grammar.entryRule}`);
1570
+ const transferConstants = composition.grammars.flatMap(grammar => [
1571
+ `${grammar.entryRule} as Transfer${grammar.entryRule}`,
1572
+ grammar.nodeRule
1573
+ ]);
1574
+ const suite = (grammar: InitGrammarNames): string => {
1575
+ const nodes = [
1576
+ `transferNode(${grammar.nodeRule}, { name: 'first', target: 'second' })`,
1577
+ `transferNode(${grammar.nodeRule}, { name: 'second' })`
1578
+ ];
1579
+ const single = `[${nodes.join(', ')}]`;
1580
+ const literal =
1581
+ ` nodes: ${single}`.length <= columns ? single : `[\n${nodes.map(node => ` ${node}`).join(',\n')}\n ]`;
1582
+ return render(SERIALIZATION_SUITE, composition, grammar).replace('__TRANSFER_NODES__', literal);
1583
+ };
1271
1584
  const text = `// Round-trips each grammar through its serializer: parse the source, serialize
1272
1585
  // the model, compare the text. The serializer is the parser's inverse, so this
1273
- // is the assertion that keeps \`ModelService.update\` / \`save\` writing files the
1274
- // language server can read back.
1586
+ // is the assertion that keeps a client session's \`update\` / \`save\` writing
1587
+ // files the language server can read back.
1275
1588
  //
1276
1589
  // The transfer case is the one that catches the mistake worth catching.
1277
1590
  // \`ModelService.modelToText\` short-circuits only a RAW STRING, so a typed model
@@ -1281,10 +1594,11 @@ function serializationTest(composition: InitComposition): string {
1281
1594
  import { parseHelper } from '@hydranium/core/testing';
1282
1595
  import { describe, expect, it } from 'vitest';
1283
1596
  ${importList(astTypes, '../src/language-server/ast.js', columns, true)}
1284
- ${importList(transferTypes, '../src/language-server/generated-hydranium/transfer-model.js', columns, true)}
1285
- import { createServices } from '../src/services.js';
1597
+ ${importList(transferConstants, memberPackageName(composition, 'protocol'), columns)}
1598
+ import { createServices } from '../src/node/services.js';
1599
+ import { transferNode } from './generated-hydranium/transfer-builder.js';
1286
1600
 
1287
- ${composition.grammars.map(grammar => render(SERIALIZATION_SUITE, composition, grammar)).join('\n\n')}
1601
+ ${composition.grammars.map(suite).join('\n\n')}
1288
1602
  `;
1289
1603
  return text;
1290
1604
  }
@@ -1364,14 +1678,9 @@ const LINKING_SUITE = `describe('__GRAMMAR__ linking', () => {
1364
1678
  });`;
1365
1679
 
1366
1680
  /**
1367
- * The validation tier, asserting the FRAMEWORK's diagnostics rather than an
1368
- * adopter rule.
1369
- *
1370
- * The scaffold binds no `validation.checks`, so a test over an adopter check
1371
- * would have to invent one and would then assert the test's own fixture rather
1372
- * than the language. What a scaffolded project really guarantees on day one is
1373
- * that a dangling reference is reported, which is a linker diagnostic — and
1374
- * that is the tier a new adopter breaks third.
1681
+ * The validation tier: the linker's diagnostic for a dangling reference, the
1682
+ * tier a new adopter breaks third, and the scaffold's one check, a warning on
1683
+ * a repeated name.
1375
1684
  */
1376
1685
  const VALIDATING_SUITE = `describe('__GRAMMAR__ validation', () => {
1377
1686
  it('reports nothing for a well-formed document', async () => {
@@ -1398,6 +1707,21 @@ const VALIDATING_SUITE = `describe('__GRAMMAR__ validation', () => {
1398
1707
  expect(diagnostics[0].severity).toBe(DiagnosticSeverity.Error);
1399
1708
  expect(diagnostics[0].message).toContain('absent');
1400
1709
  });
1710
+
1711
+ it('warns on each node named like one before it', async () => {
1712
+ const { shared, __GRAMMAR__ } = createServices();
1713
+
1714
+ const document = await parseHelper<__ENTRY_RULE__>(__GRAMMAR__)('node first\\nnode second\\nnode first', {
1715
+ documentUri: 'file:///duplicate.__EXTENSION__'
1716
+ });
1717
+ await shared.workspace.DocumentBuilder.build([document], { validation: true });
1718
+
1719
+ const diagnostics = document.diagnostics ?? [];
1720
+ expect(diagnostics).toHaveLength(1);
1721
+ expect(diagnostics[0].severity).toBe(DiagnosticSeverity.Warning);
1722
+ expect(diagnostics[0].message).toBe("A node named 'first' is already declared.");
1723
+ expect(diagnostics[0].range.start.line).toBe(2);
1724
+ });
1401
1725
  });`;
1402
1726
 
1403
1727
  /** Assemble one grammar-derived test file: a fixed preamble plus one suite per grammar. */
@@ -1409,7 +1733,7 @@ function grammarTest(composition: InitComposition, header: string, imports: read
1409
1733
  import { parseHelper } from '@hydranium/core/testing';
1410
1734
  import { describe, expect, it } from 'vitest';
1411
1735
  ${imports.join('\n')}${imports.length ? '\n' : ''}${importList(astTypes, '../src/language-server/ast.js', columns, true)}
1412
- import { createServices } from '../src/services.js';
1736
+ import { createServices } from '../src/node/services.js';
1413
1737
 
1414
1738
  ${composition.grammars.map(grammar => render(suite, composition, grammar)).join('\n\n')}
1415
1739
  `;
@@ -1430,16 +1754,16 @@ const LINKING_HEADER = `// Tier two: does my cross-reference resolve.
1430
1754
 
1431
1755
  const VALIDATING_HEADER = `// Tier three: does a broken model get reported.
1432
1756
  //
1433
- // These are the FRAMEWORK's own linker diagnostics, not adopter checks — the
1434
- // scaffold binds no \`validation.checks\`, and a test over an invented one would
1435
- // assert its own fixture rather than the language. Bind a check in your
1436
- // language module and assert it here alongside these.`;
1757
+ // A dangling reference is the FRAMEWORK's own linker diagnostic; a repeated
1758
+ // name is reported by the scaffold's own validation check. Bind a further
1759
+ // check in your language module and assert it here alongside these.`;
1437
1760
 
1438
1761
  /** The README, assembled from lines to avoid escaping the Markdown code fences. */
1439
1762
  function readme(composition: InitComposition): string {
1440
1763
  const multi = composition.grammars.length > 1;
1441
1764
  const data = composition.heads.includes('data');
1442
1765
  const primaryExtension = composition.grammars[0].extensions[0];
1766
+ const diagramCount = composition.grammars.filter(grammar => grammar.diagram).length;
1443
1767
  const grammarBullets = composition.grammars.map(
1444
1768
  grammar => `- \`src/grammar/${grammar.grammarId}.langium\` — the \`${grammar.grammar}\` grammar (.${grammar.extensions.join(', .')})`
1445
1769
  );
@@ -1450,24 +1774,15 @@ function readme(composition: InitComposition): string {
1450
1774
  '',
1451
1775
  '## Getting started',
1452
1776
  '',
1453
- // Conditional on the pin this scaffold actually carries — see
1454
- // `UNPUBLISHED_FRAMEWORK_VERSION`.
1455
- ...(composition.frameworkVersion === UNPUBLISHED_FRAMEWORK_VERSION
1456
- ? [
1457
- '> **Pre-publish note.** `@hydranium/*` is not on npm yet, so the `0.0.0`',
1458
- '> pins below are placeholders and `npm install` will fail with a 404 until',
1459
- '> the framework is released. Until then, supply the packages from a local',
1460
- '> framework checkout with [yalc](https://github.com/wclr/yalc) — a plain',
1461
- '> `file:` path or `npm link` is not enough, because the framework packages',
1462
- '> depend on each other by version and npm would try to fetch those from the',
1463
- '> registry too.',
1464
- ''
1465
- ]
1466
- : []),
1777
+ '`langium generate` fails on Node 24.20 and later with `TypeError: Invalid URL`',
1778
+ '([tdegrunt/jsonschema#423](https://github.com/tdegrunt/jsonschema/issues/423)),',
1779
+ 'so build on Node 22.',
1780
+ '',
1467
1781
  '```bash',
1468
1782
  'npm install',
1469
1783
  'npm run langium:generate # generate the AST from the grammar',
1470
1784
  'npm run build # generate + compile to lib/',
1785
+ 'npm run watch # regenerate and recompile on every grammar or source change',
1471
1786
  'npm test # typecheck the tests, then run them',
1472
1787
  '```',
1473
1788
  '',
@@ -1478,25 +1793,26 @@ function readme(composition: InitComposition): string {
1478
1793
  // nowhere else.
1479
1794
  '```bash',
1480
1795
  '# Grammar / AST reflection',
1481
- 'npx hydranium-cli reflect --services ./lib/services.js',
1796
+ 'npx hydranium-cli reflect --services ./lib/node/services.js',
1482
1797
  '',
1483
1798
  '# Grammar-convention lint (CI gate)',
1484
- 'npx hydranium-cli lint-grammar --services ./lib/services.js',
1799
+ 'npx hydranium-cli lint-grammar --services ./lib/node/services.js',
1485
1800
  '',
1486
1801
  '# Validate a workspace of model files (non-zero exit on errors)',
1487
- 'npx hydranium-cli validate --services ./lib/services.js <workspace-dir>',
1802
+ 'npx hydranium-cli validate --services ./lib/node/services.js ../workspace',
1488
1803
  ...(data
1489
1804
  ? [
1490
1805
  '',
1491
1806
  '# Data-head operations. `--server` is a command line the CLI spawns and then',
1492
1807
  "# drives the data protocol over the child's stdin/stdout, so it has to name",
1493
- '# `data-server-main.js` — `main.js` gives stdio to LSP and answers these',
1494
- '# methods with "Unhandled method".',
1808
+ ...(composition.heads.includes('lsp')
1809
+ ? ['# `data-server-main.js` — `main.js` gives stdio to LSP and answers these', '# methods with "Unhandled method".']
1810
+ : ['# `data-server-main.js` — `main.js` serves the data head on a socket.']),
1495
1811
  '#',
1496
1812
  '# The workspace goes to the ENTRY, not to `--cwd`: `--cwd` re-roots the child,',
1497
1813
  '# so a relative entry path is refused by name (an absolute one is fine).',
1498
- 'npx hydranium-cli projects --server "node ./lib/data-server-main.js <workspace-dir>"',
1499
- `npx hydranium-cli query --server "node ./lib/data-server-main.js <workspace-dir>" --uri <file:// URI of a .${primaryExtension} file>`
1814
+ 'npx hydranium-cli projects --server "node ./lib/data-server-main.js ../workspace"',
1815
+ `npx hydranium-cli query --server "node ./lib/data-server-main.js ../workspace" --uri <file:// URI of ../workspace/nodes.${primaryExtension}>`
1500
1816
  ]
1501
1817
  : []),
1502
1818
  '```',
@@ -1506,12 +1822,12 @@ function readme(composition: InitComposition): string {
1506
1822
  ...grammarBullets,
1507
1823
  ...(multi ? ['- `src/grammar/common.langium` — shared terminals, imported by each grammar (not a language)'] : []),
1508
1824
  '- `src/language-server/__PROJECT_ID__-module.ts` — `create__NAME__Services` DI wiring',
1509
- ...composition.grammars.map(
1510
- grammar =>
1511
- `- \`src/language-server/${grammar.grammarId}-serializer.ts\` — emits \`${grammar.grammar}\` back to text (the framework defaults this to a throw)`
1512
- ),
1513
- '- `src/services.ts` — zero-arg `createServices()` for the headless CLI',
1514
- '- `src/index.ts` — the package entry (`main`): DI factory + generated AST',
1825
+ ...composition.grammars.flatMap(grammar => [
1826
+ `- \`src/language-server/${grammar.grammarId}-serializer.ts\` — emits \`${grammar.grammar}\` back to text (the framework defaults this to a throw)`,
1827
+ `- \`src/language-server/${grammar.grammarId}-validation.ts\` — the \`${grammar.grammar}\` checks: a warning on a repeated name`
1828
+ ]),
1829
+ "- `src/node/services.ts` — zero-arg `createServices()` for the headless CLI, the package's `./node` entry",
1830
+ `- \`src/index.ts\` — the package root, loadable in a browser worker: DI factory + generated AST${diagramCount === 0 ? '' : diagramCount === 1 ? ' + diagram module' : ' + diagram modules'}`,
1515
1831
  `- \`src/main.ts\` — starts ${composition.heads.join(' + ')}, the \`__PROJECT_ID__\` bin entry`,
1516
1832
  ...(data
1517
1833
  ? [
@@ -1523,8 +1839,9 @@ function readme(composition: InitComposition): string {
1523
1839
  .filter(grammar => grammar.diagram)
1524
1840
  .map(
1525
1841
  grammar =>
1526
- `- \`src/glsp/${grammar.grammarId}/\` — the \`${grammar.grammar}\` diagram: type ids, state, storage, submission handler, GModel factory, configuration, create-node handler, DI module`
1842
+ `- \`src/glsp/${grammar.grammarId}/\` — the \`${grammar.grammar}\` diagram: state, storage, submission handler, GModel factory, configuration, create-node handler, DI module`
1527
1843
  ),
1844
+ `- \`../protocol/\` — the \`${memberPackageName(composition, 'protocol')}\` package: what this server and its clients both import (language ids, ${headPortConstants(composition).length === 0 ? '' : composition.heads.includes('lsp') ? 'port commands, ' : 'port variables, '}${composition.grammars.some(grammar => grammar.diagram) ? 'diagram ids, ' : ''}the transfer model), written partly by \`npm run generate\``,
1528
1845
  '- `test/services.test.ts` — the DI tree composes; grows as your language does',
1529
1846
  '- `test/parsing.test.ts` / `linking.test.ts` / `validating.test.ts` — the three tiers a new language breaks first',
1530
1847
  '- `test/serialization.test.ts` — each grammar round-trips through its serializer',
@@ -1577,6 +1894,24 @@ function readme(composition: InitComposition): string {
1577
1894
  'atomic set and depends on a single physical copy, so a floating range can',
1578
1895
  'silently resolve a second one.',
1579
1896
  '',
1897
+ '`vscode-languageserver` is pinned to `10.0.1`, and',
1898
+ '`vscode-languageserver-protocol` and `vscode-jsonrpc` to the `3.18.1` and',
1899
+ '`9.0.0` it pins, so Langium, the LSP connection and the framework share one',
1900
+ 'copy of each. With two, an error a Langium handler returns, such as a request',
1901
+ 'for a document the server does not have, reaches the client as a result, and a',
1902
+ 'framework error your own LSP handler throws loses its code. The Langium 4.4',
1903
+ 'upgrade',
1904
+ '([eclipse-emfcloud/hydranium#142](https://github.com/eclipse-emfcloud/hydranium/issues/142))',
1905
+ 'replaces these pins.',
1906
+ '',
1907
+ ...(pinsVitest(composition)
1908
+ ? [
1909
+ '`vitest` is held below 4.1, whose peer set crashes the npm every Node 22',
1910
+ 'release bundles. Raise it once every npm that installs this project is',
1911
+ '11.6 or later.',
1912
+ ''
1913
+ ]
1914
+ : []),
1580
1915
  '## If your repo gates license headers',
1581
1916
  '',
1582
1917
  'The emitted `.ts` files carry no copyright header — the scaffold cannot know',
@@ -1596,184 +1931,39 @@ function readme(composition: InitComposition): string {
1596
1931
  /**
1597
1932
  * The GLSP files for ONE grammar's diagram.
1598
1933
  *
1599
- * Per grammar rather than per project because a diagram type has exactly one
1600
- * grammar — `AbstractHydraniumGlspDiagramModule.declareLanguage()` returns that
1601
- * grammar's `LanguageMetaData`, and it is bound on the SESSION container so a
1602
- * grammar with no diagram can sit on the same server.
1934
+ * Per grammar rather than per project because the state, storage and GModel
1935
+ * factory are typed over that grammar's model, and a grammar with no diagram
1936
+ * can sit on the same server.
1603
1937
  *
1604
1938
  * The index and the computed-bounds handler are framework classes used
1605
1939
  * unmodified; storage and the submission handler are thin typed subclasses,
1606
1940
  * which is where an adopter's own load/save and log formatting land.
1607
1941
  *
1608
- * The set is EDITABLE rather than read-only: one create-node handler, registered
1609
- * on the module. GLSP's own `DiagramModule` binds no handler that mutates a
1610
- * source model, so without it the head renders and answers while telling the
1611
- * client it may change nothing — which reads as a broken diagram rather than as a
1612
- * deliberate viewer.
1942
+ * The set is EDITABLE rather than read-only: a create-node and a delete handler,
1943
+ * registered on the module. GLSP's own `DiagramModule` binds no handler that
1944
+ * mutates a source model, so without them the head renders and answers while
1945
+ * telling the client it may change nothing — which reads as a broken diagram
1946
+ * rather than as a deliberate viewer.
1613
1947
  */
1614
1948
  function glspFiles(composition: InitComposition, grammar: InitGrammarNames): InitFile[] {
1615
1949
  const columns = columnsFor(composition);
1616
- const upper = screamingSnake(grammar.grammarId);
1617
- const dir = `src/glsp/${grammar.grammarId}`;
1618
- const render = (text: string): string => grammarTier(project(text, composition), grammar);
1619
-
1620
- const types = `// GLSP diagram-type and element-type ids for the __GRAMMAR__ diagram.
1621
- //
1622
- // **Authoritative half of a client/server contract.** Every id here has to be
1623
- // registered on the client too: sprotty's registries are exact-key maps with no
1624
- // prefix fallback, so an id the client does not know yields an element with none
1625
- // of a node's features, rendered by \`MissingView\` with only a
1626
- // \`no registered view for type '…'\` console warning. Nothing fails server-side.
1627
- //
1628
- // The ids stay namespaced under the GLSP defaults (\`node:\` / \`edge:\`) so a
1629
- // reader can tell a node id from an edge id at a glance.
1630
-
1631
- import { DefaultTypes } from '@eclipse-glsp/server';
1632
-
1633
- /**
1634
- * The GLSP diagram type — the string GLSP routes every per-diagram-type request
1635
- * by. Mirrored by the client; a mismatch silently DROPS the request rather than
1636
- * reporting an unknown diagram type. Same value as the language id, so the two
1637
- * cannot drift apart as a diagram gains element types.
1638
- */
1639
- export const ${upper}_DIAGRAM_TYPE = '__LANGUAGE_ID__';
1640
-
1641
- /** A \`__NODE_RULE__\` — the starter grammar's one named, referenceable node. */
1642
- export const ${upper}_NODE_TYPE = \`\${DefaultTypes.NODE}:__GRAMMAR_ID__-node\`;
1643
-
1644
- /** A resolved \`target\` reference, drawn as a connection between two nodes. */
1645
- export const ${upper}_EDGE_TYPE = \`\${DefaultTypes.EDGE}:__GRAMMAR_ID__-target\`;
1646
- `;
1647
-
1648
- const state = `// GLSP state for the __GRAMMAR__ diagram.
1649
- //
1650
- // \`FullTextHydraniumGlspState\` is the simplest of the framework source-model
1651
- // strategies (the others project a structured transfer model, over one document
1652
- // or several): the source model is the whole document text, serialised through
1653
- // the per-URI \`Serializer\` and round-tripped by re-parsing. Both seams resolve
1654
- // through shared services, so narrowing the root type is all an adopter adds.
1655
- //
1656
- // It cannot field-merge — every concurrent edit on a whole-document model is a
1657
- // same-document collision, so undo / redo degrade to drop-on-divergence. Move to
1658
- // \`ReconcilingTransferHydraniumGlspState\` when you need field-level undo.
1659
-
1660
- import { FullTextHydraniumGlspState } from '@hydranium/glsp-server';
1661
- import { injectable } from 'inversify';
1662
- import type { __ENTRY_RULE__ } from '../../language-server/ast.js';
1663
-
1664
- @injectable()
1665
- export class __GRAMMAR__GlspState extends FullTextHydraniumGlspState<__ENTRY_RULE__> {}
1666
- `;
1667
-
1668
- const storage = `// Source-model storage for the __GRAMMAR__ diagram, inheriting both framework
1669
- // defaults: \`loadSourceModel\` (open + settle + \`setSourceRoot\`) and
1670
- // \`saveSourceModel\` (through \`ModelService.save\` → the per-URI \`Serializer\` →
1671
- // the multi-client text store → \`WritableFileSystemProvider\`).
1672
- //
1673
- // The subclass exists so a bespoke load or save has a stable place to land.
1674
-
1675
- import { type FullTextSourceModel, HydraniumGlspStorage } from '@hydranium/glsp-server';
1676
- import { injectable } from 'inversify';
1677
- import type { __ENTRY_RULE__ } from '../../language-server/ast.js';
1678
-
1679
- @injectable()
1680
- export class __GRAMMAR__GlspStorage extends HydraniumGlspStorage<__ENTRY_RULE__, FullTextSourceModel> {}
1681
- `;
1682
-
1683
- const submission = `// Submission handler for the __GRAMMAR__ diagram.
1684
- //
1685
- // Inherits the framework's \`readyEvent = IntegrityService.SettledState\`, which
1686
- // is load-bearing rather than incidental: the GModel factory resolves
1687
- // \`target.ref\`, so it needs a fully-linked AST. Without the gate those reads
1688
- // fire mid-build and warn about resolution before scopes are computed.
1689
- //
1690
- // Only \`formatSourceRoot\` is overridden, so the submit log names the model and
1691
- // its node count instead of a bare \`$type\`.
1692
-
1693
- import { ModelState } from '@eclipse-glsp/server';
1694
- import { type FullTextSourceModel, HydraniumGlspSubmissionHandler } from '@hydranium/glsp-server';
1695
- import { inject, injectable } from 'inversify';
1696
- import type { __ENTRY_RULE__ } from '../../language-server/ast.js';
1697
- import type { __GRAMMAR__GlspState } from './state.js';
1698
-
1699
- @injectable()
1700
- export class __GRAMMAR__SubmissionHandler extends HydraniumGlspSubmissionHandler<__ENTRY_RULE__, FullTextSourceModel> {
1701
- @inject(ModelState) declare protected modelState: __GRAMMAR__GlspState;
1702
-
1703
- protected override formatSourceRoot(root: __ENTRY_RULE__ | undefined): string {
1704
- return root ? \`__ENTRY_RULE__ nodes=\${root.nodes.length}\` : 'none';
1705
- }
1706
- }
1707
- `;
1708
-
1709
- const factory = `// AST → GModel for the __GRAMMAR__ diagram: one node per \`__NODE_RULE__\`, one
1710
- // edge per resolved \`target\` reference.
1711
- //
1712
- // Ids come from the index rather than being composed here, so the id strategy
1713
- // stays in one place. Nodes are emitted before edges, because a GLSP edge
1714
- // pointing at an id that does not exist fails client-side with a far less
1715
- // obvious error than a missing edge. An unresolved reference is SKIPPED rather
1716
- // than treated as an error: a dangling reference is ordinary editing state, and
1717
- // the LSP head already reports it as a diagnostic.
1718
-
1719
- import { DefaultTypes, GEdge, GGraph, GLabel, type GModelFactory, GNode, ModelState } from '@eclipse-glsp/server';
1720
- import { inject, injectable } from 'inversify';
1721
- import type { __ENTRY_RULE__ } from '../../language-server/ast.js';
1722
- import { ${upper}_EDGE_TYPE, ${upper}_NODE_TYPE } from './types.js';
1723
- import type { __GRAMMAR__GlspState } from './state.js';
1724
-
1725
- @injectable()
1726
- export class __GRAMMAR__GModelFactory implements GModelFactory {
1727
- @inject(ModelState) protected readonly modelState!: __GRAMMAR__GlspState;
1728
-
1729
- createModel(): void {
1730
- const root = this.modelState.sourceRoot;
1731
- const graph = GGraph.builder().id(this.modelState.sourceUri).build();
1732
- if (root) {
1733
- this.buildGraph(root, graph);
1734
- }
1735
- this.modelState.updateRoot(graph);
1736
- }
1737
-
1738
- protected buildGraph(root: __ENTRY_RULE__, graph: GGraph): void {
1739
- for (const node of root.nodes) {
1740
- const id = this.modelState.index.createId(node);
1741
- graph.children.push(
1742
- GNode.builder()
1743
- .id(id)
1744
- .type(${upper}_NODE_TYPE)
1745
- .add(GLabel.builder().id(\`\${id}_name\`).text(node.name).type(DefaultTypes.LABEL).build())
1746
- .build()
1747
- );
1748
- }
1749
- for (const node of root.nodes) {
1750
- const target = node.target?.ref;
1751
- if (!target) {
1752
- continue;
1753
- }
1754
- const sourceId = this.modelState.index.createId(node);
1755
- graph.children.push(
1756
- GEdge.builder()
1757
- .id(\`\${sourceId}_target\`)
1758
- .type(${upper}_EDGE_TYPE)
1759
- .sourceId(sourceId)
1760
- .targetId(this.modelState.index.createId(target))
1761
- .build()
1762
- );
1763
- }
1764
- }
1765
- }
1766
- `;
1950
+ const fixed = (file: string): InitFile => grammarTemplate(`server/src/glsp/__GRAMMAR_ID__/${file}`, composition, grammar);
1951
+ const computed = (file: string, text: string): InitFile => ({
1952
+ path: `server/src/glsp/${grammar.grammarId}/${file}`,
1953
+ content: render(text, composition, grammar)
1954
+ });
1767
1955
 
1768
1956
  const configuration = `// Diagram configuration for the __GRAMMAR__ diagram.
1769
1957
  //
1770
- // **Every hint is \`false\`, and that is not the same as read-only.** The starter
1771
- // __GRAMMAR__CreateNodeOperationHandler makes this diagram editable through the
1772
- // tool palette, which GLSP assembles from the create handlers' trigger actions —
1773
- // there is no \`creatable\` hint. What the hints govern is delete / reparent /
1774
- // reposition / resize, and nothing backs those, so declaring one would offer a
1775
- // gesture whose operation the server rejects: a worse failure than the tool being
1776
- // absent. Turn a hint on in the same change that adds its handler.
1958
+ // **A hint is \`true\` only where a handler backs it.** The starter
1959
+ // __GRAMMAR__CreateNodeOperationHandler offers creation through the tool palette,
1960
+ // which GLSP assembles from the create handlers' trigger actions — there is no
1961
+ // \`creatable\` hint. __GRAMMAR__DeleteOperationHandler backs \`deletable\` on a
1962
+ // node and an edge; a node of another document stays undeletable, since this
1963
+ // diagram does not own it. Nothing backs reparent / reposition / resize, so
1964
+ // declaring one would offer a gesture whose operation the server rejects: a worse
1965
+ // failure than the tool being absent. Turn a hint on in the same change that adds
1966
+ // its handler.
1777
1967
  //
1778
1968
  // \`needsClientLayout\` is \`true\` and \`layoutKind\` is \`NONE\`: the starter grammar
1779
1969
  // persists no bounds, so the client measures and places everything. That is also
@@ -1788,7 +1978,7 @@ ${importList(
1788
1978
  columns
1789
1979
  )}
1790
1980
  import { injectable } from 'inversify';
1791
- import { ${upper}_EDGE_TYPE, ${upper}_NODE_TYPE } from './types.js';
1981
+ import { __GRAMMAR_ID_CONST___EDGE_TYPE, __GRAMMAR_ID_CONST___EXTERNAL_NODE_TYPE, __GRAMMAR_ID_CONST___NODE_TYPE } from '__PROTOCOL_PACKAGE__';
1792
1982
 
1793
1983
  @injectable()
1794
1984
  export class __GRAMMAR__DiagramConfiguration implements DiagramConfiguration {
@@ -1800,7 +1990,14 @@ export class __GRAMMAR__DiagramConfiguration implements DiagramConfiguration {
1800
1990
 
1801
1991
  readonly shapeTypeHints: ShapeTypeHint[] = [
1802
1992
  {
1803
- elementTypeId: ${upper}_NODE_TYPE,
1993
+ elementTypeId: __GRAMMAR_ID_CONST___NODE_TYPE,
1994
+ deletable: true,
1995
+ reparentable: false,
1996
+ repositionable: false,
1997
+ resizable: false
1998
+ },
1999
+ {
2000
+ elementTypeId: __GRAMMAR_ID_CONST___EXTERNAL_NODE_TYPE,
1804
2001
  deletable: false,
1805
2002
  reparentable: false,
1806
2003
  repositionable: false,
@@ -1810,125 +2007,41 @@ export class __GRAMMAR__DiagramConfiguration implements DiagramConfiguration {
1810
2007
 
1811
2008
  readonly edgeTypeHints: EdgeTypeHint[] = [
1812
2009
  {
1813
- elementTypeId: ${upper}_EDGE_TYPE,
1814
- deletable: false,
2010
+ elementTypeId: __GRAMMAR_ID_CONST___EDGE_TYPE,
2011
+ deletable: true,
1815
2012
  repositionable: false,
1816
2013
  routable: false,
1817
- sourceElementTypeIds: [${upper}_NODE_TYPE],
1818
- targetElementTypeIds: [${upper}_NODE_TYPE]
2014
+ sourceElementTypeIds: [__GRAMMAR_ID_CONST___NODE_TYPE],
2015
+ targetElementTypeIds: [__GRAMMAR_ID_CONST___NODE_TYPE, __GRAMMAR_ID_CONST___EXTERNAL_NODE_TYPE]
1819
2016
  }
1820
2017
  ];
1821
2018
  }
1822
- `;
1823
-
1824
- const createHandler = `// The starter operation handler for the __GRAMMAR__ diagram: the tool-palette
1825
- // entry that creates a \`__NODE_RULE__\`.
1826
- //
1827
- // **Deleting this file and its \`configureOperationHandlers\` registration in
1828
- // \`diagram-module.ts\` gives a read-only viewer**, and nothing else has to change
1829
- // — creation is offered through the palette rather than through a type hint, so
1830
- // every hint in \`diagram-configuration.ts\` is already \`false\`. The scaffold emits
1831
- // the editable direction because that asymmetry runs one way: editable →
1832
- // read-only is a deletion the compiler checks, while read-only → editable is
1833
- // authoring against a seam you have not used yet.
1834
- //
1835
- // **It composes TEXT rather than mutating the AST.** The source model of
1836
- // \`FullTextHydraniumGlspState\` is the document text, and reading it back through
1837
- // \`state.sourceModel\` serialises the AST through the per-URI \`Serializer\`, which
1838
- // this scaffold does not bind — so that getter throws until you do. Appending a
1839
- // declaration to the text the parser last read needs no serializer, which is what
1840
- // makes a scaffolded diagram editable on day one. Bind a \`Serializer\` at
1841
- // \`services.serializer.Serializer\` and this becomes a
1842
- // \`HydraniumGlspRecordingCommand\` over \`state.sourceModel\` instead — the same
1843
- // binding the diagram's own save action needs.
1844
- //
1845
- // **The drop location is discarded.** \`needsClientLayout\` is \`true\` and the
1846
- // starter grammar persists no bounds, so there is nowhere to put a coordinate: the
1847
- // node is appended at the end of the document and the client places it.
1848
- //
1849
- // Like \`types.ts\`, \`gmodel-factory.ts\` and \`diagram-configuration.ts\`, this file
1850
- // knows the starter grammar's concrete syntax — the \`node\` keyword below is that
1851
- // grammar's. Replacing the grammar means replacing these four together.
1852
-
1853
- import { type Command, type CreateNodeOperation, JsonCreateNodeOperationHandler, type MaybePromise } from '@eclipse-glsp/server';
1854
- import { findNextUnique } from '@hydranium/protocol';
1855
- import { injectable } from 'inversify';
1856
- import { ${upper}_NODE_TYPE } from './types.js';
1857
- import type { __GRAMMAR__GlspState } from './state.js';
1858
-
1859
- /** Proposed name for a new node, uniquified against the ones the document already has. */
1860
- const NODE_NAME_STEM = 'Node';
1861
-
1862
- @injectable()
1863
- export class __GRAMMAR__CreateNodeOperationHandler extends JsonCreateNodeOperationHandler {
1864
- declare protected modelState: __GRAMMAR__GlspState;
1865
-
1866
- /** The palette's word for the thing it creates, so a noun rather than an action. */
1867
- override readonly label = '__NODE_RULE__';
1868
- elementTypeIds = [${upper}_NODE_TYPE];
1869
-
1870
- override createCommand(operation: CreateNodeOperation): MaybePromise<Command | undefined> {
1871
- if (!this.elementTypeIds.includes(operation.elementTypeId)) {
1872
- return undefined;
1873
- }
1874
- const state = this.modelState;
1875
- const before = this.documentText();
1876
- const after = this.withNode(
1877
- before,
1878
- findNextUnique(
1879
- NODE_NAME_STEM,
1880
- state.sourceRoot.nodes.map(node => node.name)
1881
- )
1882
- );
1883
- // Whole-document undo, which is all a full-text source model can offer: it
1884
- // has exactly one field, so there is nothing to merge a concurrent edit into.
1885
- return {
1886
- execute: () => state.updateSourceModel({ text: after }),
1887
- undo: () => state.updateSourceModel({ text: before }),
1888
- redo: () => state.updateSourceModel({ text: after })
1889
- };
1890
- }
1891
-
1892
- /** The text the captured source root was parsed from — the baseline an edit appends to. */
1893
- protected documentText(): string {
1894
- return this.modelState.sourceRoot.$document?.textDocument.getText() ?? '';
1895
- }
1896
-
1897
- /** \`text\` with one more node declaration, under exactly one trailing newline. */
1898
- protected withNode(text: string, name: string): string {
1899
- const body = text.trimEnd();
1900
- const declaration = \`node \${name}\`;
1901
- return body.length === 0 ? \`\${declaration}\\n\` : \`\${body}\\n\${declaration}\\n\`;
1902
- }
1903
- }
1904
2019
  `;
1905
2020
 
1906
2021
  const module = `// GLSP diagram module for __GRAMMAR__ — the DI wiring of one diagram type.
1907
2022
  //
1908
- // \`declareLanguage\` is the multi-grammar seam: it binds the grammar this diagram
1909
- // edits on the SESSION container, so \`modelState.diagramLanguage\` and the
1910
- // per-language lookups resolve to __LANGUAGE_ID__. That is what stops one
1911
- // diagram type from fighting over a process-wide binding when a project holds
1912
- // several grammars — a grammar with no diagram is registered on the same server.
1913
- //
1914
2023
  // \`configureActionHandlers\` REBINDS rather than adds: GLSP's own
1915
2024
  // \`DiagramModule\` already registers \`ComputedBoundsActionHandler\`, and two
1916
2025
  // handlers for one action would both run.
1917
2026
  //
1918
2027
  // \`configureOperationHandlers\` ADDS: GLSP's default pair
1919
2028
  // (\`CompoundOperationHandler\` and \`LayoutOperationHandler\`) mutates no source
1920
- // model, so the starter create handler is what makes this diagram editable at all.
2029
+ // model, so the starter create and delete handlers are what make this diagram
2030
+ // editable at all.
1921
2031
 
1922
2032
  ${importList(
1923
2033
  [
1924
2034
  'ActionHandlerConstructor',
1925
2035
  'BindingTarget',
2036
+ 'ComputedBoundsAction',
1926
2037
  'DiagramConfiguration',
1927
2038
  'GModelFactory',
1928
2039
  'GModelIndex',
2040
+ 'GModelRoot',
1929
2041
  'InstanceMultiBinding',
1930
2042
  'ModelState',
1931
2043
  'ModelSubmissionHandler',
2044
+ 'ModelValidator',
1932
2045
  'OperationHandlerConstructor',
1933
2046
  'SourceModelStorage'
1934
2047
  ],
@@ -1937,27 +2050,36 @@ ${importList(
1937
2050
  true
1938
2051
  )}
1939
2052
  import { ComputedBoundsActionHandler } from '@eclipse-glsp/server';
1940
- import type { LanguageMetaData } from '@hydranium/langium';
1941
2053
  ${importList(
1942
- ['HydraniumGlspComputedBoundsActionHandler', 'AbstractHydraniumGlspDiagramModule', 'HydraniumGlspIndex'],
2054
+ ['HydraniumGlspComputedBoundsActionHandler', 'AbstractHydraniumGlspDiagramModule', 'HydraniumGlspIndex', 'HydraniumGlspModelValidator'],
1943
2055
  '@hydranium/glsp-server',
1944
2056
  columns
1945
2057
  )}
1946
- import { __GRAMMAR__LanguageMetaData } from '../../language-server/generated/module.js';
1947
2058
  import { __GRAMMAR__CreateNodeOperationHandler } from './create-node-operation-handler.js';
2059
+ import { __GRAMMAR__DeleteOperationHandler } from './delete-operation-handler.js';
1948
2060
  import { __GRAMMAR__DiagramConfiguration } from './diagram-configuration.js';
1949
2061
  import { __GRAMMAR__GModelFactory } from './gmodel-factory.js';
1950
2062
  import { __GRAMMAR__GlspState } from './state.js';
1951
2063
  import { __GRAMMAR__GlspStorage } from './storage.js';
1952
2064
  import { __GRAMMAR__SubmissionHandler } from './submission-handler.js';
1953
- import { ${upper}_DIAGRAM_TYPE } from './types.js';
1954
-
1955
- export class __GRAMMAR__DiagramModule extends AbstractHydraniumGlspDiagramModule {
1956
- readonly diagramType = ${upper}_DIAGRAM_TYPE;
2065
+ import { __GRAMMAR_ID_CONST___DIAGRAM_TYPE } from '__PROTOCOL_PACKAGE__';
2066
+ import { injectable } from 'inversify';
1957
2067
 
1958
- protected override declareLanguage(): LanguageMetaData {
1959
- return __GRAMMAR__LanguageMetaData;
2068
+ /**
2069
+ * The framework handler, keeping none of the edge routes the client reports:
2070
+ * it routes an edge before it sizes the nodes, so a self-reference's loop would
2071
+ * stay drawn inside its node. The starter's edges have no routing points, and
2072
+ * the client routes them afresh from the sized nodes.
2073
+ */
2074
+ @injectable()
2075
+ export class __GRAMMAR__ComputedBoundsActionHandler extends HydraniumGlspComputedBoundsActionHandler {
2076
+ protected override applyBounds(root: GModelRoot, action: ComputedBoundsAction): void {
2077
+ super.applyBounds(root, { ...action, routes: undefined });
1960
2078
  }
2079
+ }
2080
+
2081
+ export class __GRAMMAR__DiagramModule extends AbstractHydraniumGlspDiagramModule {
2082
+ readonly diagramType = __GRAMMAR_ID_CONST___DIAGRAM_TYPE;
1961
2083
 
1962
2084
  protected override bindModelState(): BindingTarget<ModelState> {
1963
2085
  return { service: __GRAMMAR__GlspState };
@@ -1984,81 +2106,107 @@ export class __GRAMMAR__DiagramModule extends AbstractHydraniumGlspDiagramModule
1984
2106
  return { service: HydraniumGlspIndex };
1985
2107
  }
1986
2108
 
2109
+ /**
2110
+ * The language's diagnostics as diagram markers, following each edit. GLSP
2111
+ * binds no validator by default, and without one no marker ever shows.
2112
+ */
2113
+ protected override bindModelValidator(): BindingTarget<ModelValidator> {
2114
+ return HydraniumGlspModelValidator;
2115
+ }
2116
+
1987
2117
  protected override configureActionHandlers(binding: InstanceMultiBinding<ActionHandlerConstructor>): void {
1988
2118
  super.configureActionHandlers(binding);
1989
- binding.rebind(ComputedBoundsActionHandler, HydraniumGlspComputedBoundsActionHandler);
2119
+ binding.rebind(ComputedBoundsActionHandler, __GRAMMAR__ComputedBoundsActionHandler);
1990
2120
  }
1991
2121
 
1992
2122
  protected override configureOperationHandlers(binding: InstanceMultiBinding<OperationHandlerConstructor>): void {
1993
2123
  super.configureOperationHandlers(binding);
1994
2124
  binding.add(__GRAMMAR__CreateNodeOperationHandler);
2125
+ binding.add(__GRAMMAR__DeleteOperationHandler);
1995
2126
  }
1996
2127
  }
1997
2128
  `;
1998
2129
 
1999
2130
  return [
2000
- { path: `${dir}/types.ts`, content: render(types) },
2001
- { path: `${dir}/state.ts`, content: render(state) },
2002
- { path: `${dir}/storage.ts`, content: render(storage) },
2003
- { path: `${dir}/submission-handler.ts`, content: render(submission) },
2004
- { path: `${dir}/gmodel-factory.ts`, content: render(factory) },
2005
- { path: `${dir}/diagram-configuration.ts`, content: render(configuration) },
2006
- { path: `${dir}/create-node-operation-handler.ts`, content: render(createHandler) },
2007
- { path: `${dir}/diagram-module.ts`, content: render(module) }
2131
+ fixed('state.ts'),
2132
+ fixed('storage.ts'),
2133
+ fixed('submission-handler.ts'),
2134
+ fixed('gmodel-factory.ts'),
2135
+ computed('diagram-configuration.ts', configuration),
2136
+ fixed('create-node-operation-handler.ts'),
2137
+ fixed('delete-operation-handler.ts'),
2138
+ computed('diagram-module.ts', module),
2139
+ grammarTemplate('server/test/__GRAMMAR_ID__-diagram.test.ts', composition, grammar)
2008
2140
  ];
2009
2141
  }
2010
2142
 
2011
2143
  /**
2012
- * Every file the scaffold emits, fully rendered.
2144
+ * The server member: the grammar, the language and its heads.
2013
2145
  *
2014
2146
  * Grammar-count-dependent emissions live here rather than in a template string:
2015
2147
  * one `.langium` file per grammar, and the shared `common.langium` fragment only
2016
2148
  * when there is more than one grammar to share it.
2017
2149
  */
2018
- export function buildInitTemplates(composition: InitComposition): InitFile[] {
2150
+ function serverFiles(composition: InitComposition): InitFile[] {
2019
2151
  const multi = composition.grammars.length > 1;
2020
2152
  const grammarFiles: InitFile[] = composition.grammars.map(grammar => ({
2021
- path: `src/grammar/${grammar.grammarId}.langium`,
2153
+ path: `server/src/grammar/${grammar.grammarId}.langium`,
2022
2154
  content: render(grammarFile(multi), composition, grammar)
2023
2155
  }));
2156
+ // The shared lexical fragment, only for several grammars: each declaring its
2157
+ // own `WS` / `ID` lets the token sets drift apart.
2024
2158
  if (multi) {
2025
- grammarFiles.unshift({ path: 'src/grammar/common.langium', content: COMMON_GRAMMAR });
2159
+ grammarFiles.unshift(projectTemplate('server/src/grammar/common.langium', composition));
2026
2160
  }
2027
2161
 
2028
2162
  const diagramFiles = composition.grammars.filter(grammar => grammar.diagram).flatMap(grammar => glspFiles(composition, grammar));
2029
2163
 
2030
2164
  return [
2031
- { path: 'package.json', content: packageJson(composition) },
2032
- { path: 'langium-config.json', content: langiumConfig(composition) },
2033
- { path: 'tsconfig.json', content: tsconfigJson(composition) },
2034
- { path: 'tsconfig.test.json', content: TSCONFIG_TEST },
2035
- { path: 'vitest.config.ts', content: VITEST_CONFIG },
2036
- {
2037
- path: '.gitignore',
2038
- content: composition.packaging.workspace === undefined ? GITIGNORE : GITIGNORE_WORKSPACE_MEMBER
2039
- },
2040
- { path: 'README.md', content: readme(composition) },
2165
+ { path: 'server/package.json', content: packageJson(composition) },
2166
+ { path: 'server/langium-config.json', content: langiumConfig(composition) },
2167
+ { path: 'server/tsconfig.json', content: serverTsconfigJson(composition) },
2168
+ // `isolatedModules` is what makes this check agree with the transform that
2169
+ // actually runs the tests. `npm test` is `typecheck:test && vitest run`, and
2170
+ // vitest compiles each file on its own — a transform with no type
2171
+ // information, which cannot tell a re-exported TYPE from a re-exported value.
2172
+ // Without the flag `tsc` accepts `export { SomeType } from './x'` that the
2173
+ // transform then emits as a real import of a symbol that does not exist at
2174
+ // runtime, so the typecheck passes and the suite fails with a confusing
2175
+ // missing-export.
2176
+ projectTemplate('server/tsconfig.test.json', composition),
2177
+ // Found by name, unlike `tsconfig.test.json`. Under vite 8, vitest's transform
2178
+ // applies a tsconfig only to the files its own `include` lists, so without this
2179
+ // a test declaring a decorated class fails to load.
2180
+ projectTemplate('server/test/tsconfig.json', composition),
2181
+ projectTemplate('server/vitest.config.ts', composition),
2182
+ // Written for a workspace member too: its root may not ignore `lib/` (a `yo
2183
+ // langium` root ignores `out/`), and a rule the root repeats costs nothing.
2184
+ ignoreFile('server'),
2185
+ { path: 'server/README.md', content: readme(composition) },
2041
2186
  ...grammarFiles,
2042
- { path: `src/language-server/${composition.projectId}-module.ts`, content: moduleFile(composition) },
2043
- { path: 'src/language-server/ast.ts', content: render(AST, composition, composition.grammars[0]) },
2044
- ...composition.grammars.map(grammar => ({
2045
- path: `src/language-server/${grammar.grammarId}-serializer.ts`,
2046
- content: render(SERIALIZER, composition, grammar)
2047
- })),
2048
- { path: 'src/index.ts', content: indexFile(composition) },
2049
- { path: 'src/services.ts', content: project(SERVICES, composition) },
2050
- { path: 'src/main.ts', content: mainFile(composition) },
2051
- ...(composition.heads.includes('data') ? [{ path: 'src/data-server-main.ts', content: dataServerMainFile(composition) }] : []),
2052
- ...(portCommandNames(composition).length ? [{ path: 'src/head-ports.ts', content: headPortsFile(composition) }] : []),
2187
+ { path: `server/src/language-server/${composition.projectId}-module.ts`, content: moduleFile(composition) },
2188
+ grammarTemplate('server/src/language-server/ast.ts', composition, composition.grammars[0]),
2189
+ // Per grammar, because `services.serializer.Serializer` is a per-language slot
2190
+ // and a serializer is grammar-shaped by definition. That is also why the
2191
+ // framework refuses to default it: its `UnboundSerializer` throws, naming the
2192
+ // binding to add, rather than guessing a syntax.
2193
+ ...composition.grammars.flatMap(grammar => [
2194
+ grammarTemplate('server/src/language-server/__GRAMMAR_ID__-serializer.ts', composition, grammar),
2195
+ grammarTemplate('server/src/language-server/__GRAMMAR_ID__-validation.ts', composition, grammar)
2196
+ ]),
2197
+ { path: 'server/src/index.ts', content: indexFile(composition) },
2198
+ projectTemplate('server/src/node/services.ts', composition),
2199
+ { path: 'server/src/main.ts', content: mainFile(composition) },
2200
+ ...(composition.heads.includes('data') ? [{ path: 'server/src/data-server-main.ts', content: dataServerMainFile(composition) }] : []),
2053
2201
  ...diagramFiles,
2054
- { path: 'test/services.test.ts', content: servicesTest(composition) },
2055
- { path: 'test/parsing.test.ts', content: grammarTest(composition, PARSING_HEADER, [], PARSING_SUITE) },
2202
+ { path: 'server/test/services.test.ts', content: servicesTest(composition) },
2203
+ { path: 'server/test/parsing.test.ts', content: grammarTest(composition, PARSING_HEADER, [], PARSING_SUITE) },
2056
2204
  {
2057
- path: 'test/linking.test.ts',
2205
+ path: 'server/test/linking.test.ts',
2058
2206
  content: grammarTest(composition, LINKING_HEADER, ["import { AstUtils } from '@hydranium/langium';"], LINKING_SUITE)
2059
2207
  },
2060
2208
  {
2061
- path: 'test/validating.test.ts',
2209
+ path: 'server/test/validating.test.ts',
2062
2210
  content: grammarTest(
2063
2211
  composition,
2064
2212
  VALIDATING_HEADER,
@@ -2066,6 +2214,2260 @@ export function buildInitTemplates(composition: InitComposition): InitFile[] {
2066
2214
  VALIDATING_SUITE
2067
2215
  )
2068
2216
  },
2069
- { path: 'test/serialization.test.ts', content: serializationTest(composition) }
2217
+ { path: 'server/test/serialization.test.ts', content: serializationTest(composition) }
2218
+ ];
2219
+ }
2220
+
2221
+ /**
2222
+ * The protocol member's `package.json`.
2223
+ *
2224
+ * Its `build` runs the server's `generate` first, because the server writes
2225
+ * this package's `generated-hydranium/` modules from the grammar: a runner that
2226
+ * builds in dependency order reaches this package before the server, and would
2227
+ * otherwise compile modules that do not exist yet. A full build therefore
2228
+ * generates twice; the second pass rewrites nothing.
2229
+ */
2230
+ function protocolPackageJson(composition: InitComposition): string {
2231
+ const member = forMember(composition, 'protocol');
2232
+ const dependencies: Record<string, string> = {};
2233
+ for (const head of composition.heads) {
2234
+ Object.assign(dependencies, PROTOCOL_THIRD_PARTY_DEPENDENCIES[head]);
2235
+ }
2236
+ const dependencyLines =
2237
+ Object.keys(dependencies).length === 0 ? '' : ` "dependencies": {\n${sortedBlock(dependencies, ' ')}\n },\n`;
2238
+ return `{
2239
+ "name": "${memberPackageName(composition, 'protocol')}",
2240
+ "version": "0.0.0",
2241
+ ${composition.packaging.private ? ' "private": true,\n' : ''} "description": "What the ${composition.name} language server and its clients share: language ids, wire types and diagram ids.",
2242
+ "license": "UNLICENSED",
2243
+ "author": "",
2244
+ "files": [
2245
+ "lib",
2246
+ "src"
2247
+ ],
2248
+ "type": "module",
2249
+ "main": "lib/index.js",
2250
+ "types": "lib/index.d.ts",
2251
+ "scripts": {
2252
+ "build": "npm --prefix ../server run generate && tsc -b",
2253
+ "clean": "rimraf lib tsconfig.tsbuildinfo",
2254
+ ${lintScript(member, 'src')} "watch": "tsc -b --watch"
2255
+ },
2256
+ ${dependencyLines} "devDependencies": {
2257
+ "rimraf": "^5.0.0",
2258
+ "typescript": "^7.0.2"
2259
+ },
2260
+ "engines": {
2261
+ "node": ">=22.13"
2262
+ }
2263
+ }
2264
+ `;
2265
+ }
2266
+
2267
+ /** The protocol member's root entry, one re-export per module. */
2268
+ function protocolIndexFile(composition: InitComposition): string {
2269
+ const modules = [
2270
+ './generated-hydranium/languages.js',
2271
+ './generated-hydranium/transfer-model.js',
2272
+ ...(headPortConstants(composition).length ? ['./head-ports.js'] : []),
2273
+ ...composition.grammars.filter(grammar => grammar.diagram).map(grammar => `./${grammar.grammarId}-diagram-types.js`)
2274
+ ];
2275
+ const text = `// What the __NAME__ server and its clients both import. A client depends on
2276
+ // this package instead of the server, so it never installs Langium to reach a
2277
+ // constant or a wire type.
2278
+ //
2279
+ // The server's \`generate\` writes \`generated-hydranium/\` from the grammar;
2280
+ // commit those modules with the grammar change that produced them. An interface
2281
+ // narrowed here hides the generated constant of the same name; re-export that
2282
+ // constant beside it, and declare the type map under its own name with the
2283
+ // narrowed entry, or the builder and the GLSP state keep the generated one.
2284
+
2285
+ ${modules.map(module => `export * from '${module}';`).join('\n')}
2286
+ `;
2287
+ return project(text, composition);
2288
+ }
2289
+
2290
+ /** The protocol member's README. */
2291
+ function protocolReadme(composition: InitComposition): string {
2292
+ const lines = [
2293
+ `# ${memberPackageName(composition, 'protocol')}`,
2294
+ '',
2295
+ 'What the __NAME__ language server and its clients both import, so a client',
2296
+ 'never depends on the server or installs Langium.',
2297
+ '',
2298
+ '- `src/generated-hydranium/languages.ts` — each language id and its file extensions',
2299
+ '- `src/generated-hydranium/transfer-model.ts` — the wire types of the model, references as plain strings',
2300
+ ...(headPortConstants(composition).length === 0
2301
+ ? []
2302
+ : composition.heads.includes('lsp')
2303
+ ? ['- `src/head-ports.ts` — the LSP requests a host sends to find the socket heads']
2304
+ : ["- `src/head-ports.ts` — the environment variables naming the socket heads' ports"]),
2305
+ ...composition.grammars
2306
+ .filter(grammar => grammar.diagram)
2307
+ .map(grammar => `- \`src/${grammar.grammarId}-diagram-types.ts\` — the \`${grammar.grammar}\` diagram's type ids`),
2308
+ '',
2309
+ "The server's `npm run generate` writes `src/generated-hydranium/` from the",
2310
+ 'grammar, and `npm run build` here runs it first. Commit the generated',
2311
+ 'modules with the grammar change that produced them.',
2312
+ ''
2313
+ ];
2314
+ return project(lines.join('\n'), composition);
2315
+ }
2316
+
2317
+ /** The protocol member: everything the server and its clients both import. */
2318
+ function protocolFiles(composition: InitComposition): InitFile[] {
2319
+ return [
2320
+ { path: 'protocol/package.json', content: protocolPackageJson(composition) },
2321
+ { path: 'protocol/tsconfig.json', content: tsconfigJson(forMember(composition, 'protocol'), PROTOCOL_COMPILER_OPTIONS, '["src"]') },
2322
+ ignoreFile('protocol'),
2323
+ { path: 'protocol/README.md', content: protocolReadme(composition) },
2324
+ { path: 'protocol/src/index.ts', content: protocolIndexFile(composition) },
2325
+ ...(headPortConstants(composition).length ? [{ path: 'protocol/src/head-ports.ts', content: headPortsFile(composition) }] : []),
2326
+ ...composition.grammars
2327
+ .filter(grammar => grammar.diagram)
2328
+ .map(grammar => grammarTemplate('protocol/src/__GRAMMAR_ID__-diagram-types.ts', composition, grammar))
2329
+ ];
2330
+ }
2331
+
2332
+ /**
2333
+ * The starter model files every host and the CLI open, two per language: one
2334
+ * declaring nodes, one referencing a node in the other file.
2335
+ *
2336
+ * Named by extension alone, since `init` refuses two grammars sharing one.
2337
+ */
2338
+ function workspaceFiles(composition: InitComposition): InitFile[] {
2339
+ return composition.grammars.flatMap(grammar => [
2340
+ grammarTemplate('workspace/nodes.__EXTENSION__', composition, grammar),
2341
+ grammarTemplate('workspace/references.__EXTENSION__', composition, grammar)
2342
+ ]);
2343
+ }
2344
+
2345
+ /** The client member's compiler options: the protocol's, with the DOM its diagram renders into. */
2346
+ const CLIENT_COMPILER_OPTIONS: ReadonlyArray<readonly [string, JsonValue]> = [
2347
+ ['target', 'ES2022'],
2348
+ ['lib', ['ES2022', 'DOM']],
2349
+ ['module', 'NodeNext'],
2350
+ ['moduleResolution', 'NodeNext'],
2351
+ ['rootDir', 'src'],
2352
+ ['outDir', 'lib'],
2353
+ ['strict', true],
2354
+ ['skipLibCheck', true],
2355
+ ['declaration', true],
2356
+ // For inversify's `@injectable`, which a GLSP view needs to be bound.
2357
+ ['experimentalDecorators', true],
2358
+ ['types', []],
2359
+ // A base that sets it fails every `import` in this CommonJS member.
2360
+ ['verbatimModuleSyntax', false]
2361
+ ];
2362
+
2363
+ /**
2364
+ * The client member's `package.json`.
2365
+ *
2366
+ * CommonJS, unlike its siblings, as GLSP's client is: inversify ships an ES
2367
+ * build and a CommonJS one, so an ES module here would load the first while
2368
+ * GLSP's client loads the second, giving a page two containers' worth of
2369
+ * classes. Node from 22.12 and `tsc` under `nodenext` both let it require the
2370
+ * ES protocol member.
2371
+ */
2372
+ function clientPackageJson(composition: InitComposition): string {
2373
+ const dependencies: Record<string, string> = {
2374
+ [memberPackageName(composition, 'protocol')]: MEMBER_PIN,
2375
+ ...CLIENT_THIRD_PARTY_DEPENDENCIES
2376
+ };
2377
+ for (const framework of CLIENT_FRAMEWORK_DEPENDENCIES) {
2378
+ dependencies[framework] = frameworkPin(composition);
2379
+ }
2380
+ return `{
2381
+ "name": "${memberPackageName(composition, 'client')}",
2382
+ "version": "0.0.0",
2383
+ ${composition.packaging.private ? ' "private": true,\n' : ''} "description": "The host-neutral client side of the ${composition.name} language: what every host of it mounts.",
2384
+ "license": "UNLICENSED",
2385
+ "author": "",
2386
+ "files": [
2387
+ "lib",
2388
+ "src"
2389
+ ],
2390
+ "main": "lib/index.js",
2391
+ "types": "lib/index.d.ts",
2392
+ "scripts": {
2393
+ "build": "tsc -b",
2394
+ "clean": "rimraf lib tsconfig.tsbuildinfo",
2395
+ ${lintScript(forMember(composition, 'client'), 'src')} "watch": "tsc --watch"
2396
+ },
2397
+ "dependencies": {
2398
+ ${sortedBlock(dependencies, ' ')}
2399
+ },
2400
+ "devDependencies": {
2401
+ "rimraf": "^5.0.0",
2402
+ "typescript": "^7.0.2"
2403
+ },
2404
+ "engines": {
2405
+ "node": ">=22.13"
2406
+ }
2407
+ }
2408
+ `;
2409
+ }
2410
+
2411
+ /** The client member's README. */
2412
+ function clientReadme(composition: InitComposition): string {
2413
+ const diagrams = composition.grammars.filter(grammar => grammar.diagram);
2414
+ const lines = [
2415
+ `# ${memberPackageName(composition, 'client')}`,
2416
+ '',
2417
+ 'The host-neutral client side of the __NAME__ language: what every host of it',
2418
+ 'mounts, whatever that host is. It reads the element ids from the protocol',
2419
+ 'package and never depends on the server.',
2420
+ '',
2421
+ ...diagrams.map(
2422
+ grammar =>
2423
+ `- \`src/${grammar.grammarId}-diagram-module.ts\` — the \`${grammar.grammar}\` diagram: a registration per element type, its container module, and \`initialize${grammar.grammar}DiagramContainer\``
2424
+ ),
2425
+ '- `src/index.ts` — the package root, re-exporting each module',
2426
+ '',
2427
+ 'A host builds a diagram container with the initializer, passing its own',
2428
+ 'modules: they go first and the diagram definition last, since GLSP gives an',
2429
+ 'element type to whichever module registered it last.',
2430
+ ''
2431
+ ];
2432
+ return project(lines.join('\n'), composition);
2433
+ }
2434
+
2435
+ /** The client member's root entry, one re-export per diagram module. */
2436
+ function clientIndexFile(composition: InitComposition): string {
2437
+ const modules = composition.grammars.filter(grammar => grammar.diagram).map(grammar => `./${grammar.grammarId}-diagram-module.js`);
2438
+ return `// What every host of the ${composition.name} language mounts.
2439
+
2440
+ ${modules.map(module => `export * from '${module}';`).join('\n')}
2441
+ `;
2442
+ }
2443
+
2444
+ /**
2445
+ * The client member: the host-neutral client side of the language, emitted
2446
+ * when there is a diagram to define. Each host mounts it rather than defining
2447
+ * the diagram again.
2448
+ */
2449
+ function clientFiles(composition: InitComposition): InitFile[] {
2450
+ return [
2451
+ { path: 'client/package.json', content: clientPackageJson(composition) },
2452
+ {
2453
+ path: 'client/tsconfig.json',
2454
+ content: tsconfigJson(forMember(composition, 'client'), CLIENT_COMPILER_OPTIONS, '["src"]', '[{ "path": "../protocol" }]')
2455
+ },
2456
+ ignoreFile('client'),
2457
+ { path: 'client/README.md', content: clientReadme(composition) },
2458
+ { path: 'client/src/index.ts', content: clientIndexFile(composition) },
2459
+ ...composition.grammars
2460
+ .filter(grammar => grammar.diagram)
2461
+ .map(grammar => grammarTemplate('client/src/__GRAMMAR_ID__-diagram-module.ts', composition, grammar))
2462
+ ];
2463
+ }
2464
+
2465
+ /**
2466
+ * The browser host's `package.json`. Always private: it is an application,
2467
+ * which nothing installs as a dependency.
2468
+ */
2469
+ function hostBrowserPackageJson(composition: InitComposition): string {
2470
+ const dependencies: Record<string, string> = {
2471
+ [memberPackageName(composition, 'protocol')]: MEMBER_PIN,
2472
+ [memberPackageName(composition, 'server')]: MEMBER_PIN,
2473
+ ...(composition.heads.includes('glsp') ? { [memberPackageName(composition, 'client')]: MEMBER_PIN } : {}),
2474
+ // A page with no editor saves through the diagram's own action dispatcher.
2475
+ ...(composition.heads.includes('lsp') ? {} : { '@eclipse-glsp/client': CLIENT_THIRD_PARTY_DEPENDENCIES['@eclipse-glsp/client'] })
2476
+ };
2477
+ for (const head of ['base', ...composition.heads] as const) {
2478
+ Object.assign(dependencies, HOST_BROWSER_THIRD_PARTY_DEPENDENCIES[head]);
2479
+ for (const framework of HOST_BROWSER_FRAMEWORK_DEPENDENCIES[head]) {
2480
+ dependencies[framework] = frameworkPin(composition);
2481
+ }
2482
+ }
2483
+ return `{
2484
+ "name": "${memberPackageName(composition, 'host-browser')}",
2485
+ "version": "0.0.0",
2486
+ "private": true,
2487
+ "description": "${composition.name} in a browser page, with every head in a web worker and no backend.",
2488
+ "license": "UNLICENSED",
2489
+ "author": "",
2490
+ "type": "module",
2491
+ "scripts": {
2492
+ "build": "npm run typecheck && node esbuild.mjs",
2493
+ "clean": "rimraf out test-results playwright-report",
2494
+ ${lintScript(forMember(composition, 'host-browser'), 'src test')} "start": "node esbuild.mjs --serve",
2495
+ "test:e2e": "playwright test --tsconfig tsconfig.e2e.json",
2496
+ "test:e2e:install": "playwright install chromium",
2497
+ "typecheck": "tsc --noEmit -p tsconfig.worker.json && tsc --noEmit -p tsconfig.page.json && tsc --noEmit -p tsconfig.e2e.json"
2498
+ },
2499
+ "dependencies": {
2500
+ ${sortedBlock(dependencies, ' ')}
2501
+ },
2502
+ "devDependencies": {
2503
+ ${sortedBlock(HOST_BROWSER_DEV_DEPENDENCIES, ' ')}
2504
+ },
2505
+ "engines": {
2506
+ "node": ">=22.13"
2507
+ }
2508
+ }
2509
+ `;
2510
+ }
2511
+
2512
+ /** The workspace URI of a grammar's first starter file, as a template literal over `WORKSPACE_ROOT_URI`. */
2513
+ function starterUri(grammar: InitGrammarNames): string {
2514
+ return `\`\${WORKSPACE_ROOT_URI}/nodes.${grammar.extensions[0]}\``;
2515
+ }
2516
+
2517
+ /**
2518
+ * The worker hosting the heads: every head over the one store, with the
2519
+ * workspace seeded from `../workspace` and saved files kept in IndexedDB.
2520
+ */
2521
+ function hostWorkerFile(composition: InitComposition): string {
2522
+ const columns = columnsFor(composition);
2523
+ const lsp = composition.heads.includes('lsp');
2524
+ const data = composition.heads.includes('data');
2525
+ const glsp = composition.heads.includes('glsp');
2526
+ const diagrams = composition.grammars.filter(grammar => grammar.diagram);
2527
+ const roots = composition.grammars.map(grammar => grammar.entryRule).sort();
2528
+ const serverSymbols = [`create${composition.name}Services`, ...diagrams.map(grammar => `${grammar.grammar}DiagramModule`)].sort(
2529
+ (left, right) => left.localeCompare(right)
2530
+ );
2531
+
2532
+ const imports = [
2533
+ ...(glsp
2534
+ ? [
2535
+ '// First, before any class carrying a decorator loads: GLSP reads the metadata',
2536
+ '// its decorators emit as each class is defined.',
2537
+ "import 'reflect-metadata';",
2538
+ "import { ServerModule } from '@eclipse-glsp/server/browser.js';"
2539
+ ]
2540
+ : []),
2541
+ "import { persistentFileSystem } from '@hydranium/core';",
2542
+ importList(
2543
+ ['hostHeadsInWorker', 'IndexedDbFileSystemStore', ...(lsp ? ['startLanguageServerInWorker'] : [])],
2544
+ '@hydranium/core/browser',
2545
+ columns
2546
+ ),
2547
+ ...(data
2548
+ ? [
2549
+ "import { DataServer } from '@hydranium/data-server';",
2550
+ "import { startDataServerInWorker } from '@hydranium/data-server/browser';"
2551
+ ]
2552
+ : []),
2553
+ ...(glsp
2554
+ ? [
2555
+ "import { GlspClientLogger, HydraniumGlspAppModule } from '@hydranium/glsp-server';",
2556
+ "import { startGlspServerInWorker } from '@hydranium/glsp-server/browser';"
2557
+ ]
2558
+ : []),
2559
+ ...(data ? [importList(roots, memberPackageName(composition, 'protocol'), columns, true)] : []),
2560
+ importList(serverSymbols, memberPackageName(composition, 'server'), columns),
2561
+ "import { WORKSPACE_ROOT_URI } from './workspace.js';"
2562
+ ];
2563
+
2564
+ const services = `const shared = create${composition.name}Services({ ...fileSystem }).shared;`;
2565
+ const lspCall = `startLanguageServerInWorker(ports.lsp, connection => create${composition.name}Services({ connection, ...fileSystem }).shared);`;
2566
+ const startServices = !lsp
2567
+ ? services
2568
+ : ` const shared = ${lspCall}`.length <= columns
2569
+ ? `const shared = ${lspCall}`
2570
+ : `const shared = startLanguageServerInWorker(
2571
+ ports.lsp,
2572
+ connection => create${composition.name}Services({ connection, ...fileSystem }).shared
2573
+ );`;
2574
+ const dataServer = `connection => new DataServer<${roots.join(' | ')}>(connection, shared)`;
2575
+ const dataCall = `startDataServerInWorker(ports.data, shared, ${dataServer});`;
2576
+ const dataHead = data
2577
+ ? `
2578
+ // The data head serves from the ${lsp ? "LSP head's" : "services'"} store, on its own port.
2579
+ ${
2580
+ ` ${dataCall}`.length <= columns
2581
+ ? dataCall
2582
+ : `startDataServerInWorker(
2583
+ ports.data,
2584
+ shared,
2585
+ ${dataServer}
2586
+ );`
2587
+ }`
2588
+ : '';
2589
+ const glspHead = glsp
2590
+ ? `
2591
+ const glsp = startGlspServerInWorker({
2592
+ context: ports.glsp,
2593
+ createLogger: caller => new GlspClientLogger(shared, { component: caller }),
2594
+ serverModule: new ServerModule()${diagrams.map(grammar => `.configureDiagramModule(new ${grammar.grammar}DiagramModule())`).join('')},
2595
+ appModules: [new HydraniumGlspAppModule({ shared })]
2596
+ });
2597
+ // The GLSP head reports a failed start through \`started\`, which the
2598
+ // ready message waits for.
2599
+ return { shared, started: [glsp.started] };`
2600
+ : `
2601
+ return shared;`;
2602
+
2603
+ const text = `// The worker hosting the heads: every head over one store, in the browser and
2604
+ // with no backend. The page reaches each head over a \`MessagePort\` of its own.
2605
+
2606
+ ${imports.join('\n')}
2607
+
2608
+ /** The files of \`../workspace\`, read by \`esbuild.mjs\` and keyed by their path below the root. */
2609
+ declare const __WORKSPACE_SEED__: Record<string, string>;
2610
+ /** This project's directory, hashed by \`esbuild.mjs\`, so that no other project on the origin opens its store. */
2611
+ declare const __DIRECTORY_KEY__: string;
2612
+
2613
+ // A saved file is kept in IndexedDB and laid over the seed on the next load;
2614
+ // the heads start once the stored files are restored.
2615
+ const store = new IndexedDbFileSystemStore(\`__PROJECT_ID__-workspace-\${__DIRECTORY_KEY__}\`);
2616
+
2617
+ hostHeadsInWorker(
2618
+ persistentFileSystem({ store, seed: __WORKSPACE_SEED__, rootUri: WORKSPACE_ROOT_URI }),
2619
+ (ports, fileSystem) => {
2620
+ ${lsp ? '// The LSP head composes the services, as the Node entry does around stdio.\n ' : ''}${startServices}${dataHead}${glspHead}
2621
+ },
2622
+ ${
2623
+ lsp
2624
+ ? '// The ready message then carries the workspace files the page opens.'
2625
+ : '// With no LSP head the workspace comes up from this root, and the ready\n // message then carries its files.'
2626
+ }
2627
+ { rootUri: WORKSPACE_ROOT_URI }
2628
+ );
2629
+ `;
2630
+ return project(text, composition);
2631
+ }
2632
+
2633
+ /**
2634
+ * The page, and the one place deciding which head's part of it runs: each
2635
+ * part is a module of its own, and this calls the ones the heads serve.
2636
+ */
2637
+ function hostPageFile(composition: InitComposition): string {
2638
+ const lsp = composition.heads.includes('lsp');
2639
+ const data = composition.heads.includes('data');
2640
+ const diagram = composition.grammars.find(grammar => grammar.diagram);
2641
+ // A host takes lsp or glsp, and glsp marks a diagram grammar, so without lsp there is one.
2642
+ const diagramLanguage = lsp || diagram === undefined ? undefined : `${screamingSnake(diagram.grammarId)}_LANGUAGE`;
2643
+ const shownLanguage = diagramLanguage ?? 'ALL_LANGUAGES';
2644
+ const parts = [
2645
+ // Every part follows the file the page shows, so the switch comes first. With
2646
+ // no editor it lists only the diagram's files, the only ones the page shows.
2647
+ {
2648
+ module: './shown-file.js',
2649
+ imports: 'startShownFile',
2650
+ call: `const shownFile = await startShownFile(heads, ${diagramLanguage === undefined ? shownLanguage : `[${diagramLanguage}]`});`
2651
+ },
2652
+ // Save is armed with the editor, so it works before the other panes load;
2653
+ // with a diagram it waits for the edits of the one shown, once mounted.
2654
+ ...(lsp
2655
+ ? [
2656
+ {
2657
+ module: './editor.js',
2658
+ imports: 'armEditorSave, startEditor',
2659
+ call: [
2660
+ 'const editor = await startEditor(heads, shownFile);',
2661
+ ...(diagram === undefined
2662
+ ? ['armEditorSave(editor);']
2663
+ : [
2664
+ 'let shownDiagram: Awaited<ReturnType<typeof mountDiagram>> | undefined = undefined;',
2665
+ 'armEditorSave(editor, () => settleDiagramEdits(shownDiagram?.()));'
2666
+ ])
2667
+ ].join('\n ')
2668
+ }
2669
+ ]
2670
+ : []),
2671
+ ...(data
2672
+ ? [
2673
+ {
2674
+ module: './data-status.js',
2675
+ imports: 'showDataStatus',
2676
+ call: `await showDataStatus(heads.data, ${starterUri(composition.grammars[0])});`
2677
+ }
2678
+ ]
2679
+ : []),
2680
+ ...(diagram === undefined
2681
+ ? []
2682
+ : [
2683
+ {
2684
+ module: './diagram.js',
2685
+ imports: lsp ? 'mountDiagram, settleDiagramEdits' : 'mountDiagram',
2686
+ call: `${lsp ? 'shownDiagram' : 'const shownDiagram'} = await mountDiagram(heads.glsp, shownFile, logger, ${lsp ? 'settleDiagramEdits' : 'saveBeforeLeaving'});`
2687
+ }
2688
+ ]),
2689
+ // Without the editor, the diagram is what the page saves through.
2690
+ ...(lsp ? [] : [{ module: './diagram-save.js', imports: 'armDiagramSave, saveBeforeLeaving', call: 'armDiagramSave(shownDiagram);' }])
2691
+ ];
2692
+ const imports = [
2693
+ ...parts.map(part => `import { ${part.imports} } from '${part.module}';`),
2694
+ "import { appendLog, setStatus } from './log.js';",
2695
+ ...(data ? ["import { WORKSPACE_ROOT_URI } from './workspace.js';"] : [])
2696
+ ].sort((left, right) => left.slice(left.indexOf("'")).localeCompare(right.slice(right.indexOf("'"))));
2697
+
2698
+ return `// The page: it starts the worker, hands each head a channel of its own, and
2699
+ // fills the pane of each head the server runs, one after the other.
2700
+
2701
+ import { connectWorkerHeads } from '@hydranium/client-browser';
2702
+ import { ConsoleLogger, describeError } from '@hydranium/protocol';
2703
+ import { ${shownLanguage} } from '${memberPackageName(composition, 'protocol')}';
2704
+ ${imports.join('\n')}
2705
+
2706
+ /** Where the worker bundle is served, substituted by \`esbuild.mjs\`. */
2707
+ declare const __WORKER_BUNDLE_URL__: string;
2708
+
2709
+ async function main(): Promise<void> {
2710
+ // The page's end of each head's connection logs to the browser console.
2711
+ const logger = new ConsoleLogger();
2712
+ const heads = connectWorkerHeads(new Worker(__WORKER_BUNDLE_URL__), { logger });
2713
+ heads.onWorkerError(report => appendLog(\`worker error during \${report.phase}: \${report.message}\`));
2714
+ setStatus('starting…');
2715
+ ${parts.map(part => ` ${part.call}`).join('\n')}
2716
+ setStatus('ready');
2717
+ }
2718
+
2719
+ main().catch((error: unknown) => setStatus(\`failed: \${describeError(error)}\`));
2720
+ `;
2721
+ }
2722
+
2723
+ /**
2724
+ * The smoke test: what each head shows on the page, and an edit that survives
2725
+ * a reload, typed in the editor or, with no LSP head, made in the diagram. With
2726
+ * a diagram, also a diagram edit the reload guard and Save catch before the
2727
+ * server has answered it.
2728
+ */
2729
+ function hostSmokeSpec(composition: InitComposition): string {
2730
+ const lsp = composition.heads.includes('lsp');
2731
+ const data = composition.heads.includes('data');
2732
+ const diagram = composition.grammars.find(grammar => grammar.diagram);
2733
+ const primary = composition.grammars[0];
2734
+ const checks = [
2735
+ ...(lsp ? [" await expect(editor).toContainText('node First');"] : []),
2736
+ ...(data
2737
+ ? [
2738
+ ' // The data head reads the document out of the same store.',
2739
+ ` await expect(page.locator('#data-status')).toHaveText('data head: nodes.${primary.extensions[0]} holds a ${primary.entryRule}');`
2740
+ ]
2741
+ : []),
2742
+ ...(diagram === undefined
2743
+ ? []
2744
+ : [
2745
+ ' // The diagram follows the switch: two nodes in one file, and in the other its',
2746
+ ' // node and the target it references there, drawn as external.',
2747
+ " const first = await page.locator('#file').inputValue();",
2748
+ ` await page.locator('#file').selectOption('nodes.${diagram.extensions[0]}');`,
2749
+ " await expect(page.locator('#diagram .sprotty-node')).toHaveCount(2);",
2750
+ ` await page.locator('#file').selectOption('references.${diagram.extensions[0]}');`,
2751
+ ` await expect(page.locator('#diagram .external')).toHaveText('Second (nodes.${diagram.extensions[0]})');`,
2752
+ " await page.locator('#file').selectOption(first);"
2753
+ ])
2754
+ ];
2755
+ const edit = lsp
2756
+ ? ` await editor.click();
2757
+ await page.keyboard.press('ControlOrMeta+End');
2758
+ await page.keyboard.type('\\nnode Added');
2759
+ await page.locator('#save').click();
2760
+ await expect(page.locator('#status')).toHaveText('saved 1 file(s)');
2761
+
2762
+ await page.reload();
2763
+ await expect(page.locator('#status')).toHaveText('ready');
2764
+ await expect(editor).toContainText('node Added');`
2765
+ : ` // A node from the palette, dropped low and left of centre: the starter nodes
2766
+ // sit in the upper band and the palette in the upper right.
2767
+ const canvas = page.locator('#diagram');
2768
+ const create = async (): Promise<void> => {
2769
+ await page.locator('#diagram .tool-button', { hasText: '${diagram?.nodeRule}' }).click();
2770
+ const size = await canvas.evaluate(element => ({ width: element.clientWidth, height: element.clientHeight }));
2771
+ await canvas.click({ position: { x: size.width * 0.4, y: size.height * 0.85 } });
2772
+ };
2773
+ await create();
2774
+ await expect(nodes).toHaveCount(3);
2775
+ await page.locator('#save').click();
2776
+ await expect(page.locator('#status')).toHaveText('saved the diagram');
2777
+ // A second, left unsaved: the switch saves the diagram it leaves.
2778
+ await create();
2779
+ await expect(nodes).toHaveCount(4);
2780
+ await page.locator('#file').selectOption('references.${diagram?.extensions[0]}');
2781
+ await expect(page.locator('#diagram .external')).toBeVisible();
2782
+
2783
+ await page.reload();
2784
+ await expect(page.locator('#status')).toHaveText('ready');
2785
+ await expect(nodes).toHaveCount(4);`;
2786
+ const guardTest =
2787
+ diagram === undefined
2788
+ ? ''
2789
+ : `
2790
+ test('asks before a reload drops a diagram edit the server has not answered, and saves it with Save at once', async ({ page }) => {
2791
+ const nodes = page.locator('#diagram .sprotty-node');
2792
+ const askGuard = (): Promise<boolean> =>
2793
+ page.evaluate(() => {
2794
+ const event = new Event('beforeunload', { cancelable: true });
2795
+ window.dispatchEvent(event);
2796
+ return event.defaultPrevented;
2797
+ });
2798
+ await page.goto('/');
2799
+ await expect(page.locator('#status')).toHaveText('ready');
2800
+ await page.locator('#file').selectOption('nodes.${diagram.extensions[0]}');
2801
+ await expect(nodes).toHaveCount(2);
2802
+
2803
+ const canvas = page.locator('#diagram');
2804
+ await page.locator('#diagram .tool-button', { hasText: '${diagram.nodeRule}' }).click();
2805
+ const size = await canvas.evaluate(element => ({ width: element.clientWidth, height: element.clientHeight }));
2806
+ // Asked and clicked right after the click's own handlers, in the same turn
2807
+ // of the page, so the server's answer cannot have marked anything unsaved.
2808
+ await page.evaluate(() => {
2809
+ window.addEventListener(
2810
+ 'mouseup',
2811
+ () =>
2812
+ queueMicrotask(() => {
2813
+ const event = new Event('beforeunload', { cancelable: true });
2814
+ window.dispatchEvent(event);
2815
+ document.getElementById('save')?.click();
2816
+ Reflect.set(window, 'guardedOnCreate', event.defaultPrevented);
2817
+ }),
2818
+ { once: true }
2819
+ );
2820
+ });
2821
+ await canvas.click({ position: { x: size.width * 0.4, y: size.height * 0.85 } });
2822
+ expect(await page.evaluate(() => Reflect.get(window, 'guardedOnCreate'))).toBe(true);
2823
+ await expect(page.locator('#status')).toHaveText('${lsp ? 'saved 1 file(s)' : 'saved the diagram'}');
2824
+ expect(await askGuard()).toBe(false);
2825
+
2826
+ await page.reload();
2827
+ await expect(page.locator('#status')).toHaveText('ready');
2828
+ await page.locator('#file').selectOption('nodes.${diagram.extensions[0]}');
2829
+ await expect(nodes).toHaveCount(3);
2830
+ });
2831
+ `;
2832
+ const locators = [
2833
+ ...(lsp ? [" const editor = page.locator('#editor .view-lines');"] : []),
2834
+ ...(lsp ? [] : [" const nodes = page.locator('#diagram .sprotty-node');"])
2835
+ ];
2836
+ return `// The page loads with every head answering, and an edit saved through the
2837
+ // ${lsp ? 'LSP head' : 'GLSP head'} is still there after a reload; any console error fails that
2838
+ // test. The other asks before a reload drops a diagram edit the server has not
2839
+ // answered yet, and keeps it when Save is clicked at once.
2840
+
2841
+ import { expect, test } from '@playwright/test';
2842
+
2843
+ test('loads every head and keeps a saved ${lsp ? 'edit' : 'diagram edit'} across a reload', async ({ page }) => {
2844
+ const errors: string[] = [];
2845
+ page.on('pageerror', error => errors.push(error.message));
2846
+ page.on('console', message => {
2847
+ if (message.type() === 'error') {
2848
+ errors.push(message.text());
2849
+ }
2850
+ });
2851
+ ${locators.join('\n')}
2852
+
2853
+ await page.goto('/');
2854
+ await expect(page.locator('#status')).toHaveText('ready');
2855
+ ${checks.join('\n')}
2856
+
2857
+ ${edit}
2858
+ expect(errors).toEqual([]);
2859
+ });
2860
+ ${guardTest}`;
2861
+ }
2862
+
2863
+ /** The browser host's README. */
2864
+ function hostBrowserReadme(composition: InitComposition): string {
2865
+ const lsp = composition.heads.includes('lsp');
2866
+ const data = composition.heads.includes('data');
2867
+ const diagram = composition.grammars.find(grammar => grammar.diagram);
2868
+ const lines = [
2869
+ `# ${memberPackageName(composition, 'host-browser')}`,
2870
+ '',
2871
+ '__NAME__ in a browser page: every head runs in a web worker, with no backend',
2872
+ `and no Node runtime. The page saves through the ${lsp ? 'LSP head' : 'GLSP head'}, and the worker`,
2873
+ 'keeps each saved file in IndexedDB, laid over `../workspace` on the next',
2874
+ 'load.',
2875
+ '',
2876
+ '```bash',
2877
+ 'npm run build # type-check and bundle into out/',
2878
+ 'npm start # serve the page at the URL it prints, rebundled on every source change',
2879
+ 'npm run test:e2e:install # download the Chromium the smoke test drives, once',
2880
+ 'npm run test:e2e # the smoke test, which serves the page itself',
2881
+ '```',
2882
+ '',
2883
+ '`PORT` moves the page to another port, for `npm start` and the smoke test alike;',
2884
+ 'stop `npm start` before the smoke test, or give one of them another port.',
2885
+ '`npm start` reads `../workspace` once, so restart it after editing a file',
2886
+ 'there.',
2887
+ '',
2888
+ '## Layout',
2889
+ '',
2890
+ '- `index.html` — the page, with a pane for each head that stays hidden until its part fills it',
2891
+ '- `hydranium-mark.svg` — the tab icon',
2892
+ `- \`esbuild.mjs\` — bundles the page${lsp ? ', the worker and Monaco’s worker' : ' and the worker'}, reading \`../workspace\` in as the seed`,
2893
+ '- `src/worker.ts` — the worker: the heads over one store, seeded and persisted',
2894
+ '- `src/page.ts` — starts the worker and runs the part of the page each head serves',
2895
+ '- `src/shown-file.ts` — the file switch above the panes, which every part follows',
2896
+ ...(lsp ? ['- `src/editor.ts` — the LSP part: a Monaco editor and Save'] : []),
2897
+ ...(data ? ['- `src/data-status.ts` — the data part: one document read through the data head'] : []),
2898
+ ...(diagram === undefined
2899
+ ? []
2900
+ : [
2901
+ `- \`src/diagram.ts\` — the GLSP part: the \`${diagram.grammar}\` diagram of the file the page shows, defined in the client package`
2902
+ ]),
2903
+ ...(lsp ? [] : ['- `src/diagram-save.ts` — Save with no editor: the diagram saved through the GLSP head']),
2904
+ '- `src/log.ts` — the status line and the log area',
2905
+ '- `src/workspace.ts` — the workspace root URI both ends name',
2906
+ ...(lsp ? ['- `src/monaco-editor-worker.ts` — Monaco’s own worker, which hosts no head'] : []),
2907
+ '- `src/posix-path-shim.ts` — the `path` function the framework imports, for the bundle',
2908
+ '- `test/smoke.spec.mts` — the page loads, each head answers, and a saved edit survives a reload',
2909
+ ''
2910
+ ];
2911
+ return project(lines.join('\n'), composition);
2912
+ }
2913
+
2914
+ /** The page with the line under its log view saying what shows there, which the LSP head decides. */
2915
+ function withLogHint(page: InitFile, lsp: boolean): InitFile {
2916
+ const hint = lsp
2917
+ ? 'What the server logs over the LSP head, and the errors the page reports.'
2918
+ : "The errors the page reports. The server logs to the worker's console, in the browser's developer tools.";
2919
+ return { ...page, content: page.content.replace('__LOG_HINT__', hint) };
2920
+ }
2921
+
2922
+ /** The browser host: a page and a worker, bundled by esbuild and served as static files. */
2923
+ function hostBrowserFiles(composition: InitComposition): InitFile[] {
2924
+ const fixed = (file: string): InitFile => projectTemplate(`host-browser/${file}`, composition);
2925
+ const lsp = composition.heads.includes('lsp');
2926
+ const diagram = composition.grammars.find(grammar => grammar.diagram);
2927
+ return [
2928
+ { path: 'host-browser/package.json', content: hostBrowserPackageJson(composition) },
2929
+ ignoreFile('host-browser'),
2930
+ { path: 'host-browser/README.md', content: hostBrowserReadme(composition) },
2931
+ withLogHint(fixed('index.html'), lsp),
2932
+ fixed('hydranium-mark.svg'),
2933
+ fixed('esbuild.mjs'),
2934
+ fixed('playwright.config.mts'),
2935
+ fixed('tsconfig.worker.json'),
2936
+ fixed('tsconfig.page.json'),
2937
+ fixed('tsconfig.e2e.json'),
2938
+ { path: 'host-browser/src/worker.ts', content: hostWorkerFile(composition) },
2939
+ { path: 'host-browser/src/page.ts', content: hostPageFile(composition) },
2940
+ fixed('src/shown-file.ts'),
2941
+ ...(lsp ? [fixed('src/editor.ts')] : []),
2942
+ ...(composition.heads.includes('data') ? [fixed('src/data-status.ts')] : []),
2943
+ ...(diagram === undefined ? [] : [grammarTemplate('host-browser/src/diagram.ts', composition, diagram)]),
2944
+ ...(lsp ? [] : [fixed('src/diagram-save.ts')]),
2945
+ fixed('src/log.ts'),
2946
+ fixed('src/workspace.ts'),
2947
+ ...(lsp ? [fixed('src/monaco-editor-worker.ts'), fixed('src/monaco-editor-core-worker.d.ts')] : []),
2948
+ fixed('src/posix-path-shim.ts'),
2949
+ { path: 'host-browser/test/smoke.spec.mts', content: hostSmokeSpec(composition) }
2950
+ ];
2951
+ }
2952
+
2953
+ /** A JSON value as it sits at `indent` in a manifest npm writes. */
2954
+ function jsonAt(value: unknown, indent: string): string {
2955
+ return JSON.stringify(value, null, 2).replace(/\n/g, `\n${indent}`);
2956
+ }
2957
+
2958
+ /**
2959
+ * The languages and grammars a VS Code extension contributes. Each extension
2960
+ * declares its own, since either may be installed without the other; the
2961
+ * grammars are the server's, copied in by `copy:syntaxes`.
2962
+ */
2963
+ function vscodeLanguageContributions(composition: InitComposition): Record<string, unknown> {
2964
+ return {
2965
+ grammars: composition.grammars.map(grammar => ({
2966
+ language: grammar.languageId,
2967
+ scopeName: `source.${grammar.languageId}`,
2968
+ path: `./syntaxes/${grammar.languageId}.tmLanguage.json`
2969
+ })),
2970
+ languages: composition.grammars.map(grammar => ({
2971
+ id: grammar.languageId,
2972
+ aliases: [grammar.grammar],
2973
+ extensions: grammar.extensions.map(extension => `.${extension}`)
2974
+ }))
2975
+ };
2976
+ }
2977
+
2978
+ /** VS Code finds the grammars only inside the extension, so the build copies the server's. */
2979
+ const COPY_SYNTAXES_SCRIPT = "require('node:fs').cpSync('../server/syntaxes', 'syntaxes', { recursive: true })";
2980
+ const COPY_SYNTAXES = `node -e \\"${COPY_SYNTAXES_SCRIPT}\\"`;
2981
+
2982
+ /** `copy:syntaxes`, then again each time the server's `langium:watch` rewrites a grammar. */
2983
+ const WATCH_SYNTAXES = `node -e \\"const copy = () => ${COPY_SYNTAXES_SCRIPT}; copy(); require('node:fs').watch('../server/syntaxes', copy)\\"`;
2984
+
2985
+ /**
2986
+ * The servers-only extension's `package.json`. Always private, like a host:
2987
+ * it is installed into an application, never as a dependency.
2988
+ *
2989
+ * `onStartupFinished` rather than `onLanguage`, since a Theia backend asks for
2990
+ * a port before any document is open.
2991
+ */
2992
+ function vscodeServersPackageJson(composition: InitComposition): string {
2993
+ const dependencies: Record<string, string> = {
2994
+ [memberPackageName(composition, 'protocol')]: MEMBER_PIN,
2995
+ [memberPackageName(composition, 'server')]: MEMBER_PIN,
2996
+ ...VSCODE_LANGUAGE_CLIENT
2997
+ };
2998
+ if (socketHeads(composition).length > 0) {
2999
+ dependencies['@hydranium/client-vscode'] = frameworkPin(composition);
3000
+ }
3001
+ return `{
3002
+ "name": "${memberPackageName(composition, 'vscode-servers')}",
3003
+ "displayName": "${composition.name} Servers",
3004
+ "version": "0.0.0",
3005
+ "private": true,
3006
+ "description": "Starts the ${composition.name} server${socketHeads(composition).length > 0 ? " and publishes its socket heads' ports as host commands" : ''}, with no editor of its own.",
3007
+ "license": "UNLICENSED",
3008
+ "author": "",
3009
+ "publisher": "${composition.projectId}",
3010
+ "main": "./out/extension.js",
3011
+ "scripts": {
3012
+ "build": "npm run copy:syntaxes && tsc",
3013
+ "clean": "rimraf out syntaxes tsconfig.tsbuildinfo",
3014
+ "copy:syntaxes": "${COPY_SYNTAXES}",
3015
+ ${lintScript(forMember(composition, 'vscode-servers'), 'src')} "watch": "concurrently --kill-others --names syntaxes,tsc \\"npm run watch:syntaxes\\" \\"tsc --watch\\"",
3016
+ "watch:syntaxes": "${WATCH_SYNTAXES}"
3017
+ },
3018
+ "dependencies": {
3019
+ ${sortedBlock(dependencies, ' ')}
3020
+ },
3021
+ "devDependencies": {
3022
+ ${sortedBlock({ '@types/node': '^22.0.0', '@types/vscode': VSCODE_ENGINE, concurrently: '^9.0.0', rimraf: '^5.0.0', typescript: '^7.0.2' }, ' ')}
3023
+ },
3024
+ "contributes": ${jsonAt(vscodeLanguageContributions(composition), ' ')},
3025
+ "activationEvents": [
3026
+ "onStartupFinished"
3027
+ ],
3028
+ "engines": {
3029
+ "vscode": "${VSCODE_ENGINE}"
3030
+ }
3031
+ }
3032
+ `;
3033
+ }
3034
+
3035
+ /**
3036
+ * The servers-only extension's activation: the shared launch, and with a socket
3037
+ * head the port commands, which only this extension registers.
3038
+ */
3039
+ function vscodeServersExtensionFile(composition: InitComposition): string {
3040
+ const upper = screamingSnake(composition.projectId);
3041
+ const heads = socketHeads(composition).map(head => head.key);
3042
+ const protocolSymbols = heads.flatMap(head => [`${upper}_${head}_HOST_COMMAND`, `${upper}_${head}_PORT_COMMAND`]);
3043
+ const imports =
3044
+ heads.length === 0
3045
+ ? ''
3046
+ : `import { registerPortCommands } from '@hydranium/client-vscode/node';
3047
+ ${importList(protocolSymbols, memberPackageName(composition, 'protocol'), columnsFor(composition))}
3048
+ `;
3049
+ const portCommands =
3050
+ heads.length === 0
3051
+ ? ''
3052
+ : `
3053
+
3054
+ // Each socket head's port as a host command, for a host with no language
3055
+ // client of its own. Not in the shared launch: VS Code throws on a second
3056
+ // registration of one id, so the VS Code extension beside this one would fail
3057
+ // to activate. A pass-through: awaiting anything else in it would hang a
3058
+ // Theia backend on a user dismissing a notification.
3059
+ registerPortCommands(context, client, {
3060
+ ${heads.map(head => ` [${upper}_${head}_HOST_COMMAND]: ${upper}_${head}_PORT_COMMAND`).join(',\n')}
3061
+ });`;
3062
+ return `// The servers-only extension: it starts the ${composition.name} server and contributes no
3063
+ // editor, view or command. A Theia app sideloads this one rather than the VS
3064
+ // Code extension, whose diagram editors would give its files a second editor.
3065
+
3066
+ ${imports}import type { ExtensionContext } from 'vscode';
3067
+ import type { LanguageClient } from 'vscode-languageclient/node';
3068
+ import { start${composition.name}LanguageClient } from './language-client.js';
3069
+
3070
+ let client: LanguageClient | undefined;
3071
+
3072
+ export async function activate(context: ExtensionContext): Promise<void> {
3073
+ client = await start${composition.name}LanguageClient(context);${portCommands}
3074
+ }
3075
+
3076
+ export async function deactivate(): Promise<void> {
3077
+ await client?.stop();
3078
+ client = undefined;
3079
+ }
3080
+ `;
3081
+ }
3082
+
3083
+ /**
3084
+ * The server launch both extensions share: one launch, so VS Code and a Theia
3085
+ * app sideloading the servers extension hand the server the same documents.
3086
+ */
3087
+ function vscodeLanguageClientFile(composition: InitComposition): string {
3088
+ return `// Starts the ${composition.name} server for VS Code, and for a Theia app that sideloads
3089
+ // this extension: one launch, so both hand the server the same documents.
3090
+
3091
+ import { ALL_LANGUAGES } from '${memberPackageName(composition, 'protocol')}';
3092
+ import { type ExtensionContext, workspace } from 'vscode';
3093
+ import { LanguageClient, TransportKind } from 'vscode-languageclient/node';
3094
+
3095
+ /** Fork the server, start its language client and return it once started. */
3096
+ export async function start${composition.name}LanguageClient(context: ExtensionContext): Promise<LanguageClient> {
3097
+ // Resolved through the package, so it works from the workspace and from an
3098
+ // installed extension alike. Over IPC, which keeps the server's stdout free.
3099
+ const serverModule = require.resolve('${memberPackageName(composition, 'server')}/lib/main.js');
3100
+ const extensions = ALL_LANGUAGES.flatMap(language => language.fileExtensions).join(',');
3101
+ const client = new LanguageClient(
3102
+ '${composition.projectId}',
3103
+ '${composition.name}',
3104
+ { module: serverModule, transport: TransportKind.ipc },
3105
+ {
3106
+ documentSelector: ALL_LANGUAGES.map(({ languageId }) => ({ scheme: 'file', language: languageId })),
3107
+ // Changes on disk the editor does not hold, such as a file another tool writes.
3108
+ synchronize: { fileEvents: workspace.createFileSystemWatcher(\`**/*{\${extensions}}\`) }
3109
+ }
3110
+ );
3111
+ context.subscriptions.push(client);
3112
+ await client.start();
3113
+
3114
+ return client;
3115
+ }
3116
+ `;
3117
+ }
3118
+
3119
+ /** The folders of the Theia applications the composition emits, as code spans. */
3120
+ function theiaApplicationPaths(composition: InitComposition): string[] {
3121
+ return composition.hosts.filter(isTheiaHost).map(host => `\`../host-${host}\``);
3122
+ }
3123
+
3124
+ /** The servers-only extension's README. */
3125
+ function vscodeServersReadme(composition: InitComposition): string {
3126
+ const vscode = composition.hosts.includes('vscode');
3127
+ const theiaApps = theiaApplicationPaths(composition);
3128
+ const intro = [
3129
+ 'A VS Code extension that starts the __NAME__ server and contributes no editor, view or command: the languages, their grammars and the server.',
3130
+ `With a socket head, it also answers each head’s port under a host command, which a host without a language client of its own runs${
3131
+ theiaApps.length > 0
3132
+ ? theiaApps.length === 1
3133
+ ? `: the Theia application in ${theiaApps[0]}, which sideloads this extension.`
3134
+ : `: the Theia applications in ${listPhrase(theiaApps)}, which sideload this extension.`
3135
+ : ', such as a Theia app sideloading this extension.'
3136
+ }`,
3137
+ ...(vscode
3138
+ ? [
3139
+ 'The VS Code extension in `../host-vscode` starts the server through the same function.',
3140
+ 'Both work side by side, but each starts its own server and language client, so diagnostics may show twice: install one.'
3141
+ ]
3142
+ : [])
3143
+ ];
3144
+ const lines = [
3145
+ `# ${memberPackageName(composition, 'vscode-servers')}`,
3146
+ '',
3147
+ ...wrapProse(intro.join(' ')),
3148
+ '',
3149
+ '```bash',
3150
+ 'npm run build # copy the server’s grammars and compile into out/; build the server first',
3151
+ 'npm run watch # the same on every change',
3152
+ '```',
3153
+ '',
3154
+ '- `src/extension.ts` — activation, which starts the server and, with a socket head, registers its port commands',
3155
+ `- \`src/language-client.ts\` — the server launch${vscode ? ', shared with `../host-vscode`' : ''}`,
3156
+ ''
3157
+ ];
3158
+ return project(lines.join('\n'), composition);
3159
+ }
3160
+
3161
+ /** The servers-only extension: the server's launch, without an editor. */
3162
+ function vscodeServersFiles(composition: InitComposition): InitFile[] {
3163
+ return [
3164
+ { path: 'vscode-servers/package.json', content: vscodeServersPackageJson(composition) },
3165
+ ignoreFile('vscode-servers'),
3166
+ { path: 'vscode-servers/README.md', content: vscodeServersReadme(composition) },
3167
+ projectTemplate('vscode-servers/tsconfig.json', composition),
3168
+ { path: 'vscode-servers/src/extension.ts', content: vscodeServersExtensionFile(composition) },
3169
+ { path: 'vscode-servers/src/language-client.ts', content: vscodeLanguageClientFile(composition) }
3170
+ ];
3171
+ }
3172
+
3173
+ /**
3174
+ * The custom-editor view type of a grammar's diagram, as the editor module
3175
+ * declares it. VS Code keys custom editors by view type alone, across every
3176
+ * installed extension, so it carries the language id, which `init` qualifies
3177
+ * by the project wherever the grammar is named apart from it.
3178
+ */
3179
+ function diagramViewType(grammar: InitGrammarNames): string {
3180
+ return `${grammar.languageId}.diagram`;
3181
+ }
3182
+
3183
+ /**
3184
+ * The VS Code extension's `package.json`. Always private, as every host is.
3185
+ *
3186
+ * A diagram file opens in its diagram by default; `Reopen Editor With` reaches
3187
+ * the text.
3188
+ */
3189
+ function hostVscodePackageJson(composition: InitComposition): string {
3190
+ const diagrams = composition.grammars.filter(grammar => grammar.diagram);
3191
+ const dependencies: Record<string, string> = {
3192
+ [memberPackageName(composition, 'vscode-servers')]: MEMBER_PIN,
3193
+ ...VSCODE_LANGUAGE_CLIENT
3194
+ };
3195
+ if (diagrams.length > 0) {
3196
+ dependencies[memberPackageName(composition, 'client')] = MEMBER_PIN;
3197
+ dependencies[memberPackageName(composition, 'protocol')] = MEMBER_PIN;
3198
+ Object.assign(dependencies, HOST_VSCODE_GLSP_THIRD_PARTY_DEPENDENCIES);
3199
+ for (const framework of HOST_VSCODE_GLSP_FRAMEWORK_DEPENDENCIES) {
3200
+ dependencies[framework] = frameworkPin(composition);
3201
+ }
3202
+ }
3203
+ if (composition.heads.includes('data')) {
3204
+ dependencies[memberPackageName(composition, 'protocol')] = MEMBER_PIN;
3205
+ Object.assign(dependencies, HOST_VSCODE_DATA_THIRD_PARTY_DEPENDENCIES);
3206
+ for (const framework of HOST_VSCODE_DATA_FRAMEWORK_DEPENDENCIES) {
3207
+ dependencies[framework] = frameworkPin(composition);
3208
+ }
3209
+ }
3210
+ const devDependencies = { ...HOST_VSCODE_DEV_DEPENDENCIES, ...(diagrams.length > 0 ? { esbuild: '^0.28.0' } : {}) };
3211
+ const watches: Record<string, string> = {
3212
+ syntaxes: 'npm run watch:syntaxes',
3213
+ tsc: 'tsc --watch',
3214
+ ...(diagrams.length > 0 ? { webview: 'node esbuild.mjs --watch' } : {})
3215
+ };
3216
+ const watchNames = Object.keys(watches).join(',');
3217
+ const watchCommands = Object.values(watches)
3218
+ .map(command => `\\"${command}\\"`)
3219
+ .join(' ');
3220
+ const contributes = {
3221
+ ...(composition.heads.includes('data')
3222
+ ? { commands: [{ command: `${composition.projectId}.showModel`, title: 'Show Model', category: composition.name }] }
3223
+ : {}),
3224
+ ...(diagrams.length > 0
3225
+ ? {
3226
+ customEditors: diagrams.map(grammar => ({
3227
+ viewType: diagramViewType(grammar),
3228
+ displayName: `${grammar.grammar} Diagram`,
3229
+ selector: grammar.extensions.map(extension => ({ filenamePattern: `*.${extension}` })),
3230
+ priority: 'default'
3231
+ }))
3232
+ }
3233
+ : {}),
3234
+ ...vscodeLanguageContributions(composition)
3235
+ };
3236
+ const typecheck = [...(diagrams.length > 0 ? ['tsconfig.webview.json'] : []), 'tsconfig.e2e.json']
3237
+ .map(project => `tsc --noEmit -p ${project}`)
3238
+ .join(' && ');
3239
+ return `{
3240
+ "name": "${memberPackageName(composition, 'host-vscode')}",
3241
+ "displayName": "${composition.name}",
3242
+ "version": "0.0.0",
3243
+ "private": true,
3244
+ "description": "${composition.name} in VS Code: ${hostVscodeParts(composition)}.",
3245
+ "license": "UNLICENSED",
3246
+ "author": "",
3247
+ "publisher": "${composition.projectId}",
3248
+ "main": "./out/extension.js",
3249
+ "scripts": {
3250
+ "build": "npm run copy:syntaxes && npm run typecheck && tsc${diagrams.length > 0 ? ' && node esbuild.mjs' : ''}",
3251
+ "clean": "rimraf out syntaxes tsconfig.tsbuildinfo test-results playwright-report",
3252
+ "copy:syntaxes": "${COPY_SYNTAXES}",
3253
+ ${lintScript(forMember(composition, 'host-vscode'), 'src test')} "start": "node start.mjs",
3254
+ "test:e2e": "playwright test --tsconfig tsconfig.e2e.json",
3255
+ "test:e2e:install": "node --experimental-strip-types test/install-vscode.mts",
3256
+ "typecheck": "${typecheck}",
3257
+ "watch": "concurrently --kill-others --names ${watchNames} ${watchCommands}",
3258
+ "watch:syntaxes": "${WATCH_SYNTAXES}"
3259
+ },
3260
+ "dependencies": {
3261
+ ${sortedBlock(dependencies, ' ')}
3262
+ },
3263
+ "devDependencies": {
3264
+ ${sortedBlock(devDependencies, ' ')}
3265
+ },
3266
+ "contributes": ${jsonAt(contributes, ' ')},
3267
+ "activationEvents": ${jsonAt(
3268
+ composition.grammars.map(grammar => `onLanguage:${grammar.languageId}`),
3269
+ ' '
3270
+ )},
3271
+ "engines": {
3272
+ "vscode": "${VSCODE_ENGINE}"
3273
+ }
3274
+ }
3275
+ `;
3276
+ }
3277
+
3278
+ /** What the VS Code extension brings, as one phrase; `started` follows the language client. */
3279
+ function hostVscodeParts(composition: InitComposition, started = ''): string {
3280
+ const parts = [
3281
+ `the language client${started}`,
3282
+ ...(composition.heads.includes('data') ? ['a Show Model command reading a file through the data head'] : []),
3283
+ ...(composition.grammars.some(grammar => grammar.diagram) ? ['a custom editor for each diagram'] : [])
3284
+ ];
3285
+ return listPhrase(parts);
3286
+ }
3287
+
3288
+ /** `parts` as one English list: `a`, `a and b`, `a, b, and c`. */
3289
+ function listPhrase(parts: readonly string[]): string {
3290
+ return parts.length === 1 ? parts[0] : `${parts.slice(0, -1).join(', ')}${parts.length > 2 ? ',' : ''} and ${parts.at(-1)}`;
3291
+ }
3292
+
3293
+ /**
3294
+ * The VS Code extension's entry: the shared server launch, then the Show Model
3295
+ * command over the data head and a diagram editor per diagram grammar.
3296
+ */
3297
+ function hostVscodeExtensionFile(composition: InitComposition): string {
3298
+ const columns = columnsFor(composition);
3299
+ const diagrams = composition.grammars.filter(grammar => grammar.diagram);
3300
+ const data = composition.heads.includes('data');
3301
+ const start = `start${composition.name}LanguageClient`;
3302
+ const servers = `${memberPackageName(composition, 'vscode-servers')}/out/language-client.js`;
3303
+ const upper = screamingSnake(composition.projectId);
3304
+ const editors = diagrams.map(grammar => ({
3305
+ module: `./${grammar.grammarId}-diagram-editor.js`,
3306
+ viewType: `${screamingSnake(grammar.grammarId)}_DIAGRAM_VIEW_TYPE`,
3307
+ provider: `${grammar.grammar}DiagramEditorProvider`,
3308
+ local: `${grammar.grammar.charAt(0).toLowerCase()}${grammar.grammar.slice(1)}Editor`
3309
+ }));
3310
+ const registrations = editors.map(
3311
+ editor => ` const ${editor.local} = new ${editor.provider}(glspConnector, context.extensionUri);
3312
+ context.subscriptions.push(
3313
+ window.registerCustomEditorProvider(${editor.viewType}, ${editor.local}, {
3314
+ // A hidden tab keeps its diagram session rather than repeating the handshake.
3315
+ webviewOptions: { retainContextWhenHidden: true },
3316
+ // Two views of one document would be two GLSP clients racing on one model.
3317
+ supportsMultipleEditorsPerDocument: false
3318
+ })
3319
+ );`
3320
+ );
3321
+ const sockets = data || diagrams.length > 0;
3322
+ const protocolSymbols = [
3323
+ ...(data ? [`${upper}_DATA_SERVER_PORT_COMMAND`] : []),
3324
+ ...(diagrams.length > 0 ? [`${upper}_GLSP_SERVER_PORT_COMMAND`] : []),
3325
+ ...(data ? [`type ${composition.name}Element`] : [])
3326
+ ];
3327
+ const imports = [
3328
+ ...(sockets ? ["import { findPort } from '@hydranium/client-vscode/node';"] : []),
3329
+ ...(data ? ["import { SocketDataPort } from '@hydranium/data-client-vscode/node';"] : []),
3330
+ ...(diagrams.length > 0
3331
+ ? ["import { HydraniumGlspVscodeConnector, HydraniumGlspVscodeServer } from '@hydranium/glsp-client-vscode/node';"]
3332
+ : []),
3333
+ ...(sockets
3334
+ ? [
3335
+ importList(
3336
+ [
3337
+ 'ConsoleLogger',
3338
+ ...(data ? ['DataConnectionWithEvents'] : []),
3339
+ ...(diagrams.length > 0 ? ['describeError'] : []),
3340
+ ...(data ? ['renderFrameworkMessage'] : [])
3341
+ ],
3342
+ '@hydranium/protocol',
3343
+ columns
3344
+ )
3345
+ ]
3346
+ : []),
3347
+ ...(sockets ? [importList(protocolSymbols, memberPackageName(composition, 'protocol'), columns)] : []),
3348
+ ...(sockets
3349
+ ? [`import { ${[...(data ? ['commands'] : []), 'type ExtensionContext', 'window'].join(', ')} } from 'vscode';`]
3350
+ : ["import type { ExtensionContext } from 'vscode';"]),
3351
+ "import type { LanguageClient } from 'vscode-languageclient/node';",
3352
+ `import { ${start} } from '${servers}';`,
3353
+ ...editors.map(editor => importList([editor.viewType, editor.provider], editor.module, columns)),
3354
+ ...(data ? ["import { showModelCommand } from './show-model-command.js';"] : [])
3355
+ ];
3356
+ const dataBlock = data
3357
+ ? `
3358
+
3359
+ // The data head, read by the Show Model command. Nothing connects until it runs.
3360
+ const dataPort = new SocketDataPort({
3361
+ findPort: () => findPort(running, ${upper}_DATA_SERVER_PORT_COMMAND),
3362
+ logger: new ConsoleLogger().with('data head'),
3363
+ // A failed read shown to the user, not only logged; the message carries the detail.
3364
+ reportError: (_error, reported) => void window.showErrorMessage(renderFrameworkMessage(reported))
3365
+ });
3366
+ const dataConnection = new DataConnectionWithEvents<${composition.name}Element>(dataPort);
3367
+ context.subscriptions.push(dataConnection, dataPort, commands.registerCommand('${composition.projectId}.showModel', showModelCommand(dataConnection)));`
3368
+ : '';
3369
+ const glspBlock =
3370
+ diagrams.length > 0
3371
+ ? `
3372
+
3373
+ // The GLSP head, and the connector bridging it to every diagram webview. No
3374
+ // \`messenger\` option: the connector's own keeps messages flowing to a hidden tab.
3375
+ const glspServer = new HydraniumGlspVscodeServer({
3376
+ clientId: '${composition.projectId}-glsp',
3377
+ clientName: '${composition.name}',
3378
+ findPort: () => findPort(running, ${upper}_GLSP_SERVER_PORT_COMMAND),
3379
+ logger: new ConsoleLogger().with('GLSP head')
3380
+ });
3381
+ const glspConnector = new HydraniumGlspVscodeConnector({ server: glspServer, logging: false });
3382
+ context.subscriptions.push(glspServer, glspConnector);
3383
+ // Not awaited, so a session that opens no diagram does not wait on the port.
3384
+ // \`start()\` resolves either way; a failure is reported off \`onReady\`.
3385
+ void glspServer.start();
3386
+ void glspServer.onReady.catch((error: unknown) => {
3387
+ void window.showErrorMessage(\`${composition.name} diagram unavailable: \${describeError(error)}\`);
3388
+ });
3389
+ ${registrations.join('\n')}`
3390
+ : '';
3391
+ const opening = wrapComment(
3392
+ `The ${composition.name} VS Code extension: ${hostVscodeParts(composition, ', started the way the servers extension starts it')}.${sockets ? ' Node extension host only: the server is forked and its socket heads reached over TCP.' : ''}`
3393
+ );
3394
+ const activation = sockets
3395
+ ? ` const running = await ${start}(context);
3396
+ client = running;${dataBlock}${glspBlock}`
3397
+ : ` client = await ${start}(context);`;
3398
+ return `${opening}
3399
+
3400
+ ${imports.join('\n')}
3401
+
3402
+ let client: LanguageClient | undefined;
3403
+
3404
+ export async function activate(context: ExtensionContext): Promise<void> {
3405
+ ${activation}
3406
+ }
3407
+
3408
+ export async function deactivate(): Promise<void> {
3409
+ await client?.stop();
3410
+ client = undefined;
3411
+ }
3412
+ `;
3413
+ }
3414
+
3415
+ /** A smoke test's title: what it checks of each head the composition has. */
3416
+ function hostVscodeSmokeTitle(composition: InitComposition): string {
3417
+ return listPhrase([
3418
+ ...(composition.heads.includes('data') ? ['reads the model'] : []),
3419
+ ...(composition.grammars.some(grammar => grammar.diagram) ? ['draws the diagram'] : []),
3420
+ 'reports a broken reference'
3421
+ ]);
3422
+ }
3423
+
3424
+ /**
3425
+ * The smoke test: VS Code opens the starter workspace with the extension
3426
+ * loaded, Show Model names the model with the data head, each diagram file
3427
+ * draws, and the server reports a broken reference.
3428
+ */
3429
+ function hostVscodeSmokeSpec(composition: InitComposition): string {
3430
+ const diagram = composition.grammars.find(grammar => grammar.diagram);
3431
+ const file = `nodes.${(diagram ?? composition.grammars[0]).extensions[0]}`;
3432
+ const diagramSteps = diagram
3433
+ ? `
3434
+ // The diagram file opens in its diagram, which draws the two starter nodes.
3435
+ const webview = page.frameLocator('iframe.webview.ready').frameLocator('#active-frame');
3436
+ // In the editor's container: sprotty measures shapes in a hidden copy beside it.
3437
+ await expect(webview.locator('.hydranium-diagram-container .sprotty-node')).toHaveCount(2);
3438
+ // Then as text. The row is clicked, since Enter runs the best fuzzy match,
3439
+ // and its name ends in its keybinding, if it has one.
3440
+ await page.keyboard.press('ControlOrMeta+Shift+P');
3441
+ await page.locator('.quick-input-widget input').fill('>View: Reopen Editor with Text Editor');
3442
+ await page
3443
+ .locator('.quick-input-list')
3444
+ .getByRole('option', { name: /^View: Reopen Editor with Text Editor(,|$)/ })
3445
+ .click();
3446
+ `
3447
+ : '';
3448
+ const primary = diagram ?? composition.grammars[0];
3449
+ const showModelSteps = composition.heads.includes('data')
3450
+ ? ` // The data head reads the open file.
3451
+ await page.keyboard.press('ControlOrMeta+Shift+P');
3452
+ await page.locator('.quick-input-widget input').fill('>${composition.name}: Show Model');
3453
+ await page
3454
+ .locator('.quick-input-list')
3455
+ .getByRole('option', { name: /^${composition.name}: Show Model(,|$)/ })
3456
+ .click();
3457
+ await expect(page.locator('.notification-toast').filter({ hasText: '${file} holds a ${primary.entryRule}' })).toBeVisible();
3458
+ `
3459
+ : '';
3460
+ const opening = wrapComment(
3461
+ `VS Code opens a copy of the starter workspace with this extension loaded, ${listPhrase([
3462
+ ...(composition.heads.includes('data') ? ['the data head reads the file'] : []),
3463
+ ...(diagram ? ['the diagram file draws in its diagram editor'] : []),
3464
+ 'the server reports a reference that resolves to nothing'
3465
+ ])}.`
3466
+ );
3467
+ return `${opening}
3468
+
3469
+ import { _electron, expect, test, type ElectronApplication, type Page } from '@playwright/test';
3470
+ import { downloadAndUnzipVSCode } from '@vscode/test-electron';
3471
+ import { cpSync, mkdtempSync, rmSync } from 'node:fs';
3472
+ import { tmpdir } from 'node:os';
3473
+ import { join } from 'node:path';
3474
+ import { fileURLToPath } from 'node:url';
3475
+ import { VSCODE_CACHE, VSCODE_VERSION } from './vscode-version.mts';
3476
+
3477
+ const extensionRoot = fileURLToPath(new URL('..', import.meta.url));
3478
+
3479
+ test('${hostVscodeSmokeTitle(composition)}', async () => {
3480
+ // A copy, since the server writes its repairs to the folder it opens, and a
3481
+ // fresh profile, since a reused one restores the last run's editors.
3482
+ const scratch = mkdtempSync(join(tmpdir(), '${composition.projectId}-vscode-'));
3483
+ const workspace = join(scratch, 'workspace');
3484
+ cpSync(fileURLToPath(new URL('../../workspace', import.meta.url)), workspace, { recursive: true });
3485
+ let app: ElectronApplication | undefined;
3486
+ try {
3487
+ app = await _electron.launch({
3488
+ executablePath: await downloadAndUnzipVSCode({ version: VSCODE_VERSION, cachePath: VSCODE_CACHE }),
3489
+ args: [
3490
+ '--no-sandbox',
3491
+ '--disable-gpu-sandbox',
3492
+ '--disable-updates',
3493
+ '--skip-welcome',
3494
+ '--skip-release-notes',
3495
+ '--disable-workspace-trust',
3496
+ '--disable-extensions',
3497
+ \`--extensionDevelopmentPath=\${extensionRoot}\`,
3498
+ \`--user-data-dir=\${join(scratch, 'user-data')}\`,
3499
+ \`--extensions-dir=\${join(scratch, 'extensions')}\`,
3500
+ workspace
3501
+ ]
3502
+ });
3503
+ const page = await app.firstWindow();
3504
+ await expect(page.locator('.monaco-workbench')).toBeVisible();
3505
+ await quickOpen(page, '${file}');
3506
+ ${showModelSteps}${diagramSteps}
3507
+ const editor = page.locator('.monaco-editor .view-lines').first();
3508
+ await expect(editor).toContainText('node First');
3509
+ await editor.click();
3510
+ await page.keyboard.press('ControlOrMeta+End');
3511
+ // In one edit: typed key by key, the half-typed reference is reported on the way.
3512
+ await page.keyboard.insertText('\\nnode Broken -> Missing');
3513
+ await expect(page.locator('.monaco-editor .squiggly-error').first()).toBeVisible();
3514
+ } finally {
3515
+ await app?.close();
3516
+ rmSync(scratch, { recursive: true, force: true });
3517
+ }
3518
+ });
3519
+
3520
+ /** Open \`file\` through Quick Open, so it gets the editor a user would. */
3521
+ async function quickOpen(page: Page, file: string): Promise<void> {
3522
+ await page.keyboard.press('ControlOrMeta+P');
3523
+ const input = page.locator('.quick-input-widget input');
3524
+ await input.fill(file);
3525
+ await expect(page.locator('.quick-input-list .monaco-list-row').first()).toContainText(file);
3526
+ await input.press('Enter');
3527
+ await expect(page.locator('.quick-input-widget')).toBeHidden();
3528
+ }
3529
+ `;
3530
+ }
3531
+
3532
+ /**
3533
+ * `text` broken at spaces into lines of at most 80 columns, the width
3534
+ * `check:docs` holds Markdown to. A link or code span stays whole, and runs
3535
+ * long on a line of its own.
3536
+ */
3537
+ function wrapProse(text: string, width = 80): string[] {
3538
+ const lines: string[] = [];
3539
+ for (const piece of text.match(/!?\[[^\]]*\]\([^)]*\)\S*|`+[^`]*`+\S*|\S+/g) ?? []) {
3540
+ const last = lines.at(-1);
3541
+ if (last !== undefined && last.length + 1 + piece.length <= width) {
3542
+ lines[lines.length - 1] = `${last} ${piece}`;
3543
+ } else {
3544
+ lines.push(piece);
3545
+ }
3546
+ }
3547
+ return lines;
3548
+ }
3549
+
3550
+ /** `text` as a `//` comment of lines at most 80 columns wide. */
3551
+ function wrapComment(text: string): string {
3552
+ return wrapProse(text, 77)
3553
+ .map(line => `// ${line}`)
3554
+ .join('\n');
3555
+ }
3556
+
3557
+ /** The VS Code extension's README. */
3558
+ function hostVscodeReadme(composition: InitComposition): string {
3559
+ const diagrams = composition.grammars.filter(grammar => grammar.diagram);
3560
+ const data = composition.heads.includes('data');
3561
+ const intro = [
3562
+ diagrams.length > 0
3563
+ ? `${composition.name} in VS Code: the language client, and a custom editor drawing each diagram file.`
3564
+ : `${composition.name} in VS Code: the language client.`,
3565
+ 'The server is started by `../vscode-servers`, whose launch this extension calls, so the two never hand the server different documents.',
3566
+ socketHeads(composition).length > 0
3567
+ ? 'It needs a Node extension host: the server is forked, and its socket heads are reached over TCP.'
3568
+ : 'It needs a Node extension host, since the server is forked.'
3569
+ ];
3570
+ const dataNote = `\`${composition.name}: Show Model\`, in the Command Palette, reads the active file through the data head over a socket from the extension host, and names its root type. A webview reaches the data head too: see the Host in VS Code guide.`;
3571
+ const lines = [
3572
+ `# ${memberPackageName(composition, 'host-vscode')}`,
3573
+ '',
3574
+ ...wrapProse(intro.join(' ')),
3575
+ ...(data ? ['', ...wrapProse(dataNote)] : []),
3576
+ '',
3577
+ '```bash',
3578
+ `npm run build # copy the server’s grammars, type-check and compile${diagrams.length > 0 ? ', then bundle' : ''}`,
3579
+ `npm run watch # copy the grammars and recompile${diagrams.length > 0 ? ' and rebundle' : ''} on every change; Developer: Reload Window picks it up`,
3580
+ 'npm start # VS Code with this extension, on ../workspace; needs `code` on the PATH',
3581
+ 'npm run test:e2e:install # download the VS Code the smoke test drives, once',
3582
+ 'npm run test:e2e # the smoke test; under `xvfb-run -a` on Linux without a display',
3583
+ '```',
3584
+ '',
3585
+ '## Layout',
3586
+ '',
3587
+ `- \`src/extension.ts\` — activation: ${listPhrase([
3588
+ 'the server, through `../vscode-servers`',
3589
+ ...(data ? ['the Show Model command'] : []),
3590
+ ...(diagrams.length > 0 ? ['the diagram editors'] : [])
3591
+ ])}`,
3592
+ ...(data ? ['- `src/show-model-command.ts` — Show Model: the active file, read through the data head'] : []),
3593
+ ...diagrams.flatMap(grammar => [
3594
+ `- \`src/${grammar.grammarId}-diagram-editor.ts\` — the \`${grammar.grammar}\` diagram’s custom editor; its view type is the one \`package.json\` declares`,
3595
+ `- \`src/webview/${grammar.grammarId}-diagram.ts\` — the webview it loads, over the client package’s diagram`
3596
+ ]),
3597
+ ...(diagrams.length > 0
3598
+ ? ['- `src/webview/diagram.css` — the webview’s size and colours', '- `esbuild.mjs` — bundles each webview into `out/webview/`']
3599
+ : []),
3600
+ '- `start.mjs` — `npm start`: VS Code with this extension, on `../workspace`',
3601
+ '- `test/smoke.spec.mts` — VS Code opens the workspace, ' +
3602
+ (composition.heads.includes('data') ? 'Show Model names the model, ' : '') +
3603
+ (diagrams.length > 0 ? 'the diagram draws, ' : '') +
3604
+ 'and the server reports a broken reference',
3605
+ '- `test/vscode-version.mts` — the VS Code release the smoke test runs',
3606
+ ''
3607
+ ];
3608
+ return project(lines.join('\n'), composition);
3609
+ }
3610
+
3611
+ /** The VS Code extension: the language client and a diagram editor per diagram grammar. */
3612
+ function hostVscodeFiles(composition: InitComposition): InitFile[] {
3613
+ const fixed = (file: string): InitFile => projectTemplate(`host-vscode/${file}`, composition);
3614
+ const diagrams = composition.grammars.filter(grammar => grammar.diagram);
3615
+ return [
3616
+ { path: 'host-vscode/package.json', content: hostVscodePackageJson(composition) },
3617
+ ignoreFile('host-vscode'),
3618
+ { path: 'host-vscode/README.md', content: hostVscodeReadme(composition) },
3619
+ fixed('tsconfig.json'),
3620
+ fixed('tsconfig.e2e.json'),
3621
+ fixed('playwright.config.mts'),
3622
+ fixed('start.mjs'),
3623
+ { path: 'host-vscode/src/extension.ts', content: hostVscodeExtensionFile(composition) },
3624
+ ...(composition.heads.includes('data') ? [fixed('src/show-model-command.ts')] : []),
3625
+ ...(diagrams.length > 0 ? [fixed('tsconfig.webview.json'), fixed('esbuild.mjs'), fixed('src/webview/diagram.css')] : []),
3626
+ ...diagrams.flatMap(grammar => [
3627
+ grammarTemplate('host-vscode/src/__GRAMMAR_ID__-diagram-editor.ts', composition, grammar),
3628
+ grammarTemplate('host-vscode/src/webview/__GRAMMAR_ID__-diagram.ts', composition, grammar)
3629
+ ]),
3630
+ { path: 'host-vscode/test/smoke.spec.mts', content: hostVscodeSmokeSpec(composition) },
3631
+ fixed('test/vscode-version.mts'),
3632
+ fixed('test/install-vscode.mts')
3633
+ ];
3634
+ }
3635
+
3636
+ /**
3637
+ * The Theia release of every Theia member, the one the framework's own
3638
+ * Theia examples take, so a scaffold builds against what the repo tests: the
3639
+ * Theia community release. Exact, as Theia's members pin each other, so a
3640
+ * workspace root declares it too and GLSP's open Theia peer resolves to it.
3641
+ */
3642
+ const THEIA_VERSION = '1.74.3';
3643
+
3644
+ /**
3645
+ * What each head adds to the Theia extension; `base` is the connection hardening
3646
+ * and editor sync every one gets. With the third-party entries below, they name
3647
+ * the peers of the framework's Theia packages, so an installer that adds no peers
3648
+ * still finds them.
3649
+ */
3650
+ const THEIA_FRAMEWORK_DEPENDENCIES: Record<InitHead | 'base', readonly string[]> = {
3651
+ base: ['@hydranium/client-theia', '@hydranium/protocol'],
3652
+ lsp: [],
3653
+ data: ['@hydranium/data-client-theia'],
3654
+ glsp: ['@hydranium/glsp-client', '@hydranium/glsp-client-theia']
3655
+ };
3656
+ const THEIA_THIRD_PARTY_DEPENDENCIES: Record<InitHead | 'base', Readonly<Record<string, string>>> = {
3657
+ base: {
3658
+ '@theia/core': THEIA_VERSION,
3659
+ '@theia/editor': THEIA_VERSION,
3660
+ '@theia/filesystem': THEIA_VERSION,
3661
+ '@theia/output': THEIA_VERSION,
3662
+ inversify: '^6.1.3',
3663
+ 'vscode-jsonrpc': '9.0.0'
3664
+ },
3665
+ lsp: {},
3666
+ data: { '@theia/workspace': THEIA_VERSION },
3667
+ glsp: {
3668
+ '@eclipse-glsp/client': '2.8.0',
3669
+ '@eclipse-glsp/theia-integration': '2.8.0',
3670
+ '@theia/process': THEIA_VERSION,
3671
+ '@theia/workspace': THEIA_VERSION
3672
+ }
3673
+ };
3674
+
3675
+ /** The Theia extension's third-party pins for `heads`, for its manifest and a workspace root's. */
3676
+ function theiaThirdPartyDependencies(heads: readonly InitHead[]): Array<[string, string]> {
3677
+ return (['base', ...heads] as const).flatMap(head => Object.entries(THEIA_THIRD_PARTY_DEPENDENCIES[head]));
3678
+ }
3679
+
3680
+ /**
3681
+ * The Theia packages the application assembles: the workbench a user expects,
3682
+ * and `plugin-ext` with its VS Code API to sideload the servers extension.
3683
+ */
3684
+ const HOST_THEIA_BROWSER_DEPENDENCIES: readonly string[] = [
3685
+ '@theia/core',
3686
+ '@theia/editor',
3687
+ '@theia/filesystem',
3688
+ '@theia/markers',
3689
+ '@theia/messages',
3690
+ '@theia/monaco',
3691
+ '@theia/navigator',
3692
+ '@theia/output',
3693
+ '@theia/plugin-ext',
3694
+ '@theia/plugin-ext-vscode',
3695
+ '@theia/preferences',
3696
+ '@theia/process',
3697
+ '@theia/workspace'
3698
+ ];
3699
+
3700
+ /** The Theia tooling the application builds with. */
3701
+ const HOST_THEIA_BROWSER_DEV_DEPENDENCIES: readonly string[] = ['@theia/cli'];
3702
+
3703
+ /** Every Theia package the application declares, for a workspace root's pins. */
3704
+ function hostTheiaBrowserTheiaDependencies(): Array<[string, string]> {
3705
+ return [...HOST_THEIA_BROWSER_DEPENDENCIES, ...HOST_THEIA_BROWSER_DEV_DEPENDENCIES].map(name => [name, THEIA_VERSION]);
3706
+ }
3707
+
3708
+ /** The Electron application's Theia packages: the browser application's, and Theia's Electron integration. */
3709
+ const HOST_THEIA_ELECTRON_DEPENDENCIES: readonly string[] = [...HOST_THEIA_BROWSER_DEPENDENCIES, '@theia/electron'].sort();
3710
+
3711
+ /** The Electron release `@theia/electron` peers on, exactly. */
3712
+ const ELECTRON_VERSION = '42.11.16';
3713
+
3714
+ /** Every package the Electron application pins, for a workspace root's pins. */
3715
+ function hostTheiaElectronPins(): Array<[string, string]> {
3716
+ return [
3717
+ ...[...HOST_THEIA_ELECTRON_DEPENDENCIES, ...HOST_THEIA_BROWSER_DEV_DEPENDENCIES].map((name): [string, string] => [
3718
+ name,
3719
+ THEIA_VERSION
3720
+ ]),
3721
+ ['electron', ELECTRON_VERSION]
3722
+ ];
3723
+ }
3724
+
3725
+ /** The Theia extension's `theiaExtensions` entries: one per head it forwards, and one per diagram. */
3726
+ function theiaExtensionEntries(composition: InitComposition): Array<Record<string, string>> {
3727
+ const id = composition.projectId;
3728
+ return [
3729
+ {
3730
+ frontendPreload: `lib/browser/${id}-connection-preload-module`,
3731
+ frontend: `lib/browser/${id}-frontend-module`,
3732
+ backend: `lib/node/${id}-connection-backend-module`
3733
+ },
3734
+ ...(composition.heads.includes('data') ? [{ backend: `lib/node/${id}-data-backend-module` }] : []),
3735
+ ...(composition.heads.includes('glsp') ? [{ backend: `lib/node/${id}-glsp-backend-module` }] : []),
3736
+ ...composition.grammars
3737
+ .filter(grammar => grammar.diagram)
3738
+ .map(grammar => ({ frontend: `lib/browser/${grammar.grammarId}-diagram-frontend-module` }))
3739
+ ];
3740
+ }
3741
+
3742
+ /** The Theia extension's `package.json`. Private unless `--public`, as the client member is. */
3743
+ function theiaPackageJson(composition: InitComposition): string {
3744
+ const dependencies: Record<string, string> = {
3745
+ // The socket heads' host commands, and the data head's model type.
3746
+ ...(socketHeads(composition).length > 0 ? { [memberPackageName(composition, 'protocol')]: MEMBER_PIN } : {}),
3747
+ ...(composition.heads.includes('glsp') ? { [memberPackageName(composition, 'client')]: MEMBER_PIN } : {}),
3748
+ ...Object.fromEntries(theiaThirdPartyDependencies(composition.heads))
3749
+ };
3750
+ for (const head of ['base', ...composition.heads] as const) {
3751
+ for (const framework of THEIA_FRAMEWORK_DEPENDENCIES[head]) {
3752
+ dependencies[framework] = frameworkPin(composition);
3753
+ }
3754
+ }
3755
+ return `{
3756
+ "name": "${memberPackageName(composition, 'theia')}",
3757
+ "version": "0.0.0",
3758
+ ${composition.packaging.private ? ' "private": true,\n' : ''} "description": "The ${composition.name} Theia extension: ${theiaParts(composition)}.",
3759
+ "license": "UNLICENSED",
3760
+ "author": "",
3761
+ "files": [
3762
+ "lib",
3763
+ "src",
3764
+ "style"
3765
+ ],
3766
+ "scripts": {
3767
+ "build": "tsc",
3768
+ "clean": "rimraf lib tsconfig.tsbuildinfo",
3769
+ ${lintScript(forMember(composition, 'theia'), 'src')} "watch": "tsc --watch"
3770
+ },
3771
+ "dependencies": {
3772
+ ${sortedBlock(dependencies, ' ')}
3773
+ },
3774
+ "devDependencies": {
3775
+ ${sortedBlock({ '@types/node': '^22.0.0', rimraf: '^5.0.0', typescript: '^7.0.2' }, ' ')}
3776
+ },
3777
+ "engines": {
3778
+ "node": ">=22.13"
3779
+ },
3780
+ "theiaExtensions": ${jsonAt(theiaExtensionEntries(composition), ' ')}
3781
+ }
3782
+ `;
3783
+ }
3784
+
3785
+ /** What the Theia extension brings, as one phrase. */
3786
+ function theiaParts(composition: InitComposition): string {
3787
+ return listPhrase([
3788
+ 'reconnect hardening',
3789
+ ...(composition.heads.includes('data') ? ['a Show Model command reading a file through the data head'] : []),
3790
+ ...(composition.grammars.some(grammar => grammar.diagram) ? ['a diagram editor for each diagram'] : [])
3791
+ ]);
3792
+ }
3793
+
3794
+ /** The extension's one frontend module: the logger, the connection diagnostics and editor sync, and each head's client. */
3795
+ function theiaFrontendModuleFile(composition: InitComposition): string {
3796
+ const id = composition.projectId;
3797
+ const name = composition.name;
3798
+ const data = composition.heads.includes('data');
3799
+ const glsp = composition.heads.includes('glsp');
3800
+ const imports = [
3801
+ ...(glsp ? ["import { GLSPClientContribution } from '@eclipse-glsp/theia-integration';"] : []),
3802
+ "import { bindChannelLogger, bindConnectionDiagnostics, bindEditorDiskSync } from '@hydranium/client-theia/browser';",
3803
+ ...(data
3804
+ ? [
3805
+ "import { bindDataConnection } from '@hydranium/data-client-theia/browser';",
3806
+ "import { CommandContribution } from '@theia/core';"
3807
+ ]
3808
+ : []),
3809
+ "import { ContainerModule } from '@theia/core/shared/inversify';",
3810
+ ...(data
3811
+ ? [
3812
+ `import { ${name}DataConnection } from './${id}-data-connection.js';`,
3813
+ `import { ${name}DataPort } from './${id}-data-port.js';`
3814
+ ]
3815
+ : []),
3816
+ ...(glsp ? [`import { ${name}GlspClientContribution } from './${id}-glsp-client-contribution.js';`] : []),
3817
+ ...(data ? [`import { ${name}ShowModelCommand } from './${id}-show-model-command.js';`] : [])
3818
+ ];
3819
+ const dataBlock = data
3820
+ ? `
3821
+
3822
+ // The data head: one connection, opened when the command first runs.
3823
+ bind(${name}DataPort).toSelf().inSingletonScope();
3824
+ bindDataConnection(bind, isBound, ${name}DataConnection);
3825
+ bind(${name}ShowModelCommand).toSelf().inSingletonScope();
3826
+ bind(CommandContribution).toService(${name}ShowModelCommand);`
3827
+ : '';
3828
+ const glspBlock = glsp
3829
+ ? `
3830
+
3831
+ // One GLSP client for every diagram, so each diagram module skips binding its own.
3832
+ bind(${name}GlspClientContribution).toSelf().inSingletonScope();
3833
+ bind(GLSPClientContribution).toService(${name}GlspClientContribution);`
3834
+ : '';
3835
+ return `${wrapComment(
3836
+ `The ${name} Theia extension's frontend: ${listPhrase([
3837
+ 'the connection’s lifecycle in an Output channel',
3838
+ 'a warning when an outage outlasts the offline buffer',
3839
+ 'editor disk sync',
3840
+ ...(data ? ['the data head’s connection and the Show Model command'] : []),
3841
+ ...(glsp ? ['the GLSP client the diagrams share'] : [])
3842
+ ])}.`
3843
+ )}
3844
+
3845
+ ${imports.join('\n')}
3846
+
3847
+ export default new ContainerModule((bind, _unbind, isBound, rebind) => {
3848
+ bindChannelLogger(bind, { channelName: '${name} Connection' });
3849
+ bindConnectionDiagnostics(bind);
3850
+ // Keeps an editor from writing over a file a head saved while it held the same text unsaved.
3851
+ bindEditorDiskSync(bind, isBound, rebind);${dataBlock}${glspBlock}
3852
+ });
3853
+ `;
3854
+ }
3855
+
3856
+ /** The Theia extension's README. */
3857
+ function theiaReadme(composition: InitComposition): string {
3858
+ const id = composition.projectId;
3859
+ const data = composition.heads.includes('data');
3860
+ const glsp = composition.heads.includes('glsp');
3861
+ const diagrams = composition.grammars.filter(grammar => grammar.diagram);
3862
+ const theiaApps = theiaApplicationPaths(composition);
3863
+ const intro = [
3864
+ `The ${composition.name} Theia extension: ${theiaParts(composition)}.`,
3865
+ socketHeads(composition).length > 0
3866
+ ? 'The language client is not here: the application sideloads `../vscode-servers`, which starts the server and answers each socket head’s port under a host command, and the backend modules forward the page’s channels to those ports.'
3867
+ : 'The language client is not here: the application sideloads `../vscode-servers`, which starts the server.',
3868
+ theiaApps.length === 1 ? `The application in ${theiaApps[0]} runs it.` : `The applications in ${listPhrase(theiaApps)} run it.`
3869
+ ];
3870
+ const before = [...(socketHeads(composition).length > 0 ? ['protocol'] : []), ...(glsp ? ['client'] : [])];
3871
+ const lines = [
3872
+ `# ${memberPackageName(composition, 'theia')}`,
3873
+ '',
3874
+ ...wrapProse(intro.join(' ')),
3875
+ '',
3876
+ '```bash',
3877
+ 'npm run build # compile into lib/' +
3878
+ (before.length > 0 ? `; build the ${before.join(' and ')} package${before.length > 1 ? 's' : ''} first` : ''),
3879
+ '```',
3880
+ '',
3881
+ '## Layout',
3882
+ '',
3883
+ `- \`src/browser/${id}-connection-preload-module.ts\` and \`src/node/${id}-connection-backend-module.ts\` — reconnect hardening, sized by the application’s \`connectionBufferBytes\``,
3884
+ `- \`src/browser/${id}-frontend-module.ts\` — the frontend bindings`,
3885
+ ...(data
3886
+ ? [
3887
+ `- \`src/browser/${id}-data-port.ts\` and \`${id}-data-connection.ts\` — the data head’s connection`,
3888
+ `- \`src/browser/${id}-show-model-command.ts\` — \`${composition.name}: Show Model\`, reading the current file through the data head`,
3889
+ `- \`src/node/${id}-data-backend-module.ts\` — forwards the data channel to the data head’s port`
3890
+ ]
3891
+ : []),
3892
+ ...(glsp
3893
+ ? [
3894
+ `- \`src/common/${id}-glsp-contribution.ts\` — the id the GLSP client and its forwarder share`,
3895
+ `- \`src/browser/${id}-glsp-client-contribution.ts\` — the GLSP client every diagram shares`,
3896
+ `- \`src/node/${id}-glsp-backend-module.ts\` — forwards the GLSP channel to the GLSP head’s port`
3897
+ ]
3898
+ : []),
3899
+ ...diagrams.map(
3900
+ grammar =>
3901
+ `- \`src/browser/${grammar.grammarId}-diagram-frontend-module.ts\` — the \`${grammar.grammar}\` diagram editor, over the client package’s diagram`
3902
+ ),
3903
+ ...(diagrams.length > 0 ? ['- `style/diagram.css` — the diagrams’ colours, from the Theia theme'] : []),
3904
+ ''
3905
+ ];
3906
+ return project(lines.join('\n'), composition);
3907
+ }
3908
+
3909
+ /** The Theia extension: what a Theia application runs of the language, beside the sideloaded servers extension. */
3910
+ function theiaFiles(composition: InitComposition): InitFile[] {
3911
+ const fixed = (file: string): InitFile => ({
3912
+ path: project(`theia/${file}`, composition),
3913
+ content: project(template(`theia/${file}`), composition)
3914
+ });
3915
+ const id = composition.projectId;
3916
+ const data = composition.heads.includes('data');
3917
+ const glsp = composition.heads.includes('glsp');
3918
+ const diagrams = composition.grammars.filter(grammar => grammar.diagram);
3919
+ return [
3920
+ { path: 'theia/package.json', content: theiaPackageJson(composition) },
3921
+ ignoreFile('theia'),
3922
+ { path: 'theia/README.md', content: theiaReadme(composition) },
3923
+ fixed('tsconfig.json'),
3924
+ fixed('src/browser/__PROJECT_ID__-connection-preload-module.ts'),
3925
+ { path: `theia/src/browser/${id}-frontend-module.ts`, content: theiaFrontendModuleFile(composition) },
3926
+ fixed('src/node/__PROJECT_ID__-connection-backend-module.ts'),
3927
+ ...(data
3928
+ ? [
3929
+ fixed('src/browser/__PROJECT_ID__-data-port.ts'),
3930
+ fixed('src/browser/__PROJECT_ID__-data-connection.ts'),
3931
+ fixed('src/browser/__PROJECT_ID__-show-model-command.ts'),
3932
+ fixed('src/node/__PROJECT_ID__-data-backend-module.ts')
3933
+ ]
3934
+ : []),
3935
+ ...(glsp
3936
+ ? [
3937
+ fixed('src/common/__PROJECT_ID__-glsp-contribution.ts'),
3938
+ fixed('src/browser/__PROJECT_ID__-glsp-client-contribution.ts'),
3939
+ fixed('src/node/__PROJECT_ID__-glsp-backend-module.ts')
3940
+ ]
3941
+ : []),
3942
+ ...diagrams.map(grammar => grammarTemplate('theia/src/browser/__GRAMMAR_ID__-diagram-frontend-module.ts', composition, grammar)),
3943
+ ...(diagrams.length > 0 ? [fixed('style/diagram.css')] : [])
3944
+ ];
3945
+ }
3946
+
3947
+ /**
3948
+ * The Theia application's `package.json`. Always private, as every host is.
3949
+ *
3950
+ * Theia's default `frontendConnectionTimeout` of 0 ends the session on any
3951
+ * dropped socket, and the page reloads; a minute lets the reconnect hardening
3952
+ * resume it.
3953
+ */
3954
+ function hostTheiaBrowserPackageJson(composition: InitComposition): string {
3955
+ const dependencies: Record<string, string> = {
3956
+ [memberPackageName(composition, 'theia')]: MEMBER_PIN,
3957
+ ...Object.fromEntries(HOST_THEIA_BROWSER_DEPENDENCIES.map(name => [name, THEIA_VERSION]))
3958
+ };
3959
+ const devDependencies: Record<string, string> = {
3960
+ // Built before this application, whose start links it into plugins/.
3961
+ [memberPackageName(composition, 'vscode-servers')]: MEMBER_PIN,
3962
+ '@playwright/test': '^1.55.0',
3963
+ ...Object.fromEntries(HOST_THEIA_BROWSER_DEV_DEPENDENCIES.map(name => [name, THEIA_VERSION])),
3964
+ '@types/node': '^22.0.0',
3965
+ rimraf: '^5.0.0',
3966
+ typescript: '^7.0.2'
3967
+ };
3968
+ const theia = {
3969
+ target: 'browser',
3970
+ frontend: {
3971
+ config: {
3972
+ applicationName: composition.name,
3973
+ connectionBufferBytes: 102400,
3974
+ preferences: { 'security.workspace.trust.enabled': false }
3975
+ }
3976
+ },
3977
+ backend: { config: { connectionBufferBytes: 102400, frontendConnectionTimeout: 60000 } }
3978
+ };
3979
+ return `{
3980
+ "name": "${memberPackageName(composition, 'host-theia-browser')}",
3981
+ "version": "0.0.0",
3982
+ "private": true,
3983
+ "description": "${composition.name} in a Theia browser application: the Theia extension, and the servers extension sideloaded for the language client.",
3984
+ "license": "UNLICENSED",
3985
+ "author": "",
3986
+ "scripts": {
3987
+ "build": "theia build --mode development && npm run typecheck",
3988
+ "clean": "rimraf lib src-gen plugins gen-esbuild.browser.mjs gen-esbuild.node.mjs smoke-workspace test-results playwright-report",
3989
+ ${lintScript(forMember(composition, 'host-theia-browser'), 'test')} "start": "node start.mjs",
3990
+ "test:e2e": "playwright test --tsconfig tsconfig.e2e.json",
3991
+ "test:e2e:install": "playwright install chromium",
3992
+ "typecheck": "tsc --noEmit -p tsconfig.e2e.json",
3993
+ "watch": "theia build --watch --mode development"
3994
+ },
3995
+ "dependencies": {
3996
+ ${sortedBlock(dependencies, ' ')}
3997
+ },
3998
+ "devDependencies": {
3999
+ ${sortedBlock(devDependencies, ' ')}
4000
+ },
4001
+ "engines": {
4002
+ "node": ">=22.13"
4003
+ },
4004
+ "theia": ${jsonAt(theia, ' ')}
4005
+ }
4006
+ `;
4007
+ }
4008
+
4009
+ /**
4010
+ * The Theia smoke test: the application opens a copy of the starter
4011
+ * workspace, and each head answers. The steps are the same in both
4012
+ * applications; the browser one's page is Chromium on the server the
4013
+ * configuration starts, the Electron one's the window the test launches.
4014
+ */
4015
+ function theiaSmokeSpec(composition: InitComposition, target: 'browser' | 'electron'): string {
4016
+ const data = composition.heads.includes('data');
4017
+ const diagram = composition.grammars.find(grammar => grammar.diagram);
4018
+ const primary = diagram ?? composition.grammars[0];
4019
+ const file = `nodes.${primary.extensions[0]}`;
4020
+ const showModelSteps = data
4021
+ ? `
4022
+ // The data head reads the open file, with focus in the Explorer beside it.
4023
+ await page.locator('.theia-FileTree .theia-TreeNode', { hasText: '${file}' }).click();
4024
+ await expect(page.locator('.theia-FileTree:focus-within')).toHaveCount(1);
4025
+ await runCommand(page, '${composition.name}: Show Model');
4026
+ // \`first()\`: Theia lists a notification in its toast and in the notification centre.
4027
+ await expect(
4028
+ page.locator('.theia-notification-message').filter({ hasText: '${file} holds a ${primary.entryRule}' }).first()
4029
+ ).toBeVisible();
4030
+ `
4031
+ : '';
4032
+ const diagramSteps = diagram
4033
+ ? `
4034
+ // The diagram file opens in its diagram, which draws the two starter nodes.
4035
+ // In the editor's copy: sprotty measures shapes in a hidden one on the page.
4036
+ await expect(page.locator('.sprotty:not(.sprotty-hidden) .sprotty-node')).toHaveCount(2);
4037
+ `
4038
+ : '';
4039
+ const textSteps = diagram
4040
+ ? ` // Then as text, through the Explorer's Open With.
4041
+ await page.locator('.theia-FileTree .theia-TreeNode', { hasText: '${file}' }).click({ button: 'right' });
4042
+ await page.locator('.lm-Menu-item', { hasText: 'Open With...' }).click();
4043
+ await page.locator('.quick-input-list .monaco-list-row', { hasText: 'Text Editor' }).click();
4044
+ `
4045
+ : '';
4046
+ return `${wrapComment(
4047
+ `Theia opens a copy of the starter workspace with this application's extensions, ${listPhrase([
4048
+ ...(diagram ? ['the diagram file draws in its diagram editor'] : []),
4049
+ ...(data ? ['the data head reads the file'] : []),
4050
+ 'the server reports a reference that resolves to nothing'
4051
+ ])}.`
4052
+ )}
4053
+
4054
+ ${target === 'browser' ? "import { expect, test, type Page } from '@playwright/test';\n" : theiaElectronSmokeFixture(composition)}
4055
+ test('${listPhrase([...(diagram ? ['draws the diagram'] : []), ...(data ? ['reads the model'] : []), 'reports a broken reference'])}', async ({ page }) => {
4056
+ ${target === 'browser' ? " await page.goto('/');\n" : ''} // Up once the loading screen is gone; a key pressed before then is lost.
4057
+ await expect(page.locator('.theia-preload')).toHaveCount(0);
4058
+ await page.keyboard.press('ControlOrMeta+Shift+E');
4059
+ await expect(page.locator('.theia-FileTree .theia-TreeNode', { hasText: '${file}' })).toBeVisible();
4060
+ await quickOpen(page, '${file}');
4061
+ ${diagramSteps}${showModelSteps}
4062
+ ${textSteps} const editor = page.locator('.monaco-editor .view-lines').first();
4063
+ await expect(editor).toContainText('node First');
4064
+ await editor.click();
4065
+ await page.keyboard.press('ControlOrMeta+End');
4066
+ // In one edit: typed key by key, the half-typed reference is reported on the way.
4067
+ await page.keyboard.insertText('\\nnode Broken -> Missing');
4068
+ await expect(page.locator('.monaco-editor .squiggly-error').first()).toBeVisible();
4069
+ });
4070
+
4071
+ /** Open \`file\` through Quick Open, so it gets the editor a user would. */
4072
+ async function quickOpen(page: Page, file: string): Promise<void> {
4073
+ await page.keyboard.press('ControlOrMeta+P');
4074
+ const input = page.locator('.quick-input-widget input');
4075
+ await input.fill(file);
4076
+ await expect(page.locator('.quick-input-list .monaco-list-row').first()).toContainText(file);
4077
+ await input.press('Enter');
4078
+ await expect(page.locator('.quick-input-widget')).toBeHidden();
4079
+ }
4080
+ ${
4081
+ data
4082
+ ? `
4083
+ /** Run the command whose palette entry reads \`label\`, checked before Enter, since the match is fuzzy. */
4084
+ async function runCommand(page: Page, label: string): Promise<void> {
4085
+ await page.keyboard.press('F1');
4086
+ const input = page.locator('.quick-input-widget input');
4087
+ await input.fill(\`>\${label}\`);
4088
+ await expect(page.locator('.quick-input-list .monaco-list-row.focused')).toContainText(label);
4089
+ await input.press('Enter');
4090
+ await expect(page.locator('.quick-input-widget')).toBeHidden();
4091
+ }
4092
+ `
4093
+ : ''
4094
+ }`;
4095
+ }
4096
+
4097
+ /** The Theia application's README. */
4098
+ function hostTheiaBrowserReadme(composition: InitComposition): string {
4099
+ const intro = [
4100
+ `${composition.name} in a Theia browser application: the Theia extension in \`../theia\`, and \`../vscode-servers\` sideloaded through \`@theia/plugin-ext\`, which starts the server and its language client.`,
4101
+ 'The backend runs the server, so this is a Node application; Theia serves the page.',
4102
+ ...(composition.grammars.some(grammar => grammar.diagram)
4103
+ ? ['The servers extension contributes no editor, so a diagram file opens in the Theia diagram editor alone.']
4104
+ : [])
4105
+ ];
4106
+ const lines = [
4107
+ `# ${memberPackageName(composition, 'host-theia-browser')}`,
4108
+ '',
4109
+ ...wrapProse(intro.join(' ')),
4110
+ '',
4111
+ '```bash',
4112
+ 'npm run build # bundle and type-check; build the members first',
4113
+ 'npm run watch # rebundle whenever the members’ builds change; reload the page to pick it up',
4114
+ 'npm start # Theia at http://localhost:3000 on ../workspace; THEIA_PORT picks another port',
4115
+ 'npm run test:e2e:install # download the Chromium the smoke test drives, once',
4116
+ 'npm run test:e2e # the smoke test, which starts the application itself',
4117
+ '```',
4118
+ '',
4119
+ ...wrapProse(
4120
+ 'The `theia` block of `package.json` sets `frontendConnectionTimeout`, without which Theia ends the session on any dropped socket and the page reloads, and `connectionBufferBytes`, the messages kept while the socket is down; the Theia extension’s connection modules read both.'
4121
+ ),
4122
+ '',
4123
+ '## Layout',
4124
+ '',
4125
+ '- `esbuild.mjs` — the bundling `theia build` runs. It keeps this file, so it is the place to adjust the bundle',
4126
+ '- `start.mjs` — `npm start`: links `../vscode-servers` into `plugins/`, then starts the backend on `THEIA_PORT`, on a folder given as its argument or `../workspace`',
4127
+ '- `playwright.config.mts` — the smoke tier, on port 4938 or `THEIA_PORT`, on a copy of `../workspace` in `smoke-workspace/`',
4128
+ '- `test/smoke.spec.mts` — Theia opens the workspace and each head answers',
4129
+ ''
4130
+ ];
4131
+ return project(lines.join('\n'), composition);
4132
+ }
4133
+
4134
+ /** The Theia browser application: the Theia extension and the sideloaded servers extension. */
4135
+ function hostTheiaBrowserFiles(composition: InitComposition): InitFile[] {
4136
+ const fixed = (file: string): InitFile => projectTemplate(`host-theia-browser/${file}`, composition);
4137
+ return [
4138
+ { path: 'host-theia-browser/package.json', content: hostTheiaBrowserPackageJson(composition) },
4139
+ ignoreFile('host-theia-browser'),
4140
+ { path: 'host-theia-browser/README.md', content: hostTheiaBrowserReadme(composition) },
4141
+ fixed('esbuild.mjs'),
4142
+ fixed('start.mjs'),
4143
+ fixed('playwright.config.mts'),
4144
+ fixed('tsconfig.e2e.json'),
4145
+ { path: 'host-theia-browser/test/smoke.spec.mts', content: theiaSmokeSpec(composition, 'browser') }
4146
+ ];
4147
+ }
4148
+
4149
+ /**
4150
+ * The Electron smoke test's imports and its `page`: the application's window,
4151
+ * launched by the test on a scratch copy of the workspace.
4152
+ */
4153
+ function theiaElectronSmokeFixture(composition: InitComposition): string {
4154
+ return `import { expect, test as base, type ElectronApplication, type Page } from '@playwright/test';
4155
+ import { once } from 'node:events';
4156
+ import { cpSync, mkdirSync, mkdtempSync, rmSync, symlinkSync } from 'node:fs';
4157
+ import { tmpdir } from 'node:os';
4158
+ import { join } from 'node:path';
4159
+ import { fileURLToPath, pathToFileURL } from 'node:url';
4160
+
4161
+ /**
4162
+ * The application in Electron, on a copy of the starter workspace, since the
4163
+ * server writes its repairs to the folder it opens, with a profile of its own:
4164
+ * Theia quits at once while another window holds one. Its settings are its own
4165
+ * too, so a run never writes \`~/.theia/settings.json\`.
4166
+ */
4167
+ const test = base.extend<{ page: Page }>({
4168
+ page: async ({ playwright }, use) => {
4169
+ const scratch = mkdtempSync(join(tmpdir(), '${composition.projectId}-theia-electron-'));
4170
+ const workspace = join(scratch, 'workspace');
4171
+ // The servers extension, sideloaded from a plugins folder as \`npm start\` does.
4172
+ const plugins = join(scratch, 'plugins');
4173
+ const link = join(plugins, '${composition.projectId}-vscode-servers');
4174
+ let app: ElectronApplication | undefined;
4175
+ try {
4176
+ cpSync(fileURLToPath(new URL('../../workspace', import.meta.url)), workspace, { recursive: true });
4177
+ mkdirSync(plugins);
4178
+ symlinkSync(fileURLToPath(new URL('../../vscode-servers', import.meta.url)), link, 'junction');
4179
+ // Playwright resolves Electron itself; given its path, Theia opens this
4180
+ // folder instead of the workspace.
4181
+ app = await playwright._electron.launch({
4182
+ args: [
4183
+ fileURLToPath(new URL('..', import.meta.url)),
4184
+ '--no-sandbox',
4185
+ \`--user-data-dir=\${join(scratch, 'user-data')}\`,
4186
+ // In URI form, since Theia reads the argument as a URI.
4187
+ \`--plugins=local-dir:\${pathToFileURL(plugins).pathname}\`,
4188
+ workspace
4189
+ ],
4190
+ env: {
4191
+ ...process.env,
4192
+ THEIA_CONFIG_DIR: join(scratch, 'config'),
4193
+ // Menus drawn in the page, where the test can click them.
4194
+ THEIA_ELECTRON_DISABLE_NATIVE_ELEMENTS: '1'
4195
+ }
4196
+ });
4197
+ await use(await app.firstWindow());
4198
+ } finally {
4199
+ try {
4200
+ // Exited, not closed: closing asks whether to save the edited file. An
4201
+ // app that is already gone is left alone, so the test's own error stands.
4202
+ const child = app?.process();
4203
+ if (app && child?.exitCode === null && child.signalCode === null) {
4204
+ const exited = once(child, 'exit');
4205
+ await app.evaluate(({ app: electron }) => electron.exit(0));
4206
+ await exited;
4207
+ }
4208
+ } finally {
4209
+ // Unlinked first, so the remove never reaches \`../vscode-servers\` through it.
4210
+ rmSync(link, { force: true });
4211
+ rmSync(scratch, { recursive: true, force: true });
4212
+ }
4213
+ }
4214
+ }
4215
+ });
4216
+ `;
4217
+ }
4218
+
4219
+ /**
4220
+ * The Theia Electron application's `package.json`: the browser application's
4221
+ * `theia` block with the Electron target. Always private, as every host is.
4222
+ */
4223
+ function hostTheiaElectronPackageJson(composition: InitComposition): string {
4224
+ const dependencies: Record<string, string> = {
4225
+ [memberPackageName(composition, 'theia')]: MEMBER_PIN,
4226
+ ...Object.fromEntries(HOST_THEIA_ELECTRON_DEPENDENCIES.map(name => [name, THEIA_VERSION]))
4227
+ };
4228
+ const devDependencies: Record<string, string> = {
4229
+ // Built before this application, whose start links it into plugins/.
4230
+ [memberPackageName(composition, 'vscode-servers')]: MEMBER_PIN,
4231
+ '@playwright/test': '^1.55.0',
4232
+ ...Object.fromEntries(HOST_THEIA_BROWSER_DEV_DEPENDENCIES.map(name => [name, THEIA_VERSION])),
4233
+ '@types/node': '^22.0.0',
4234
+ electron: ELECTRON_VERSION,
4235
+ rimraf: '^5.0.0',
4236
+ typescript: '^7.0.2'
4237
+ };
4238
+ const theia = {
4239
+ target: 'electron',
4240
+ frontend: {
4241
+ config: {
4242
+ applicationName: composition.name,
4243
+ connectionBufferBytes: 102400,
4244
+ preferences: { 'security.workspace.trust.enabled': false }
4245
+ }
4246
+ },
4247
+ backend: { config: { connectionBufferBytes: 102400, frontendConnectionTimeout: 60000 } }
4248
+ };
4249
+ return `{
4250
+ "name": "${memberPackageName(composition, 'host-theia-electron')}",
4251
+ "version": "0.0.0",
4252
+ "private": true,
4253
+ "description": "${composition.name} in a Theia Electron application: the Theia extension, and the servers extension sideloaded for the language client.",
4254
+ "license": "UNLICENSED",
4255
+ "author": "",
4256
+ "main": "lib/backend/electron-main.js",
4257
+ "scripts": {
4258
+ "build": "theia build --mode development && npm run typecheck",
4259
+ "clean": "rimraf lib src-gen plugins gen-esbuild.browser.mjs gen-esbuild.electron.mjs gen-esbuild.node.mjs test-results playwright-report",
4260
+ ${lintScript(forMember(composition, 'host-theia-electron'), 'test')} "start": "node start.mjs",
4261
+ "test:e2e": "playwright test --tsconfig tsconfig.e2e.json",
4262
+ "typecheck": "tsc --noEmit -p tsconfig.e2e.json",
4263
+ "watch": "theia build --watch --mode development"
4264
+ },
4265
+ "dependencies": {
4266
+ ${sortedBlock(dependencies, ' ')}
4267
+ },
4268
+ "devDependencies": {
4269
+ ${sortedBlock(devDependencies, ' ')}
4270
+ },
4271
+ "engines": {
4272
+ "node": ">=22.13"
4273
+ },
4274
+ "theia": ${jsonAt(theia, ' ')}
4275
+ }
4276
+ `;
4277
+ }
4278
+
4279
+ /** The Theia Electron application's README. */
4280
+ function hostTheiaElectronReadme(composition: InitComposition): string {
4281
+ const intro = [
4282
+ `${composition.name} in a Theia Electron application: the Theia extension in \`../theia\`, and \`../vscode-servers\` sideloaded through \`@theia/plugin-ext\`, which starts the server and its language client.`,
4283
+ 'Electron runs the window, and a backend process it starts runs the server.',
4284
+ ...(composition.grammars.some(grammar => grammar.diagram)
4285
+ ? ['The servers extension contributes no editor, so a diagram file opens in the Theia diagram editor alone.']
4286
+ : [])
4287
+ ];
4288
+ const lines = [
4289
+ `# ${memberPackageName(composition, 'host-theia-electron')}`,
4290
+ '',
4291
+ ...wrapProse(intro.join(' ')),
4292
+ '',
4293
+ '```bash',
4294
+ 'npm run build # bundle and type-check, and download Electron; build the members first',
4295
+ 'npm run watch # rebundle whenever the members’ builds change; reload the window to pick it up',
4296
+ 'npm start # the application on ../workspace',
4297
+ 'npm run test:e2e # the smoke test, which launches the application itself',
4298
+ '```',
4299
+ '',
4300
+ ...wrapProse(
4301
+ 'There is no `theia rebuild:electron` step: Theia’s native modules are N-API builds, which load in Electron as `npm install` built them for Node.'
4302
+ ),
4303
+ '',
4304
+ ...wrapProse(
4305
+ '`npm run watch` reports a `theia-source-map-paths` JSON error as it starts: `esbuild.mjs` starts the browser and electron builds together, and they share `lib/frontend`. Later rebuilds are clean.'
4306
+ ),
4307
+ '',
4308
+ '## Layout',
4309
+ '',
4310
+ '- `esbuild.mjs` — the bundling `theia build` runs. It keeps this file, so it is the place to adjust the bundle',
4311
+ '- `start.mjs` — `npm start`: links `../vscode-servers` into `plugins/`, then starts the application on a folder given as its argument or `../workspace`',
4312
+ '- `playwright.config.mts` — the smoke tier',
4313
+ '- `test/smoke.spec.mts` — Electron opens a copy of the workspace with a profile of its own, and each head answers',
4314
+ ''
4315
+ ];
4316
+ return project(lines.join('\n'), composition);
4317
+ }
4318
+
4319
+ /** The Theia Electron application: the browser application's extensions in a desktop window. */
4320
+ function hostTheiaElectronFiles(composition: InitComposition): InitFile[] {
4321
+ const fixed = (file: string): InitFile => projectTemplate(`host-theia-electron/${file}`, composition);
4322
+ return [
4323
+ { path: 'host-theia-electron/package.json', content: hostTheiaElectronPackageJson(composition) },
4324
+ ignoreFile('host-theia-electron'),
4325
+ { path: 'host-theia-electron/README.md', content: hostTheiaElectronReadme(composition) },
4326
+ fixed('esbuild.mjs'),
4327
+ fixed('start.mjs'),
4328
+ fixed('playwright.config.mts'),
4329
+ fixed('tsconfig.e2e.json'),
4330
+ { path: 'host-theia-electron/test/smoke.spec.mts', content: theiaSmokeSpec(composition, 'electron') }
4331
+ ];
4332
+ }
4333
+
4334
+ /**
4335
+ * The formatter and linter a standalone root runs. Exact, because a formatter
4336
+ * release that changes its output would fail the project's `format:check`.
4337
+ */
4338
+ const ROOT_STYLE_DEV_DEPENDENCIES: Readonly<Record<string, string>> = { oxfmt: '0.71.0', oxlint: '1.82.0' };
4339
+
4340
+ /**
4341
+ * The standalone root's formatter config: the style every template is written
4342
+ * in, at the width the emitted sources wrap at. Generated code is ignored
4343
+ * because each run of its generator rewrites it in that generator's style.
4344
+ */
4345
+ function oxfmtConfig(composition: InitComposition): string {
4346
+ return `{
4347
+ "$schema": "./node_modules/oxfmt/configuration_schema.json",
4348
+ "arrowParens": "avoid",
4349
+ "endOfLine": "lf",
4350
+ "ignorePatterns": ["**/generated", "**/generated-hydranium", "**/syntaxes", "**/*.md"],
4351
+ "jsxSingleQuote": true,
4352
+ "printWidth": ${columnsFor(composition)},
4353
+ "singleQuote": true,
4354
+ "sortPackageJson": true,
4355
+ "tabWidth": 3,
4356
+ "trailingComma": "none",
4357
+ "overrides": [
4358
+ {
4359
+ "files": ["*.json", "*.yml", "*.yaml"],
4360
+ "options": {
4361
+ "printWidth": 100,
4362
+ "tabWidth": 2
4363
+ }
4364
+ }
4365
+ ]
4366
+ }
4367
+ `;
4368
+ }
4369
+
4370
+ /**
4371
+ * A standalone project's root: the members as npm workspaces.
4372
+ *
4373
+ * Always private: it is never published, whatever `--public` makes of the
4374
+ * members. npm runs a script across the members in the order listed here, not
4375
+ * by their dependencies; listing protocol first is safe because its `build`
4376
+ * runs the server's `generate` before compiling.
4377
+ *
4378
+ * It declares the exact pins `--monorepo` prints for a workspace root, for the
4379
+ * same reason: a package ranging over one, such as a framework package's peer,
4380
+ * otherwise takes the top of the tree with the newest match, and each member's
4381
+ * exact copy nests beneath it.
4382
+ *
4383
+ * `watch` keeps every non-host member built; `watch:<host>` adds one host, so
4384
+ * only the bundler of the host being worked on runs.
4385
+ *
4386
+ * `format` and `lint` run at the root over every member, which is why the
4387
+ * members get no `lint` of their own here.
4388
+ */
4389
+ function rootFiles(composition: InitComposition): InitFile[] {
4390
+ const devDependencies = {
4391
+ ...Object.fromEntries(workspaceRootPins(composition)),
4392
+ concurrently: '^9.0.0',
4393
+ ...ROOT_STYLE_DEV_DEPENDENCIES
4394
+ };
4395
+ const members = initMembers(composition.heads, composition.hosts);
4396
+ // Only the server's watch is `tsc -b`, so protocol is built by one process
4397
+ // rather than two writing the same `lib/`; a host's watch joins only in its
4398
+ // own `watch:<host>`.
4399
+ const watched = members.filter(member => member !== 'protocol' && !member.startsWith('host-'));
4400
+ const parallel = (commands: Readonly<Record<string, string>>): string =>
4401
+ `concurrently --kill-others --names ${Object.keys(commands).join(',')} ${Object.values(commands)
4402
+ .map(command => `\\"${command}\\"`)
4403
+ .join(' ')}`;
4404
+ const scripts: Record<string, string> = {
4405
+ build: 'npm run build --workspaces',
4406
+ clean: 'npm run clean --workspaces --if-present',
4407
+ format: 'oxfmt',
4408
+ 'format:check': 'oxfmt --check',
4409
+ lint: 'oxlint --report-unused-disable-directives --max-warnings 0',
4410
+ ...Object.fromEntries(composition.hosts.map(host => [`start:${host}`, `npm --prefix host-${host} start`])),
4411
+ test: 'npm test --workspaces --if-present',
4412
+ watch: parallel(Object.fromEntries(watched.map(member => [member, `npm --prefix ${member} run watch`]))),
4413
+ // The browser host's `start` is its watch: it rebundles the page as it serves it.
4414
+ ...Object.fromEntries(
4415
+ composition.hosts.map(host => [
4416
+ `watch:${host}`,
4417
+ parallel({
4418
+ watch: 'npm run watch',
4419
+ [`host-${host}`]: `npm --prefix host-${host} ${host === 'browser' ? 'start' : 'run watch'}`
4420
+ })
4421
+ ])
4422
+ )
4423
+ };
4424
+ const content = `{
4425
+ "name": "${composition.projectId}-root",
4426
+ "version": "0.0.0",
4427
+ "private": true,
4428
+ "workspaces": [
4429
+ ${members.map(member => ` "${member}"`).join(',\n')}
4430
+ ],
4431
+ "scripts": {
4432
+ ${Object.entries(scripts)
4433
+ .map(([name, command]) => ` "${name}": "${command}"`)
4434
+ .join(',\n')}
4435
+ },
4436
+ "devDependencies": {
4437
+ ${sortedBlock(devDependencies, ' ')}
4438
+ },
4439
+ "engines": {
4440
+ "node": ">=22.13"
4441
+ }
4442
+ }
4443
+ `;
4444
+ return [
4445
+ { path: 'package.json', content },
4446
+ ignoreFile(''),
4447
+ { path: '.editorconfig', content: template('editorconfig') },
4448
+ { path: '.oxfmtrc.json', content: oxfmtConfig(composition) },
4449
+ { path: '.oxlintrc.json', content: template('oxlintrc.json') },
4450
+ { path: '.nvmrc', content: `${SCAFFOLD_NODE_MAJOR}\n` }
4451
+ ];
4452
+ }
4453
+
4454
+ /**
4455
+ * Every file the scaffold emits, fully rendered, at its path in the project
4456
+ * directory. A workspace member's project gets no root of its own: it joins the
4457
+ * surrounding workspace, whose manifest `init` prints the changes for.
4458
+ */
4459
+ export function buildInitTemplates(composition: InitComposition): InitFile[] {
4460
+ return [
4461
+ ...(composition.packaging.workspace === undefined ? rootFiles(composition) : []),
4462
+ ...protocolFiles(composition),
4463
+ ...serverFiles(composition),
4464
+ ...(composition.heads.includes('glsp') ? clientFiles(composition) : []),
4465
+ ...(emitsVscodeServers(composition) ? vscodeServersFiles(composition) : []),
4466
+ ...(composition.hosts.some(isTheiaHost) ? theiaFiles(composition) : []),
4467
+ ...(composition.hosts.includes('browser') ? hostBrowserFiles(composition) : []),
4468
+ ...(composition.hosts.includes('vscode') ? hostVscodeFiles(composition) : []),
4469
+ ...(composition.hosts.includes('theia-browser') ? hostTheiaBrowserFiles(composition) : []),
4470
+ ...(composition.hosts.includes('theia-electron') ? hostTheiaElectronFiles(composition) : []),
4471
+ ...workspaceFiles(composition)
2070
4472
  ];
2071
4473
  }