@engenty/wizards-runtime 0.13.0 → 0.14.1

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 (313) hide show
  1. package/apps/runtime/dist/agents/architect.js +8 -7
  2. package/apps/runtime/dist/agents/goose-connections.js +82 -0
  3. package/apps/runtime/dist/agents/space-agent.js +9 -2
  4. package/apps/runtime/dist/agents/studio-assistant.js +101 -67
  5. package/apps/runtime/dist/agents/website.js +1 -1
  6. package/apps/runtime/dist/app.js +17 -1
  7. package/apps/runtime/dist/assistant/knows.js +6 -5
  8. package/apps/runtime/dist/authoring/guide.js +25 -5
  9. package/apps/runtime/dist/broker/account.js +166 -0
  10. package/apps/runtime/dist/broker/call.js +417 -0
  11. package/apps/runtime/dist/broker/caller.js +10 -0
  12. package/apps/runtime/dist/broker/grant.js +152 -0
  13. package/apps/runtime/dist/broker/host.js +51 -0
  14. package/apps/runtime/dist/broker/index.js +8 -0
  15. package/apps/runtime/dist/broker/kept.js +31 -0
  16. package/apps/runtime/dist/broker/log.js +240 -0
  17. package/apps/runtime/dist/broker/registry.js +9 -0
  18. package/apps/runtime/dist/broker/rwx.js +367 -0
  19. package/apps/runtime/dist/broker/send.js +189 -0
  20. package/apps/runtime/dist/connectors/builtin.js +1 -1
  21. package/apps/runtime/dist/connectors/external.js +38 -37
  22. package/apps/runtime/dist/connectors/index.js +30 -91
  23. package/apps/runtime/dist/connectors/mail.js +0 -8
  24. package/apps/runtime/dist/connectors/person-sign-ins.js +73 -0
  25. package/apps/runtime/dist/connectors/plugin-connections.js +65 -92
  26. package/apps/runtime/dist/connectors/smtp.js +1 -1
  27. package/apps/runtime/dist/connectors/space-connections.js +436 -0
  28. package/apps/runtime/dist/db/adopt.js +3 -3
  29. package/apps/runtime/dist/db/client.js +26 -0
  30. package/apps/runtime/dist/db/live-triggers.js +65 -23
  31. package/apps/runtime/dist/db/migrations/tenant/0027_work_chats.sql +52 -0
  32. package/apps/runtime/dist/db/migrations/tenant/0028_chat_approvals.sql +17 -0
  33. package/apps/runtime/dist/db/migrations/tenant/0029_work_chats_live.sql +49 -0
  34. package/apps/runtime/dist/db/migrations/tenant/{0027_space_skill.sql → 0030_space_skill.sql} +8 -8
  35. package/apps/runtime/dist/db/migrations/tenant/0031_space.sql +624 -0
  36. package/apps/runtime/dist/db/migrations/tenant/0032_rwx_rule.sql +18 -0
  37. package/apps/runtime/dist/db/migrations/tenant/0033_broker_log.sql +23 -0
  38. package/apps/runtime/dist/db/migrations/tenant/0034_space_connection.sql +35 -0
  39. package/apps/runtime/dist/db/migrations/tenant/0035_run_grant.sql +1 -0
  40. package/apps/runtime/dist/db/migrations/tenant/0036_approval_held_for.sql +1 -0
  41. package/apps/runtime/dist/db/migrations/tenant/0037_ways_out.sql +5 -0
  42. package/apps/runtime/dist/db/migrations/tenant/0038_heard.sql +11 -0
  43. package/apps/runtime/dist/db/migrations/tenant/0039_members_studio.sql +1 -0
  44. package/apps/runtime/dist/db/migrations/tenant/meta/0027_snapshot.json +383 -155
  45. package/apps/runtime/dist/db/migrations/tenant/meta/0028_snapshot.json +4468 -0
  46. package/apps/runtime/dist/db/migrations/tenant/meta/0029_snapshot.json +4475 -0
  47. package/apps/runtime/dist/db/migrations/tenant/meta/0030_snapshot.json +4629 -0
  48. package/apps/runtime/dist/db/migrations/tenant/meta/0031_snapshot.json +4629 -0
  49. package/apps/runtime/dist/db/migrations/tenant/meta/0032_snapshot.json +4757 -0
  50. package/apps/runtime/dist/db/migrations/tenant/meta/0033_snapshot.json +5039 -0
  51. package/apps/runtime/dist/db/migrations/tenant/meta/0034_snapshot.json +5022 -0
  52. package/apps/runtime/dist/db/migrations/tenant/meta/0035_snapshot.json +5029 -0
  53. package/apps/runtime/dist/db/migrations/tenant/meta/0036_snapshot.json +5037 -0
  54. package/apps/runtime/dist/db/migrations/tenant/meta/0037_snapshot.json +5076 -0
  55. package/apps/runtime/dist/db/migrations/tenant/meta/0038_snapshot.json +5145 -0
  56. package/apps/runtime/dist/db/migrations/tenant/meta/0039_snapshot.json +5153 -0
  57. package/apps/runtime/dist/db/migrations/tenant/meta/_journal.json +86 -2
  58. package/apps/runtime/dist/db/schema.js +295 -72
  59. package/apps/runtime/dist/docs/dev/architecture.md +215 -0
  60. package/apps/runtime/dist/docs/dev/broker.md +298 -0
  61. package/apps/runtime/dist/docs/dev/index.md +5 -1
  62. package/apps/runtime/dist/docs/dev/integration/index.md +2 -0
  63. package/apps/runtime/dist/docs/dev/meta.json +3 -0
  64. package/apps/runtime/dist/docs/dev/plugins/connections.md +8 -5
  65. package/apps/runtime/dist/docs/dev/plugins/events.md +1 -1
  66. package/apps/runtime/dist/docs/dev/plugins/examples.md +1 -0
  67. package/apps/runtime/dist/docs/dev/plugins/index.md +2 -2
  68. package/apps/runtime/dist/docs/dev/plugins/reference.md +3 -2
  69. package/apps/runtime/dist/docs/dev/plugins/space.md +16 -6
  70. package/apps/runtime/dist/docs/dev/plugins/studio.md +2 -2
  71. package/apps/runtime/dist/docs/dev/plugins/tools.md +0 -1
  72. package/apps/runtime/dist/docs/dev/skills.md +16 -9
  73. package/apps/runtime/dist/docs/dev/wizard-format/agent-steps.md +40 -5
  74. package/apps/runtime/dist/docs/dev/wizard-format/lists-and-connections.md +17 -2
  75. package/apps/runtime/dist/docs/dev/wizard-format/templates.md +2 -0
  76. package/apps/runtime/dist/docs/dev/wizard-format/views-and-widgets.md +22 -2
  77. package/apps/runtime/dist/docs/user-guide/capabilities.md +132 -0
  78. package/apps/runtime/dist/docs/user-guide/cloud-sync.md +2 -0
  79. package/apps/runtime/dist/docs/user-guide/command-line.md +1 -0
  80. package/apps/runtime/dist/docs/user-guide/connectors.md +63 -7
  81. package/apps/runtime/dist/docs/user-guide/index.md +10 -1
  82. package/apps/runtime/dist/docs/user-guide/meta.json +6 -1
  83. package/apps/runtime/dist/docs/user-guide/protocol.md +80 -0
  84. package/apps/runtime/dist/docs/user-guide/skills.md +8 -4
  85. package/apps/runtime/dist/docs/user-guide/space.md +5 -4
  86. package/apps/runtime/dist/docs/user-guide/together.md +16 -2
  87. package/apps/runtime/dist/docs/user-guide/troubleshooting.md +2 -2
  88. package/apps/runtime/dist/docs/user-guide/work-mode.md +128 -0
  89. package/apps/runtime/dist/engenty/connections-external/build-connector.js +2 -5
  90. package/apps/runtime/dist/engenty/connections-external/importer/classify.js +72 -0
  91. package/apps/runtime/dist/engenty/connections-google/connectors/gmail.js +1 -1
  92. package/apps/runtime/dist/engenty/connections-microsoft/outlook.js +3 -2
  93. package/apps/runtime/dist/engenty/connections-sdk/types.js +2 -0
  94. package/apps/runtime/dist/engenty/connections-slack/connector.js +2 -1
  95. package/apps/runtime/dist/engine/resources.js +43 -12
  96. package/apps/runtime/dist/engine/runner.js +75 -23
  97. package/apps/runtime/dist/engine/steps.js +30 -12
  98. package/apps/runtime/dist/engine/template.js +18 -1
  99. package/apps/runtime/dist/env.js +9 -4
  100. package/apps/runtime/dist/index.js +18 -2
  101. package/apps/runtime/dist/live/feed.js +2 -2
  102. package/apps/runtime/dist/live/origin.js +2 -2
  103. package/apps/runtime/dist/live/views.js +51 -26
  104. package/apps/runtime/dist/manage.js +7 -0
  105. package/apps/runtime/dist/mcp/flow-app.js +1 -1
  106. package/apps/runtime/dist/mcp/tools.js +75 -34
  107. package/apps/runtime/dist/models.js +1 -1
  108. package/apps/runtime/dist/motion-graphics/project.js +8 -8
  109. package/apps/runtime/dist/motion-graphics/tools.js +1 -1
  110. package/apps/runtime/dist/plugins/events.js +2 -2
  111. package/apps/runtime/dist/plugins/jobs.js +4 -1
  112. package/apps/runtime/dist/plugins/loader.js +2 -2
  113. package/apps/runtime/dist/prompts/architect.md +3 -3
  114. package/apps/runtime/dist/prompts/authoring.md +46 -12
  115. package/apps/runtime/dist/prompts/goose.md +7 -7
  116. package/apps/runtime/dist/prompts/mcp.md +6 -6
  117. package/apps/runtime/dist/prompts/services.md +4 -4
  118. package/apps/runtime/dist/prompts/step.md +2 -2
  119. package/apps/runtime/dist/prompts/tools.md +39 -10
  120. package/apps/runtime/dist/routes/api.js +31 -20
  121. package/apps/runtime/dist/routes/broker.js +316 -0
  122. package/apps/runtime/dist/routes/connections.js +71 -0
  123. package/apps/runtime/dist/routes/delivery.js +25 -0
  124. package/apps/runtime/dist/routes/discover.js +17 -0
  125. package/apps/runtime/dist/routes/live.js +11 -1
  126. package/apps/runtime/dist/routes/person.js +4 -1
  127. package/apps/runtime/dist/routes/plugins.js +3 -1
  128. package/apps/runtime/dist/routes/rules.js +26 -0
  129. package/apps/runtime/dist/routes/runs.js +54 -33
  130. package/apps/runtime/dist/routes/skills.js +6 -6
  131. package/apps/runtime/dist/routes/studio.js +153 -144
  132. package/apps/runtime/dist/routes/work.js +199 -0
  133. package/apps/runtime/dist/sandbox/index.js +27 -0
  134. package/apps/runtime/dist/services/access.js +38 -17
  135. package/apps/runtime/dist/services/api.js +38 -13
  136. package/apps/runtime/dist/services/architect.js +3 -3
  137. package/apps/runtime/dist/services/assistant-chats.js +9 -1
  138. package/apps/runtime/dist/services/brand.js +12 -12
  139. package/apps/runtime/dist/services/broker-bell.js +69 -0
  140. package/apps/runtime/dist/services/broker-notify.js +127 -0
  141. package/apps/runtime/dist/services/client-steps.js +79 -0
  142. package/apps/runtime/dist/services/cloud.js +42 -42
  143. package/apps/runtime/dist/services/command-risk.js +51 -0
  144. package/apps/runtime/dist/services/discover.js +85 -0
  145. package/apps/runtime/dist/services/knowledge-model.js +13 -13
  146. package/apps/runtime/dist/services/knowledge.js +117 -80
  147. package/apps/runtime/dist/services/manage-reports.js +74 -7
  148. package/apps/runtime/dist/services/members-studio.js +165 -0
  149. package/apps/runtime/dist/services/onboarding.js +22 -22
  150. package/apps/runtime/dist/services/package-file.js +1 -1
  151. package/apps/runtime/dist/services/package.js +22 -22
  152. package/apps/runtime/dist/services/pages.js +7 -7
  153. package/apps/runtime/dist/services/runs.js +4 -3
  154. package/apps/runtime/dist/services/seen.js +55 -0
  155. package/apps/runtime/dist/services/shares.js +23 -13
  156. package/apps/runtime/dist/services/site.js +23 -23
  157. package/apps/runtime/dist/services/skills-registry.js +15 -15
  158. package/apps/runtime/dist/services/skills.js +44 -44
  159. package/apps/runtime/dist/services/space-categories.js +35 -35
  160. package/apps/runtime/dist/services/space-data.js +130 -111
  161. package/apps/runtime/dist/services/{project-files.js → space-files.js} +84 -75
  162. package/apps/runtime/dist/services/{project-index.js → space-index.js} +116 -73
  163. package/apps/runtime/dist/services/space-origin.js +19 -11
  164. package/apps/runtime/dist/services/spaces.js +478 -612
  165. package/apps/runtime/dist/services/synced-spaces.js +668 -0
  166. package/apps/runtime/dist/services/themes.js +15 -15
  167. package/apps/runtime/dist/services/widgets.js +6 -6
  168. package/apps/runtime/dist/services/wizards.js +112 -38
  169. package/apps/runtime/dist/services/work-ai.js +257 -0
  170. package/apps/runtime/dist/services/work-approvals.js +104 -0
  171. package/apps/runtime/dist/services/work-chats.js +908 -0
  172. package/apps/runtime/dist/services/work-connections.js +90 -0
  173. package/apps/runtime/dist/services/work-files.js +85 -0
  174. package/apps/runtime/dist/services/work-mastra.js +73 -0
  175. package/apps/runtime/dist/services/work-sandbox.js +42 -0
  176. package/apps/runtime/dist/sharing/files.js +14 -4
  177. package/apps/runtime/dist/sharing/index.js +40 -39
  178. package/apps/runtime/dist/sharing/jobs.js +67 -17
  179. package/apps/runtime/dist/sharing/targets/connector.js +10 -6
  180. package/apps/runtime/dist/sharing/targets/email.js +10 -8
  181. package/apps/runtime/dist/sharing/targets/slack.js +10 -8
  182. package/apps/runtime/dist/sharing/targets/storage.js +6 -4
  183. package/apps/runtime/dist/store/index.js +14 -3
  184. package/apps/runtime/dist/store/shared-lists.js +4 -2
  185. package/apps/runtime/dist/sync/apply.js +2 -2
  186. package/apps/runtime/dist/sync/client.js +113 -113
  187. package/apps/runtime/dist/sync/hub.js +41 -41
  188. package/apps/runtime/dist/sync/log.js +12 -12
  189. package/apps/runtime/dist/sync/records.js +118 -120
  190. package/apps/runtime/dist/texts.js +38 -2
  191. package/apps/runtime/dist/tools/connections.js +112 -0
  192. package/apps/runtime/dist/tools/connector.js +157 -67
  193. package/apps/runtime/dist/tools/index.js +28 -13
  194. package/apps/runtime/dist/tools/mail.js +40 -11
  195. package/apps/runtime/dist/tools/pages.js +11 -5
  196. package/apps/runtime/dist/tools/plugin.js +43 -7
  197. package/apps/runtime/dist/tools/skills.js +1 -1
  198. package/apps/runtime/dist/tools/{project.js → space.js} +30 -25
  199. package/apps/runtime/dist/tools/store.js +3 -2
  200. package/apps/runtime/dist/widgets/step.js +10 -10
  201. package/apps/web/dist/assets/AboutDialog-SpDcn8VZ.js +1 -0
  202. package/apps/web/dist/assets/CapabilitiesPage-Bgnm_3dk.js +2 -0
  203. package/apps/web/dist/assets/{ChangelogDialog-SwyId00t.js → ChangelogDialog-DAnjV6cZ.js} +1 -1
  204. package/apps/web/dist/assets/{CodeEditor-BwZsk5Al.js → CodeEditor-nxoOt8ge.js} +1 -1
  205. package/apps/web/dist/assets/EditorPage-B98C-9Nv.js +3 -0
  206. package/apps/web/dist/assets/{FlowPreview-DtSpjVTl.js → FlowPreview-aMfwcPul.js} +1 -1
  207. package/apps/web/dist/assets/LangSwitch-DpD0inR4.js +1 -0
  208. package/apps/web/dist/assets/Marketplace-CpzD9pNQ.js +2 -0
  209. package/apps/web/dist/assets/NewWizardChannels-D8IYLg_S.js +1 -0
  210. package/apps/web/dist/assets/NewWizardPage-DlBt0Mfq.js +7 -0
  211. package/apps/web/dist/assets/OnboardingPage-ztHT01ah.js +1 -0
  212. package/apps/web/dist/assets/PreviewPane-DC1kAi3x.js +9 -0
  213. package/apps/web/dist/assets/PublicRunner-D6lKP0j8.js +1 -0
  214. package/apps/web/dist/assets/ReadOnly-DFsuKPCw.js +1 -0
  215. package/apps/web/dist/assets/SettingsPage-DkHeCO2c.js +2 -0
  216. package/apps/web/dist/assets/SetupPage-DZ8xRkfS.js +1 -0
  217. package/apps/web/dist/assets/SharePage-494ZPsjQ.js +1 -0
  218. package/apps/web/dist/assets/SkillEditor-CqQMg2MC.js +1 -0
  219. package/apps/web/dist/assets/Skills-CnhpgoOA.js +9 -0
  220. package/apps/web/dist/assets/SpacePage-CWlU_BZP.js +2 -0
  221. package/apps/web/dist/assets/UpdateCheck-BKNkNJyG.js +2 -0
  222. package/apps/web/dist/assets/changelog-BhMZS-rs.js +1 -0
  223. package/apps/web/dist/assets/circle-alert-C8Ma-bPY.js +1 -0
  224. package/apps/web/dist/assets/circle-check-Bu9Z3mlJ.js +1 -0
  225. package/apps/web/dist/assets/code-editor-CfTGqOpp.js +2 -0
  226. package/apps/web/dist/assets/{code-xml-TwKzzMtA.js → code-xml-B4kLFZSj.js} +1 -1
  227. package/apps/web/dist/assets/connection-sign-in-Cngd_QDO.js +1 -0
  228. package/apps/web/dist/assets/esm-Xwn4GtqG.js +7 -0
  229. package/apps/web/dist/assets/{eye-Brd-xPUJ.js → eye-BpoKpIdt.js} +1 -1
  230. package/apps/web/dist/assets/host-BrP-ENHg.css +1 -0
  231. package/apps/web/dist/assets/host-C0WQlRKB.js +118 -0
  232. package/apps/web/dist/assets/i18n-BJ7Ld6O6.js +55 -0
  233. package/apps/web/dist/assets/index-ClVtdDUZ.js +10 -0
  234. package/apps/web/dist/assets/index-D18DvnxX.css +1 -0
  235. package/apps/web/dist/assets/logo-BpnjXTRy.js +1 -0
  236. package/apps/web/dist/assets/oss-credits-IdX5bc71.js +1 -0
  237. package/apps/web/dist/assets/{phone-DhkHteoJ.js → phone-Ctvf-Am-.js} +1 -1
  238. package/apps/web/dist/assets/read-aloud-Da_RSm2S.js +1 -0
  239. package/apps/web/dist/assets/{runners-G-XYaDgR.js → runners-CyIvJIHr.js} +1 -1
  240. package/apps/web/dist/assets/scroll-text-ChrjRu9Y.js +1 -0
  241. package/apps/web/dist/assets/session-SXPtTWRK.js +2 -0
  242. package/apps/web/dist/assets/theme-BCau3f6O.js +11 -0
  243. package/apps/web/dist/assets/ui-Uqnx1UpK.js +82 -0
  244. package/apps/web/dist/assets/{upload-BYZTwJTD.js → upload-BchUnQGV.js} +1 -1
  245. package/apps/web/dist/assets/{useMutation-D0QP_k2-.js → useMutation-DEkZhp5c.js} +1 -1
  246. package/apps/web/dist/assets/{volume-2-CVHoxdGM.js → volume-2-CU_oy81Z.js} +1 -1
  247. package/apps/web/dist/assets/with-selector-CoMyWBAX.js +1 -0
  248. package/apps/web/dist/index.html +17 -10
  249. package/apps/web/dist/mcp/flow.html +119 -64
  250. package/node_modules/@engenty/wizards/dist/plugin/index.d.ts +20 -10
  251. package/node_modules/@engenty/wizards-shared/dist/assistant.d.ts +6 -1
  252. package/node_modules/@engenty/wizards-shared/dist/assistant.js +6 -1
  253. package/node_modules/@engenty/wizards-shared/dist/connectors.d.ts +236 -2
  254. package/node_modules/@engenty/wizards-shared/dist/connectors.js +52 -2
  255. package/node_modules/@engenty/wizards-shared/dist/definition.d.ts +150 -8
  256. package/node_modules/@engenty/wizards-shared/dist/definition.js +46 -11
  257. package/node_modules/@engenty/wizards-shared/dist/discover.d.ts +21 -0
  258. package/node_modules/@engenty/wizards-shared/dist/discover.js +1 -0
  259. package/node_modules/@engenty/wizards-shared/dist/feature-flags.d.ts +26 -2
  260. package/node_modules/@engenty/wizards-shared/dist/feature-flags.js +26 -2
  261. package/node_modules/@engenty/wizards-shared/dist/fit.js +1 -1
  262. package/node_modules/@engenty/wizards-shared/dist/json-schema.d.ts +1 -1
  263. package/node_modules/@engenty/wizards-shared/dist/json-schema.js +1 -1
  264. package/node_modules/@engenty/wizards-shared/dist/live.d.ts +2 -2
  265. package/node_modules/@engenty/wizards-shared/dist/live.js +1 -1
  266. package/node_modules/@engenty/wizards-shared/dist/marketplace.js +3 -1
  267. package/node_modules/@engenty/wizards-shared/dist/run.d.ts +54 -6
  268. package/node_modules/@engenty/wizards-shared/dist/run.js +85 -0
  269. package/node_modules/@engenty/wizards-shared/dist/runner-texts.d.ts +15 -1
  270. package/node_modules/@engenty/wizards-shared/dist/runner-texts.js +14 -0
  271. package/node_modules/@engenty/wizards-shared/dist/rwx.d.ts +42 -0
  272. package/node_modules/@engenty/wizards-shared/dist/rwx.js +29 -0
  273. package/node_modules/@engenty/wizards-shared/dist/skills.d.ts +1 -1
  274. package/node_modules/@engenty/wizards-shared/dist/space-data.d.ts +2 -2
  275. package/node_modules/@engenty/wizards-shared/dist/{projects.d.ts → spaces.d.ts} +39 -15
  276. package/node_modules/@engenty/wizards-shared/dist/{projects.js → spaces.js} +16 -9
  277. package/node_modules/@engenty/wizards-shared/dist/store.d.ts +7 -2
  278. package/node_modules/@engenty/wizards-shared/dist/surface.d.ts +35 -4
  279. package/node_modules/@engenty/wizards-shared/dist/surface.js +121 -3
  280. package/node_modules/@engenty/wizards-shared/dist/sync.d.ts +1 -1
  281. package/node_modules/@engenty/wizards-shared/dist/theme-look.js +1 -1
  282. package/node_modules/@engenty/wizards-shared/dist/wizard-package.d.ts +2 -2
  283. package/node_modules/@engenty/wizards-shared/dist/wizard-package.js +3 -3
  284. package/package.json +4 -1
  285. package/plugin/.claude-plugin/plugin.json +1 -1
  286. package/plugin/plugin.json +1 -1
  287. package/plugin/skills/build-wizard/SKILL.md +1 -1
  288. package/apps/runtime/dist/services/projects.js +0 -473
  289. package/apps/web/dist/assets/AboutDialog-B-JxkELB.js +0 -1
  290. package/apps/web/dist/assets/EditorPage-DQ_2FOzI.js +0 -3
  291. package/apps/web/dist/assets/Marketplace-DoH4YO3D.js +0 -2
  292. package/apps/web/dist/assets/NewWizardChannels-Tgoexgj4.js +0 -1
  293. package/apps/web/dist/assets/NewWizardPage-B24AF482.js +0 -7
  294. package/apps/web/dist/assets/OnboardingPage-BEvq4slJ.js +0 -1
  295. package/apps/web/dist/assets/PreviewPane-B_v7Y8R7.js +0 -10
  296. package/apps/web/dist/assets/ProjectPage-ClRuhFJo.js +0 -10
  297. package/apps/web/dist/assets/PublicRunner-MicrpVsv.js +0 -1
  298. package/apps/web/dist/assets/ReadOnly-BXjv-MSv.js +0 -1
  299. package/apps/web/dist/assets/SettingsPage-DY8O1r43.js +0 -2
  300. package/apps/web/dist/assets/SetupPage-BOVkVpMu.js +0 -1
  301. package/apps/web/dist/assets/SharePage-DXGzJSnR.js +0 -1
  302. package/apps/web/dist/assets/SkillEditor-BzzTDeaU.js +0 -1
  303. package/apps/web/dist/assets/changelog-BLdS-0Bj.js +0 -1
  304. package/apps/web/dist/assets/esm-BdxDT9Km.js +0 -7
  305. package/apps/web/dist/assets/i18n-8-Sw11tB.js +0 -55
  306. package/apps/web/dist/assets/index-OsdQFHmh.js +0 -49
  307. package/apps/web/dist/assets/index-QPipX5Fi.css +0 -1
  308. package/apps/web/dist/assets/lock-C0uxcOlq.js +0 -1
  309. package/apps/web/dist/assets/logo-CGNoptDg.js +0 -1
  310. package/apps/web/dist/assets/oss-credits-DpRWUPjD.js +0 -1
  311. package/apps/web/dist/assets/session-BWI-KENJ.js +0 -2
  312. package/apps/web/dist/assets/theme-D7krsx0_.js +0 -11
  313. package/apps/web/dist/assets/ui-DSXG3f49.js +0 -83
@@ -1,668 +1,534 @@
1
- import { createHash } from "node:crypto";
2
- import { tableColumnsSchema } from "@engenty/wizards-shared/engenty/data-tables";
3
- import { CATEGORY_TYPES } from "@engenty/wizards-shared/knowledge";
4
- import { PROJECT_LIMITS } from "@engenty/wizards-shared/projects";
5
- import { note, noteText } from "@engenty/wizards-shared/run";
6
- import { SPACE_DATA_LIMITS } from "@engenty/wizards-shared/space-data";
7
- import { MAX_WIZARD_THEMES, themeSchema } from "@engenty/wizards-shared/theme";
8
- import { WORKSPACE_LIMITS } from "@engenty/wizards-shared/workspace";
9
- import { and, count, eq, inArray, isNull, notInArray, sql } from "drizzle-orm";
1
+ import { note } from "@engenty/wizards-shared/run";
2
+ import { COLOR_SECTION_KINDS, cleanAssetSections, cleanLogoSections, FACT_TYPES, FONT_USES, FONT_WEIGHTS, GRADIENT_TYPES, NOTIFY_MAIL, orderColors, PAGE_LANGS, PAGE_LIMITS, PAGE_SLUG, RULE_MARKS, SPACE_LIMITS, } from "@engenty/wizards-shared/spaces";
3
+ import { and, count, eq, isNull, ne } from "drizzle-orm";
10
4
  import { nanoid } from "nanoid";
11
5
  import { z } from "zod";
12
- import { db, inTransaction, schema } from "../db/client.js";
13
- import { missingModels } from "../engine/requirements.js";
6
+ import { db, schema } from "../db/client.js";
14
7
  import { env } from "../env.js";
15
- import { currentTier } from "../models.js";
8
+ import { managed, tenantInfo } from "../manage.js";
16
9
  import { spaceChanged } from "../plugins/events.js";
17
- import { sandboxEngine } from "../sandbox/index.js";
18
- import { codeOf, putLink } from "../tenants/control.js";
10
+ import { cloudSpaceLimit, twoWayActive } from "../sync/state.js";
11
+ import { putLink } from "../tenants/control.js";
19
12
  import { currentTenant } from "../tenants/tenant.js";
20
- import { asSync, mayBuild } from "./access.js";
21
- import { emitDraftChanged } from "./draft-events.js";
13
+ import { serverText } from "../texts.js";
14
+ import { mayBuild, requireAdmin, requireBuild, requireWritable } from "./access.js";
22
15
  import { notFound, ServiceError } from "./errors.js";
23
- import { keepFiles, replaceFiles } from "./files.js";
24
- import { addProjectFile, projectFiles, removeProjectFile } from "./project-files.js";
25
- import { reindexSpace } from "./project-index.js";
26
- import { brandColorSchema, projectFactSchema, projectLimit, removeProject, } from "./projects.js";
27
- import { deleteWizard, draftIssues, parseDraft, rotateShareLink, shareUrl } from "./wizards.js";
28
- /**
29
- * A local install's project on this runtime (docs/manage-contract.md, "Spaces of a local
30
- * install"). The install sends a wizard when it publishes it: the published version and its
31
- * workspace, under the ids they have there. Here the project is shown and its wizards run; it
32
- * is changed only by the next sync. The share link is this runtime's own.
33
- */
34
- /** Ids as the local install makes them (nanoid); nothing else is taken as a key. */
35
- const syncedId = z.string().regex(/^[A-Za-z0-9_-]{8,40}$/);
36
- const spaceSchema = z.object({
37
- name: z.string().min(1).max(80),
16
+ import { forgetWizardLinks } from "./links.js";
17
+ import { pushPages } from "./pages.js";
18
+ import { removeSpaceFiles } from "./space-files.js";
19
+ const sectionId = z.string().regex(/^[A-Za-z0-9_-]{1,40}$/);
20
+ export const brandColorSchema = z.object({
21
+ name: z.string().max(120),
22
+ value: z.string().regex(/^#[0-9a-fA-F]{6}$/),
23
+ section: sectionId.optional(),
24
+ });
25
+ export const colorSectionSchema = z.object({
26
+ id: sectionId,
27
+ title: z.string().max(80),
28
+ kind: z.enum(COLOR_SECTION_KINDS).optional(),
29
+ });
30
+ const hexColor = z.string().regex(/^#[0-9a-fA-F]{6}$/);
31
+ export const gradientSchema = z.object({
32
+ id: sectionId,
33
+ name: z.string().max(80),
34
+ description: z.string().max(400).optional(),
35
+ section: sectionId,
36
+ type: z.enum(GRADIENT_TYPES),
37
+ angle: z.number().min(-360).max(720),
38
+ stops: z
39
+ .array(z.object({ color: hexColor, at: z.number().min(0).max(100) }))
40
+ .min(2)
41
+ .max(12),
42
+ });
43
+ export const patternSchema = z.object({
44
+ id: sectionId,
45
+ name: z.string().max(80),
46
+ description: z.string().max(400).optional(),
47
+ section: sectionId,
48
+ file: z.string().max(40),
49
+ tile: z.boolean().optional(),
50
+ });
51
+ const rulesSchema = z
52
+ .array(z.object({ text: z.string().max(200), mark: z.enum(RULE_MARKS).optional() }))
53
+ .max(SPACE_LIMITS.logoRules);
54
+ export const brandFontSchema = z.object({
55
+ id: sectionId,
56
+ family: z.string().max(80),
57
+ role: z.string().max(200),
58
+ weights: z.array(z.number().int().min(100).max(900)).max(FONT_WEIGHTS.length + 3),
59
+ license: z.string().max(200).optional(),
60
+ uses: z.array(z.enum(FONT_USES)).max(FONT_USES.length).optional(),
61
+ source: z
62
+ .union([
63
+ z.object({ file: z.string().max(40) }),
64
+ z.object({
65
+ url: z
66
+ .string()
67
+ .max(600)
68
+ .url()
69
+ .refine((u) => u.startsWith("https://"), "an https:// address"),
70
+ }),
71
+ ])
72
+ .optional(),
73
+ });
74
+ export const textStyleSchema = z.object({
75
+ id: sectionId,
76
+ name: z.string().max(60),
77
+ font: sectionId.optional(),
78
+ size: z.number().min(6).max(400),
79
+ weight: z.number().int().min(100).max(900),
80
+ lineHeight: z.number().min(50).max(300),
81
+ tracking: z.number().min(-20).max(50),
82
+ uppercase: z.boolean().optional(),
83
+ });
84
+ export const assetSectionSchema = z.object({
85
+ id: sectionId,
86
+ title: z.string().max(80),
87
+ assets: z.array(z.string().max(40)).max(SPACE_LIMITS.files.asset),
88
+ });
89
+ export const logoSectionSchema = z.object({
90
+ id: sectionId,
91
+ title: z.string().max(80),
92
+ description: z.string().max(400),
93
+ logos: z.array(z.string().max(40)).max(SPACE_LIMITS.files.logo),
94
+ });
95
+ export const voiceBlockSchema = z.object({
96
+ id: sectionId,
97
+ title: z.string().max(80),
98
+ text: z.string().max(SPACE_LIMITS.voiceText),
99
+ });
100
+ export const brandLinkSchema = z.object({
101
+ id: sectionId,
102
+ label: z.string().max(80),
103
+ url: z.string().max(600),
104
+ });
105
+ export const spaceFactSchema = z.object({
106
+ key: z.string().regex(/^[a-z0-9_]{1,40}$/),
107
+ label: z.string().min(1).max(80),
108
+ value: z.string().max(4000),
109
+ type: z.enum(FACT_TYPES).optional(),
110
+ });
111
+ const trimmed = (max) => z
112
+ .string()
113
+ .trim()
114
+ .max(max)
115
+ .transform((v) => v || undefined)
116
+ .optional();
117
+ /** The space's public page as the studio sends it, whole. */
118
+ export const spacePageSchema = z.object({
119
+ on: z.boolean(),
120
+ slug: z.string().trim().toLowerCase().max(PAGE_LIMITS.slug),
121
+ title: z.string().trim().min(1).max(PAGE_LIMITS.title),
122
+ headline: trimmed(PAGE_LIMITS.headline),
123
+ intro: trimmed(PAGE_LIMITS.intro),
124
+ lang: z.enum(PAGE_LANGS),
125
+ form: z.enum(["du", "sie"]).optional(),
126
+ wizards: z.array(z.string().max(40)).max(60),
127
+ examples: z.record(z.string().max(40), z.string().regex(/^[A-Za-z0-9_-]{1,40}$/)),
128
+ slugs: z.record(z.string().max(40), z.string().regex(PAGE_SLUG)).optional(),
129
+ });
130
+ export const spacePatchSchema = z.object({
131
+ name: z.string().min(1).max(80).optional(),
132
+ page: spacePageSchema.optional(),
38
133
  brand: z
39
134
  .object({
40
135
  name: z.string().max(120).optional(),
41
136
  about: z.string().max(8000).optional(),
42
- colors: z.array(brandColorSchema).max(PROJECT_LIMITS.colors).optional(),
43
- })
44
- .default({}),
45
- facts: z.array(projectFactSchema).max(PROJECT_LIMITS.facts).default([]),
46
- /** The logo end users see; null for none. */
47
- logo: z
48
- .object({
49
- name: z.string().min(1).max(120),
50
- mime: z.string().max(100),
51
- description: z.string().max(600).default(""),
52
- data: z.string(),
137
+ brandName: z.string().max(120).optional(),
138
+ tagline: z.string().max(200).optional(),
139
+ voice: z.array(voiceBlockSchema).max(SPACE_LIMITS.voiceBlocks).optional(),
140
+ voiceRules: rulesSchema.optional(),
141
+ links: z.array(brandLinkSchema).max(SPACE_LIMITS.links).optional(),
142
+ colors: z.array(brandColorSchema).max(SPACE_LIMITS.colors).optional(),
143
+ colorSections: z.array(colorSectionSchema).max(SPACE_LIMITS.logoSections).optional(),
144
+ gradients: z.array(gradientSchema).max(SPACE_LIMITS.gradients).optional(),
145
+ patterns: z.array(patternSchema).max(SPACE_LIMITS.files.pattern).optional(),
146
+ colorRules: rulesSchema.optional(),
147
+ assetSections: z.array(assetSectionSchema).max(SPACE_LIMITS.logoSections).optional(),
148
+ fonts: z.array(brandFontSchema).max(SPACE_LIMITS.fonts).optional(),
149
+ textStyles: z.array(textStyleSchema).max(SPACE_LIMITS.textStyles).optional(),
150
+ typeRules: rulesSchema.optional(),
151
+ logoSections: z.array(logoSectionSchema).max(SPACE_LIMITS.logoSections).optional(),
152
+ logoRules: rulesSchema.optional(),
53
153
  })
54
- .nullable()
55
- .default(null),
56
- });
57
- export const syncWizardSchema = z.object({
58
- space: spaceSchema,
59
- /** The version the install published, as it counts them. */
60
- version: z.number().int().min(1).max(1_000_000),
61
- definition: z.unknown(),
62
- files: z
63
- .array(z.object({
64
- path: z.string().max(300),
65
- mime: z.string().max(100).optional(),
66
- data: z.string(),
67
- }))
68
- .max(WORKSPACE_LIMITS.files)
69
- .default([]),
70
- shareEnabled: z.boolean().default(true),
71
- dailyRunLimit: z.number().int().min(1).max(10_000).optional(),
72
- /** The install's themes the wizard names; the cloud keeps them as the install has them. */
73
- themes: z.array(themeSchema).max(MAX_WIZARD_THEMES).default([]),
74
- });
75
- export const syncSettingsSchema = z.object({
76
- shareEnabled: z.boolean().optional(),
77
- translate: z.boolean().optional(),
78
- dailyRunLimit: z.number().int().min(1).max(10_000).optional(),
79
- });
80
- export const checkSchema = z.object({
81
- definition: z.unknown(),
82
- /** Paths of the wizard's workspace files. */
83
- files: z.array(z.string().max(300)).max(WORKSPACE_LIMITS.files).default([]),
154
+ .optional(),
155
+ facts: z.array(spaceFactSchema).max(SPACE_LIMITS.facts).optional(),
156
+ /** The space's own mail domains, where a guest's run may send to (broker/send.ts). Admins only. */
157
+ mailDomains: z
158
+ .array(z
159
+ .string()
160
+ .trim()
161
+ .toLowerCase()
162
+ .regex(/^([a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z][a-z0-9-]{0,61}[a-z0-9]$/))
163
+ .max(20)
164
+ .optional(),
165
+ /** How the admins hear of the broker's critical lines (docs/plans/broker.md, "Notifications"). */
166
+ notify: z.object({ bell: z.boolean(), mail: z.enum(NOTIFY_MAIL) }).optional(),
167
+ /** „Mitglieder dürfen ins Studio“ (services/members-studio.ts). Admins only, as every change here. */
168
+ membersStudio: z.boolean().optional(),
84
169
  });
85
- const stepsWith = (def, has) => def.steps.filter(has).map((s) => ({ id: s.id, title: s.title }));
86
170
  /**
87
- * What of a wizard does not work on this runtime: what its validator says here (a connector
88
- * the project lacks, a plugin's tool), model classes nothing is bound to, the sandbox where
89
- * there is none.
171
+ * How many spaces the tenant works with: the number the Manage-App gives for it, else this
172
+ * runtime's (`LIMIT_SPACES`, one unless set). The studio shows a space switcher only above
173
+ * one. Spaces beyond the number stay in the database and are not listed.
90
174
  */
91
- export async function serverProblems(def, issues) {
92
- const problems = issues.map((issue) => ({
93
- code: /connector/i.test(issue.message) ? "connector" : "invalid",
94
- blocking: true,
95
- steps: stepsWith(def, (s) => s.id === issue.stepId),
96
- detail: issue.message,
97
- }));
98
- for (const missing of await missingModels(def)) {
99
- problems.push({
100
- code: "model",
101
- blocking: missing.blocking,
102
- steps: missing.steps,
103
- detail: `${missing.cls}: ${missing.problem}`,
104
- });
105
- }
106
- // The organization's tier may allow no web search: steps that search run without it.
107
- const tier = await currentTier();
108
- if (tier && !tier.rules.search) {
109
- const steps = stepsWith(def, (s) => s.type === "agent" && s.tools.includes("web_search"));
110
- if (steps.length) {
111
- problems.push({
112
- code: "model",
113
- blocking: false,
114
- steps,
115
- detail: `web_search: ${noteText(note("tierNoSearch", { tier: tier.name }), "en")}`,
116
- });
175
+ export async function spaceLimit() {
176
+ if (managed) {
177
+ const info = await tenantInfo(currentTenant()).catch(() => null);
178
+ // Null: the plan sets no limit.
179
+ if (info && info.limits.projects === null) {
180
+ return Number.POSITIVE_INFINITY;
181
+ }
182
+ if (info?.limits.projects) {
183
+ return info.limits.projects;
117
184
  }
118
185
  }
119
- if (!sandboxEngine()) {
120
- const steps = stepsWith(def, (s) => s.type === "agent" && s.tools.includes("sandbox"));
121
- if (steps.length) {
122
- problems.push({ code: "sandbox", blocking: false, steps, detail: "" });
186
+ // A local install that syncs both ways has the organization's spaces: its number counts.
187
+ if (twoWayActive()) {
188
+ const limit = cloudSpaceLimit();
189
+ if (limit === null) {
190
+ return Number.POSITIVE_INFINITY;
191
+ }
192
+ if (limit !== undefined) {
193
+ return Math.max(1, limit);
123
194
  }
124
195
  }
125
- return problems;
196
+ return Math.max(1, env.limits.spaces);
126
197
  }
127
- /** What a wizard would lack here, asked before it is sent: no project is touched. */
128
- export async function checkOnServer(input) {
129
- const { draft, issues } = parseDraft(input.definition, input.files);
130
- // Connectors are a project's; a project that is not here yet has none.
131
- const connectors = (draft.connections ?? [])
132
- .filter((c) => c.connector)
133
- .map((c) => ({
134
- message: `Connection "${c.id}" uses connector "${c.connector}", which this project has not imported.`,
135
- }));
136
- return serverProblems(draft, [...issues, ...connectors]);
198
+ /** The number for the studio: null where there is no limit (JSON has no infinity). */
199
+ export async function spaceLimitOrNull() {
200
+ const limit = await spaceLimit();
201
+ return Number.isFinite(limit) ? limit : null;
137
202
  }
138
- async function syncedProject(spaceId) {
139
- const p = await db.query.project.findFirst({
140
- where: and(eq(schema.project.id, spaceId), eq(schema.project.tenantId, currentTenant())),
203
+ export async function ownedSpace(_userId, spaceId) {
204
+ const p = await db.query.space.findFirst({
205
+ where: and(eq(schema.space.id, spaceId), eq(schema.space.tenantId, currentTenant())),
141
206
  });
142
- return p ?? null;
207
+ if (!p) {
208
+ throw notFound();
209
+ }
210
+ return p;
143
211
  }
144
- /** Refuses a project beyond the tenant's number; a synced one counts like one made here. */
145
- async function requireRoom(spaceId) {
146
- const mine = eq(schema.project.tenantId, currentTenant());
147
- // What a tenant that builds nothing here once made here is not shown, so it takes no place.
148
- const counted = (await mayBuild()) ? mine : and(mine, eq(schema.project.origin, "local"));
149
- const others = await db
150
- .select({ id: schema.project.id, name: schema.project.name, origin: schema.project.origin })
151
- .from(schema.project)
152
- .where(and(counted, sql `${schema.project.id} <> ${spaceId}`));
153
- const limit = await projectLimit();
154
- if (others.length >= limit) {
155
- throw new ServiceError("refused", limit === 1 ? note("accountAlreadySpace") : note("accountAlreadySpaces", { count: limit }), {
156
- reason: "space_limit",
157
- limit,
158
- spaces: others.filter((p) => p.origin === "local").map((p) => ({ id: p.id, name: p.name })),
212
+ /** The tenant's spaces that were made here, not synced from a local install. */
213
+ const madeHere = () => and(eq(schema.space.tenantId, currentTenant()), isNull(schema.space.origin));
214
+ /** The tenant's spaces a local install synced. */
215
+ const synced = () => and(eq(schema.space.tenantId, currentTenant()), eq(schema.space.origin, "local"));
216
+ /** What the first space is called, in the language of whoever first opens the studio. */
217
+ const FIRST_SPACE = { cloud: "firstSpaceCloud", local: "firstSpaceLocal" };
218
+ /**
219
+ * A tenant that builds here always has a space of its own: the first one is made when its
220
+ * studio is first opened, named in that request's language.
221
+ */
222
+ async function ensureSpace(lang = "en") {
223
+ const any = await db.query.space.findFirst({ where: madeHere() });
224
+ if (!any) {
225
+ const id = nanoid(12);
226
+ await db.insert(schema.space).values({
227
+ id,
228
+ tenantId: currentTenant(),
229
+ name: serverText(lang, FIRST_SPACE[env.manage.url ? "cloud" : "local"]),
159
230
  });
231
+ spaceChanged("space.created", id);
160
232
  }
161
233
  }
162
- /** A synced project holds so many wizards: each brings up to 25 MB of files to keep. */
163
- async function requireWizardRoom(spaceId) {
164
- const [row] = await db
165
- .select({ n: count() })
166
- .from(schema.wizard)
167
- .where(eq(schema.wizard.projectId, spaceId));
168
- if ((row?.n ?? 0) >= env.limits.syncedWizards) {
169
- throw new ServiceError("refused", note("roomMostPublishedWizards", { count: env.limits.syncedWizards }), { reason: "wizard_limit", limit: env.limits.syncedWizards });
234
+ /**
235
+ * The space a caller means when it names none: the oldest one made here, where a wizard
236
+ * lands; for a tenant that builds nothing here, the one its local install synced.
237
+ */
238
+ export async function defaultSpace(_userId) {
239
+ const build = await mayBuild();
240
+ if (build) {
241
+ await ensureSpace();
170
242
  }
243
+ const p = await db.query.space.findFirst({
244
+ where: build ? madeHere() : synced(),
245
+ orderBy: [schema.space.createdAt],
246
+ });
247
+ if (!p) {
248
+ throw notFound();
249
+ }
250
+ return p;
171
251
  }
172
- const hashOf = (data) => createHash("sha256").update(data).digest("hex");
173
252
  /**
174
- * The project's logo follows the install's: kept when it is the same picture, else replaced —
175
- * the new one is stored before the old one goes, so a store that fails leaves the old one.
253
+ * The spaces the studio shows. A tenant that builds here: its own and the synced ones, up to
254
+ * its number. One that does not: only what its local install synced — possibly nothing yet.
176
255
  */
177
- async function syncLogo(projectId, logo) {
178
- const here = await projectFiles(projectId, "logo");
179
- const data = logo ? Buffer.from(logo.data, "base64") : null;
180
- const mark = data ? `sync:${hashOf(data)}` : null;
181
- if (mark && here.length === 1 && here[0].source === mark) {
182
- return;
256
+ export async function listSpaces(_userId, lang) {
257
+ const build = await mayBuild();
258
+ if (build) {
259
+ await ensureSpace(lang);
183
260
  }
184
- if (logo && data && mark) {
185
- await addProjectFile(projectId, {
186
- kind: "logo",
187
- name: logo.name,
188
- mime: logo.mime,
189
- data,
190
- // With words of its own no model is asked to describe it.
191
- description: logo.description || logo.name,
192
- source: mark,
193
- });
194
- }
195
- for (const old of here) {
196
- await removeProjectFile(projectId, old.id);
261
+ // The oldest come first: with a limit of one, that is the space everything lands in.
262
+ const limit = await spaceLimit();
263
+ const spaces = await db.query.space.findMany({
264
+ where: build ? eq(schema.space.tenantId, currentTenant()) : synced(),
265
+ orderBy: [schema.space.createdAt],
266
+ ...(Number.isFinite(limit) ? { limit } : {}),
267
+ });
268
+ const counts = await db
269
+ .select({ spaceId: schema.wizard.spaceId, n: count() })
270
+ .from(schema.wizard)
271
+ .where(eq(schema.wizard.tenantId, currentTenant()))
272
+ .groupBy(schema.wizard.spaceId);
273
+ return spaces.map((p) => ({
274
+ ...p,
275
+ wizardCount: counts.find((x) => x.spaceId === p.id)?.n ?? 0,
276
+ }));
277
+ }
278
+ export async function createSpace(_userId, name) {
279
+ await requireBuild();
280
+ await requireAdmin();
281
+ const [{ n }] = await db
282
+ .select({ n: count() })
283
+ .from(schema.space)
284
+ .where(eq(schema.space.tenantId, currentTenant()));
285
+ const limit = await spaceLimit();
286
+ if (n >= limit) {
287
+ throw new ServiceError("refused", limit === 1 ? note("onlyOneSpaceAllowed") : note("mostSpaces", { count: limit }));
197
288
  }
289
+ const id = nanoid(12);
290
+ await db.insert(schema.space).values({ id, tenantId: currentTenant(), name, brand: {} });
291
+ spaceChanged("space.created", id);
292
+ return { id };
198
293
  }
199
- /** The install's themes as it has them: a synced space is a mirror, so the install's version wins. */
200
- async function mirrorThemes(project, themes) {
201
- if (!themes.length) {
202
- return;
294
+ export async function updateSpace(userId, spaceId, patch) {
295
+ const p = await ownedSpace(userId, spaceId);
296
+ await requireWritable(p);
297
+ await requireAdmin();
298
+ if (patch.facts && new Set(patch.facts.map((f) => f.key)).size !== patch.facts.length) {
299
+ throw new ServiceError("invalid", note("twoEntriesSameKey"));
300
+ }
301
+ if (patch.brand?.fonts) {
302
+ await linkFontFiles(p.id, patch.brand.fonts);
203
303
  }
204
- const ids = new Set(themes.map((t) => t.id));
304
+ const page = patch.page ? await checkedPage(p, patch.page) : undefined;
205
305
  await db
206
- .update(schema.project)
207
- .set({ themes: [...project.themes.filter((t) => !ids.has(t.id)), ...themes] })
208
- .where(eq(schema.project.id, project.id));
209
- }
210
- /** Makes or updates the synced project: its name and what it says about itself (the logo: syncLogo). */
211
- async function syncSpace(spaceId, space) {
212
- const existing = await syncedProject(spaceId);
213
- if (existing && existing.origin !== "local") {
214
- throw new ServiceError("refused", note("spaceIdAlreadyExists"), {
215
- reason: "id_taken",
216
- });
306
+ .update(schema.space)
307
+ .set({
308
+ ...(patch.name ? { name: patch.name } : {}),
309
+ ...(patch.brand ? { brand: brandAfter(p.brand, patch.brand) } : {}),
310
+ ...(patch.facts ? { facts: patch.facts } : {}),
311
+ ...(patch.mailDomains ? { mailDomains: [...new Set(patch.mailDomains)] } : {}),
312
+ ...(patch.notify ? { notify: patch.notify } : {}),
313
+ ...(page ? { page } : {}),
314
+ ...(patch.membersStudio !== undefined ? { membersStudio: patch.membersStudio } : {}),
315
+ updatedAt: new Date(),
316
+ })
317
+ .where(eq(schema.space.id, p.id));
318
+ spaceChanged("space.updated", p.id);
319
+ // The page itself, and what it is drawn from: the brand, the facts as the imprint.
320
+ if (page || patch.brand || patch.facts) {
321
+ pushPages();
217
322
  }
218
- if (!existing) {
219
- await requireRoom(spaceId);
323
+ }
324
+ /**
325
+ * The page as it is kept: its address made of the allowed characters and taken by no other space
326
+ * of the tenant, only this tenant's wizards of this space on it, and the page on in one space at
327
+ * most (`409 page_taken`, naming that space). The form is German's alone.
328
+ */
329
+ async function checkedPage(p, page) {
330
+ if (!PAGE_SLUG.test(page.slug)) {
331
+ throw new ServiceError("invalid", note("pageSlugInvalid"));
220
332
  }
221
- const now = new Date();
222
- const values = { name: space.name, brand: space.brand, facts: space.facts, syncedAt: now };
223
- if (existing) {
224
- await db
225
- .update(schema.project)
226
- .set({ ...values, updatedAt: now })
227
- .where(eq(schema.project.id, spaceId));
333
+ const others = await db.query.space.findMany({
334
+ where: and(eq(schema.space.tenantId, currentTenant()), ne(schema.space.id, p.id)),
335
+ columns: { id: true, name: true, page: true },
336
+ });
337
+ if (others.some((o) => o.page?.slug === page.slug)) {
338
+ throw new ServiceError("invalid", note("pageSlugTaken"));
228
339
  }
229
- else {
230
- await db.insert(schema.project).values({
231
- id: spaceId,
232
- tenantId: currentTenant(),
233
- origin: "local",
234
- ...values,
340
+ const holder = page.on ? others.find((o) => o.page?.on) : undefined;
341
+ if (holder) {
342
+ throw new ServiceError("page_taken", note("pageTaken", { space: holder.name }), {
343
+ space: { id: holder.id, name: holder.name },
235
344
  });
236
345
  }
237
- spaceChanged(existing ? "space.updated" : "space.created", spaceId);
238
- const project = await syncedProject(spaceId);
239
- if (!project) {
240
- throw notFound();
241
- }
242
- return project;
346
+ const own = new Set((await db.query.wizard.findMany({
347
+ where: eq(schema.wizard.spaceId, p.id),
348
+ columns: { id: true },
349
+ })).map((w) => w.id));
350
+ const wizards = [...new Set(page.wizards)].filter((id) => own.has(id));
351
+ const examples = Object.fromEntries(Object.entries(page.examples).filter(([id]) => own.has(id)));
352
+ // The wizards' addresses are kept as made (pages.ts); a wizard that is gone frees its address.
353
+ const slugs = Object.fromEntries(Object.entries({ ...p.page?.slugs, ...page.slugs }).filter(([id]) => own.has(id)));
354
+ return {
355
+ on: page.on,
356
+ slug: page.slug,
357
+ title: page.title,
358
+ ...(page.headline ? { headline: page.headline } : {}),
359
+ ...(page.intro ? { intro: page.intro } : {}),
360
+ lang: page.lang,
361
+ ...(page.lang === "de" && page.form ? { form: page.form } : {}),
362
+ wizards,
363
+ examples,
364
+ ...(Object.keys(slugs).length ? { slugs } : {}),
365
+ };
243
366
  }
244
367
  /**
245
- * Takes a wizard a local install published: the project it is in, the wizard under its id, its
246
- * workspace, and the version — published here when a run of it can finish. Sending the same
247
- * wizard again updates the copy; its link stays. The files' bytes are kept first; then the
248
- * project, the wizard, its workspace and the version are written in one transaction, so an
249
- * install whose sending broke off finds nothing half done and sends again.
368
+ * A brand font's own file is a font of the space; run pages ask for it by its id, before the
369
+ * tenant is known, so the control database learns it.
250
370
  */
251
- export async function syncWizard(rawSpaceId, rawWizardId, input) {
252
- const spaceId = syncedId.parse(rawSpaceId);
253
- const wizardId = syncedId.parse(rawWizardId);
254
- // The shape is checked before anything is written; a wrong one leaves nothing behind.
255
- const { draft } = parseDraft(input.definition, input.files.map((f) => f.path));
256
- return asSync(async () => {
257
- const files = await keepFiles(input.files.map((f) => ({ path: f.path, mime: f.mime, data: Buffer.from(f.data, "base64") })));
258
- const taken = await inTransaction(async () => {
259
- const project = await syncSpace(spaceId, input.space);
260
- await mirrorThemes(project, input.themes);
261
- const existing = await db.query.wizard.findFirst({
262
- where: and(eq(schema.wizard.id, wizardId), eq(schema.wizard.tenantId, currentTenant())),
263
- });
264
- if (existing && existing.projectId !== spaceId) {
265
- throw new ServiceError("refused", note("wizardIdAlreadyBelongs"), {
266
- reason: "id_taken",
267
- });
268
- }
269
- const settings = {
270
- title: draft.title,
271
- draft,
272
- shareEnabled: input.shareEnabled,
273
- ...(input.dailyRunLimit ? { dailyRunLimit: input.dailyRunLimit } : {}),
274
- };
275
- if (!existing) {
276
- await requireWizardRoom(spaceId);
277
- }
278
- if (existing) {
279
- await db
280
- .update(schema.wizard)
281
- .set({ ...settings, revision: sql `${schema.wizard.revision} + 1`, updatedAt: new Date() })
282
- .where(eq(schema.wizard.id, wizardId));
283
- }
284
- else {
285
- await db.insert(schema.wizard).values({
286
- id: wizardId,
287
- projectId: spaceId,
288
- tenantId: currentTenant(),
289
- // The link is made here: a token an install brought could be one another tenant holds.
290
- shareToken: nanoid(14),
291
- dailyRunLimit: env.limits.defaultDailyRuns,
292
- ...settings,
293
- });
294
- }
295
- // The workspace becomes what was sent: files that are gone there go here.
296
- await replaceFiles(wizardId, files);
297
- const row = await db.query.wizard.findFirst({ where: eq(schema.wizard.id, wizardId) });
298
- if (!row) {
299
- throw notFound();
300
- }
301
- const problems = await serverProblems(draft, await draftIssues(row));
302
- const runnable = !problems.some((p) => p.blocking);
303
- let publishedVersion = row.publishedVersion;
304
- if (runnable) {
305
- await db
306
- .insert(schema.wizardVersion)
307
- .values({ id: nanoid(12), wizardId, version: input.version, definition: draft, files })
308
- .onConflictDoUpdate({
309
- target: [schema.wizardVersion.wizardId, schema.wizardVersion.version],
310
- set: { definition: draft, files },
311
- });
312
- await db
313
- .update(schema.wizard)
314
- .set({ publishedVersion: input.version })
315
- .where(eq(schema.wizard.id, wizardId));
316
- publishedVersion = input.version;
317
- }
318
- // Last, since it reaches the object store: a store that fails takes everything back.
319
- await syncLogo(spaceId, input.space.logo);
320
- return { row, problems, runnable, publishedVersion };
321
- });
322
- const { row, problems, runnable, publishedVersion } = taken;
323
- // The public link lives in the control database, outside the transaction: set on every
324
- // sync, so one that failed to get there once is there after the next.
325
- await putLink(row.shareToken, "wizard", wizardId);
326
- emitDraftChanged({
327
- wizardId,
328
- kind: "draft",
329
- revision: row.revision,
330
- source: "mcp",
331
- client: "sync",
332
- note: null,
333
- touched: [],
371
+ async function linkFontFiles(spaceId, fonts) {
372
+ for (const f of fonts) {
373
+ if (!(f.source && "file" in f.source)) {
374
+ continue;
375
+ }
376
+ const file = await db.query.spaceFile.findFirst({
377
+ where: and(eq(schema.spaceFile.id, f.source.file), eq(schema.spaceFile.spaceId, spaceId)),
334
378
  });
335
- return {
336
- wizardId,
337
- shareUrl: shareUrl(row.shareToken),
338
- code: await codeOf(row.shareToken),
339
- shareEnabled: row.shareEnabled,
340
- publishedVersion,
341
- runnable,
342
- problems,
343
- };
344
- });
345
- }
346
- async function syncedWizard(rawSpaceId, rawWizardId) {
347
- const spaceId = syncedId.parse(rawSpaceId);
348
- const wizardId = syncedId.parse(rawWizardId);
349
- const project = await syncedProject(spaceId);
350
- const w = project?.origin === "local"
351
- ? await db.query.wizard.findFirst({
352
- where: and(eq(schema.wizard.id, wizardId), eq(schema.wizard.projectId, spaceId)),
353
- })
354
- : null;
355
- if (!w) {
356
- throw notFound();
379
+ if (!file?.mime.startsWith("font/")) {
380
+ throw new ServiceError("invalid", note("fontSourceNoFont", { family: f.family }));
381
+ }
382
+ await putLink(file.id, "font", file.id);
357
383
  }
358
- return w;
359
- }
360
- /** The install changed how a synced wizard is shared: its link on or off, its runs a day. */
361
- export async function patchSyncedWizard(spaceId, wizardId, patch) {
362
- const w = await syncedWizard(spaceId, wizardId);
363
- await db
364
- .update(schema.wizard)
365
- .set({ ...patch, updatedAt: new Date() })
366
- .where(eq(schema.wizard.id, w.id));
367
- return { ok: true };
368
- }
369
- /** The install made a new link for a wizard: its copy here gets one too, the old one stops. */
370
- export async function rotateSyncedLink(userId, spaceId, wizardId) {
371
- const w = await syncedWizard(spaceId, wizardId);
372
- const { shareToken } = await asSync(() => rotateShareLink(userId, w.id));
373
- return { shareUrl: shareUrl(shareToken), code: await codeOf(shareToken) };
374
384
  }
375
- /** The install deleted a wizard: its copy here goes, with its link and its runs. */
376
- export async function removeSyncedWizard(userId, spaceId, wizardId) {
377
- const w = await syncedWizard(spaceId, wizardId);
378
- await asSync(() => deleteWizard(userId, w.id));
379
- return { ok: true };
380
- }
381
- /** The projects local installs synced, with their wizards: what an install compares itself to. */
382
- export async function listSyncedSpaces() {
383
- const projects = await db.query.project.findMany({
384
- where: and(eq(schema.project.tenantId, currentTenant()), eq(schema.project.origin, "local")),
385
- orderBy: [schema.project.createdAt],
386
- });
387
- const wizards = projects.length
388
- ? await db
389
- .select({
390
- id: schema.wizard.id,
391
- projectId: schema.wizard.projectId,
392
- title: schema.wizard.title,
393
- publishedVersion: schema.wizard.publishedVersion,
394
- shareToken: schema.wizard.shareToken,
395
- shareEnabled: schema.wizard.shareEnabled,
396
- })
397
- .from(schema.wizard)
398
- .where(inArray(schema.wizard.projectId, projects.map((p) => p.id)))
399
- : [];
400
- return projects.map((p) => ({
401
- id: p.id,
402
- name: p.name,
403
- syncedAt: p.syncedAt?.toISOString() ?? null,
404
- wizards: wizards
405
- .filter((w) => w.projectId === p.id)
406
- .map((w) => ({
407
- id: w.id,
408
- title: w.title,
409
- publishedVersion: w.publishedVersion,
410
- shareUrl: shareUrl(w.shareToken),
411
- shareEnabled: w.shareEnabled,
412
- })),
413
- }));
414
- }
415
- /** Takes a synced project away from this runtime: its wizards, their links and runs, its files. */
416
- export async function removeSyncedSpace(rawSpaceId) {
417
- const spaceId = syncedId.parse(rawSpaceId);
418
- const project = await syncedProject(spaceId);
419
- if (project?.origin !== "local") {
420
- throw notFound();
385
+ /** An address as typed, with https:// where it has no scheme; empty where it is not one. */
386
+ function webAddress(raw) {
387
+ const text = raw.trim();
388
+ if (!text)
389
+ return "";
390
+ const url = /^[a-z][a-z0-9+.-]*:/i.test(text) ? text : `https://${text}`;
391
+ try {
392
+ const u = new URL(url);
393
+ return u.protocol === "https:" || u.protocol === "http:" || u.protocol === "mailto:" ? url : "";
394
+ }
395
+ catch {
396
+ return "";
421
397
  }
422
- await asSync(() => removeProject(spaceId));
423
- return { ok: true };
424
398
  }
425
- // --- the space's own tables and pages --------------------------------------------
426
- // What the admin made under Space → Data on the install, not what a wizard keeps: those stay
427
- // where their runs write them. Sent as a whole, it replaces what came before.
428
- // Since Knowledge: sub-pages, where an item came from, categories and what has them. An install of
429
- // before sends none of it.
430
- export const syncDataSchema = z.object({
431
- tables: z
432
- .array(z.object({
433
- id: syncedId,
434
- title: z.string().min(1).max(120),
435
- format: z.enum(["faq"]).nullish(),
436
- originLabel: z.string().max(120).nullish(),
437
- columns: tableColumnsSchema,
438
- rows: z
439
- .array(z.object({ id: syncedId, cells: z.record(z.string(), z.unknown()) }))
440
- .max(SPACE_DATA_LIMITS.rowsPerTable),
399
+ /**
400
+ * The brand with the patch on it. Sections and rules are optional: a section without title and
401
+ * logos and rules without words are not kept.
402
+ */
403
+ function brandAfter(brand, patch) {
404
+ const { logoSections, logoRules, colors, colorSections, colorRules, gradients, patterns, assetSections, fonts, textStyles, typeRules, voice, voiceRules, links, ...rest } = {
405
+ ...brand,
406
+ ...patch,
407
+ };
408
+ // A rule is its words and its sign; a bullet is the sign of none.
409
+ const rows = (list) => (list ?? [])
410
+ .map(({ text, mark }) => ({
411
+ text: text.trim(),
412
+ ...(mark && mark !== "bullet" ? { mark } : {}),
441
413
  }))
442
- .max(SPACE_DATA_LIMITS.tables),
443
- pages: z
444
- .array(z.object({
445
- id: syncedId,
446
- title: z.string().min(1).max(200),
447
- markdown: z.string().max(SPACE_DATA_LIMITS.pageChars),
448
- parentId: syncedId.nullish(),
449
- position: z.number().int().min(0).optional(),
450
- originLabel: z.string().max(120).nullish(),
414
+ .filter((r) => r.text);
415
+ const used = new Set([...(colors ?? []), ...(gradients ?? []), ...(patterns ?? [])].map((c) => c.section));
416
+ const colorGroups = (colorSections ?? [])
417
+ .map((s) => ({
418
+ ...s,
419
+ title: s.title.trim(),
420
+ ...(s.kind && s.kind !== "colors" ? { kind: s.kind } : { kind: undefined }),
451
421
  }))
452
- .max(SPACE_DATA_LIMITS.pages),
453
- categories: z
454
- .array(z.object({
455
- id: syncedId,
456
- name: z.string().min(1).max(80),
457
- type: z.enum(CATEGORY_TYPES),
458
- unit: z.string().max(20).nullish(),
459
- multiple: z.boolean(),
460
- ordered: z.boolean(),
461
- hint: z.string().max(120).nullish(),
462
- tableId: syncedId.nullish(),
463
- columnId: z.string().max(64).nullish(),
464
- position: z.number().int().min(0),
465
- values: z
466
- .array(z.object({
467
- id: syncedId,
468
- value: z.string().min(1).max(200),
469
- position: z.number().int().min(0),
470
- summary: z.string().max(20_000).nullish(),
471
- }))
472
- .max(2000),
422
+ .filter((s) => s.title || used.has(s.id));
423
+ // A gradient or a pattern lives in a section of its kind; colours only in colour sections.
424
+ const kindOf = (id) => colorGroups.find((s) => s.id === id)?.kind ?? "colors";
425
+ const inKind = (id, kind) => colorGroups.some((s) => s.id === id && s.kind === kind);
426
+ const told = ({ description, ...x }) => ({
427
+ ...x,
428
+ name: x.name.trim(),
429
+ ...(description?.trim() ? { description: description.trim() } : {}),
430
+ });
431
+ const fills = (gradients ?? []).filter((g) => inKind(g.section, "gradients")).map(told);
432
+ const tiles = (patterns ?? []).filter((p) => inKind(p.section, "patterns")).map(told);
433
+ const swatches = colors?.map((c) => c.section && kindOf(c.section) !== "colors" ? { name: c.name, value: c.value } : c);
434
+ const sections = cleanLogoSections((logoSections ?? []).map((s) => ({
435
+ ...s,
436
+ title: s.title.trim(),
437
+ description: s.description.trim(),
438
+ }))).filter((s) => s.title || s.logos.length);
439
+ const assetGroups = cleanAssetSections((assetSections ?? []).map((s) => ({ ...s, title: s.title.trim() }))).filter((s) => s.title || s.assets.length);
440
+ const typefaces = (fonts ?? [])
441
+ .map(({ license, uses, ...f }) => ({
442
+ ...f,
443
+ family: f.family.trim(),
444
+ role: f.role.trim(),
445
+ ...(license?.trim() ? { license: license.trim() } : {}),
446
+ ...(uses?.length ? { uses: FONT_USES.filter((u) => uses.includes(u)) } : {}),
473
447
  }))
474
- .max(60)
475
- .optional(),
476
- /** `p:<page>`, `t:<table>`, `r:<row>`: files stay with the install. */
477
- assignments: z
478
- .array(z.object({
479
- categoryId: syncedId,
480
- item: z.string().regex(/^[ptr]:[A-Za-z0-9_-]{8,40}$/),
481
- valueId: syncedId.nullish(),
482
- text: z.string().max(300).nullish(),
483
- num: z.number().nullish(),
484
- at: z.number().int().nullish(),
485
- bool: z.boolean().nullish(),
486
- by: z.enum(["person", "origin", "model"]),
448
+ .filter((f) => f.family);
449
+ const styles = (textStyles ?? [])
450
+ .map((s) => ({
451
+ ...s,
452
+ name: s.name.trim(),
453
+ font: typefaces.some((f) => f.id === s.font) ? s.font : undefined,
487
454
  }))
488
- .max(200_000)
489
- .optional(),
490
- });
491
- /**
492
- * Takes the space's own tables and pages a local install sent: those it no longer has go, the
493
- * others are written under the ids they have there. The space must be here already: it comes
494
- * with the first wizard.
495
- */
496
- export async function syncSpaceData(rawSpaceId, input) {
497
- const spaceId = syncedId.parse(rawSpaceId);
498
- const project = await syncedProject(spaceId);
499
- if (project?.origin !== "local") {
500
- throw notFound();
501
- }
502
- const own = (table) => and(eq(table.projectId, spaceId), isNull(table.wizardId));
503
- const tableIds = input.tables.map((t) => t.id);
504
- const pageIds = input.pages.map((p) => p.id);
505
- // An id this tenant uses for something else is not taken over.
506
- const [tablesHere, pagesHere] = await Promise.all([
507
- tableIds.length
508
- ? db.query.spaceTable.findMany({
509
- where: inArray(schema.spaceTable.id, tableIds),
510
- columns: { id: true, projectId: true, wizardId: true },
511
- })
512
- : [],
513
- pageIds.length
514
- ? db.query.spacePage.findMany({
515
- where: inArray(schema.spacePage.id, pageIds),
516
- columns: { id: true, projectId: true, wizardId: true },
517
- })
518
- : [],
519
- ]);
520
- if ([...tablesHere, ...pagesHere].some((x) => x.projectId !== spaceId || x.wizardId !== null)) {
521
- throw new ServiceError("refused", note("idAlreadyUse"), {
522
- reason: "id_taken",
523
- });
455
+ .filter((s) => s.name);
456
+ const typeRows = rows(typeRules);
457
+ const rules = rows(logoRules);
458
+ const colourRules = rows(colorRules);
459
+ // A block without words and a link without an address are not kept.
460
+ const blocks = (voice ?? [])
461
+ .map((b) => ({ ...b, title: b.title.trim(), text: b.text.trim() }))
462
+ .filter((b) => b.text);
463
+ const voiceRows = rows(voiceRules);
464
+ const places = (links ?? [])
465
+ .map((l) => ({ ...l, label: l.label.trim(), url: webAddress(l.url) }))
466
+ .filter((l) => l.url);
467
+ return {
468
+ ...rest,
469
+ ...(blocks.length ? { voice: blocks } : {}),
470
+ ...(voiceRows.length ? { voiceRules: voiceRows } : {}),
471
+ ...(places.length ? { links: places } : {}),
472
+ ...(swatches ? { colors: orderColors(swatches, colorGroups) } : {}),
473
+ ...(colorGroups.length
474
+ ? { colorSections: colorGroups.map(({ kind, ...s }) => (kind ? { ...s, kind } : s)) }
475
+ : {}),
476
+ ...(fills.length ? { gradients: fills } : {}),
477
+ ...(tiles.length ? { patterns: tiles } : {}),
478
+ ...(colourRules.length ? { colorRules: colourRules } : {}),
479
+ ...(assetGroups.length ? { assetSections: assetGroups } : {}),
480
+ ...(typefaces.length ? { fonts: typefaces } : {}),
481
+ ...(styles.length ? { textStyles: styles } : {}),
482
+ ...(typeRows.length ? { typeRules: typeRows } : {}),
483
+ ...(sections.length ? { logoSections: sections } : {}),
484
+ ...(rules.length ? { logoRules: rules } : {}),
485
+ };
486
+ }
487
+ export function spaceProfile(p) {
488
+ return {
489
+ name: p.brand.name ?? "",
490
+ about: p.brand.about ?? "",
491
+ brandName: p.brand.brandName ?? "",
492
+ tagline: p.brand.tagline ?? "",
493
+ voice: p.brand.voice ?? [],
494
+ voiceRules: p.brand.voiceRules ?? [],
495
+ links: p.brand.links ?? [],
496
+ colors: p.brand.colors ?? [],
497
+ colorSections: p.brand.colorSections ?? [],
498
+ gradients: p.brand.gradients ?? [],
499
+ patterns: p.brand.patterns ?? [],
500
+ colorRules: p.brand.colorRules ?? [],
501
+ logoSections: p.brand.logoSections ?? [],
502
+ assetSections: p.brand.assetSections ?? [],
503
+ fonts: p.brand.fonts ?? [],
504
+ textStyles: p.brand.textStyles ?? [],
505
+ typeRules: p.brand.typeRules ?? [],
506
+ logoRules: p.brand.logoRules ?? [],
507
+ facts: p.facts.filter((f) => f.value.trim()),
508
+ };
509
+ }
510
+ export async function deleteSpace(userId, spaceId) {
511
+ await requireWritable(await ownedSpace(userId, spaceId));
512
+ await requireAdmin();
513
+ const all = await db.query.space.findMany({ where: madeHere() });
514
+ if (all.length <= 1) {
515
+ throw new ServiceError("refused", note("notDeleteLastSpace"));
524
516
  }
525
- const now = new Date();
526
- await inTransaction(async () => {
527
- await db
528
- .delete(schema.spaceTable)
529
- .where(and(own(schema.spaceTable), tableIds.length ? notInArray(schema.spaceTable.id, tableIds) : undefined));
530
- await db
531
- .delete(schema.spacePage)
532
- .where(and(own(schema.spacePage), pageIds.length ? notInArray(schema.spacePage.id, pageIds) : undefined));
533
- for (const table of input.tables) {
534
- const values = { title: table.title, columns: table.columns, updatedAt: now };
535
- await db
536
- .insert(schema.spaceTable)
537
- .values({ id: table.id, tenantId: currentTenant(), projectId: spaceId, ...values })
538
- .onConflictDoUpdate({ target: schema.spaceTable.id, set: values });
539
- await db.delete(schema.spaceTableRow).where(eq(schema.spaceTableRow.tableId, table.id));
540
- for (let i = 0; i < table.rows.length; i += 200) {
541
- const batch = table.rows.slice(i, i + 200);
542
- // The order they stand in there: one millisecond apart.
543
- await db.insert(schema.spaceTableRow).values(batch.map((row, j) => ({
544
- id: row.id,
545
- tableId: table.id,
546
- cells: row.cells,
547
- createdAt: new Date(now.getTime() - table.rows.length + i + j),
548
- })));
549
- }
550
- }
551
- for (const page of input.pages) {
552
- const values = {
553
- title: page.title,
554
- markdown: page.markdown,
555
- position: page.position ?? 0,
556
- originLabel: page.originLabel ?? null,
557
- // Its place comes after every page is there.
558
- parentId: null,
559
- slug: null,
560
- updatedAt: now,
561
- };
562
- await db
563
- .insert(schema.spacePage)
564
- .values({ id: page.id, tenantId: currentTenant(), projectId: spaceId, ...values })
565
- .onConflictDoUpdate({ target: schema.spacePage.id, set: values });
566
- }
567
- const pagesThere = new Set(pageIds);
568
- for (const page of input.pages) {
569
- if (page.parentId && pagesThere.has(page.parentId) && page.parentId !== page.id) {
570
- await db
571
- .update(schema.spacePage)
572
- .set({ parentId: page.parentId })
573
- .where(eq(schema.spacePage.id, page.id));
574
- }
575
- }
576
- for (const table of input.tables) {
577
- await db
578
- .update(schema.spaceTable)
579
- .set({ format: table.format ?? null, originLabel: table.originLabel ?? null, slug: null })
580
- .where(eq(schema.spaceTable.id, table.id));
581
- }
582
- if (input.categories) {
583
- await syncCategories(spaceId, input.categories, input.assignments ?? []);
584
- }
585
- });
586
- await reindexSpace(spaceId);
587
- return { tables: input.tables.length, pages: input.pages.length };
517
+ await removeSpace(spaceId);
588
518
  }
589
- /** The categories a local install sent, their values, and what has them: they replace these here. */
590
- async function syncCategories(spaceId, categories, assignments) {
591
- const ids = categories.map((c) => c.id);
592
- const taken = ids.length
593
- ? await db.query.spaceCategory.findMany({
594
- where: inArray(schema.spaceCategory.id, ids),
595
- columns: { id: true, projectId: true },
596
- })
597
- : [];
598
- if (taken.some((c) => c.projectId !== spaceId)) {
599
- throw new ServiceError("refused", note("idAlreadyUse"), {
600
- reason: "id_taken",
601
- });
519
+ /** Takes a space away with its wizards' links and its files. */
520
+ export async function removeSpace(spaceId) {
521
+ const wizards = await db
522
+ .select({ id: schema.wizard.id })
523
+ .from(schema.wizard)
524
+ .where(eq(schema.wizard.spaceId, spaceId));
525
+ for (const w of wizards) {
526
+ await forgetWizardLinks(w.id);
602
527
  }
528
+ await removeSpaceFiles(spaceId);
603
529
  await db
604
- .delete(schema.spaceCategory)
605
- .where(and(eq(schema.spaceCategory.projectId, spaceId), ids.length ? notInArray(schema.spaceCategory.id, ids) : undefined));
606
- await db.delete(schema.spaceItemCategory).where(eq(schema.spaceItemCategory.projectId, spaceId));
607
- const tables = new Set((await db.query.spaceTable.findMany({
608
- where: eq(schema.spaceTable.projectId, spaceId),
609
- columns: { id: true },
610
- })).map((t) => t.id));
611
- const values = new Set();
612
- for (const c of categories) {
613
- const row = {
614
- name: c.name,
615
- type: c.type,
616
- unit: c.unit ?? null,
617
- multiple: c.multiple,
618
- ordered: c.ordered,
619
- hint: c.hint ?? null,
620
- proposed: false,
621
- tableId: c.tableId && tables.has(c.tableId) ? c.tableId : null,
622
- columnId: c.tableId && tables.has(c.tableId) ? (c.columnId ?? null) : null,
623
- position: c.position,
624
- updatedAt: new Date(),
625
- };
626
- await db
627
- .insert(schema.spaceCategory)
628
- .values({ id: c.id, tenantId: currentTenant(), projectId: spaceId, ...row })
629
- .onConflictDoUpdate({ target: schema.spaceCategory.id, set: row });
630
- const valueIds = c.values.map((v) => v.id);
631
- await db
632
- .delete(schema.spaceCategoryValue)
633
- .where(and(eq(schema.spaceCategoryValue.categoryId, c.id), valueIds.length ? notInArray(schema.spaceCategoryValue.id, valueIds) : undefined));
634
- for (const v of c.values) {
635
- const set = {
636
- value: v.value,
637
- position: v.position,
638
- summary: v.summary ?? null,
639
- summaryAt: v.summary ? new Date() : null,
640
- };
641
- await db
642
- .insert(schema.spaceCategoryValue)
643
- .values({ id: v.id, categoryId: c.id, ...set })
644
- .onConflictDoUpdate({ target: schema.spaceCategoryValue.id, set });
645
- values.add(v.id);
646
- }
647
- }
648
- const known = new Set(ids);
649
- const rows = assignments.filter((a) => known.has(a.categoryId) && (!a.valueId || values.has(a.valueId)));
650
- for (let i = 0; i < rows.length; i += 200) {
651
- await db.insert(schema.spaceItemCategory).values(rows.slice(i, i + 200).map((a) => {
652
- const id = a.item.slice(2);
653
- return {
654
- projectId: spaceId,
655
- categoryId: a.categoryId,
656
- pageId: a.item[0] === "p" ? id : null,
657
- tableId: a.item[0] === "t" ? id : null,
658
- rowId: a.item[0] === "r" ? id : null,
659
- valueId: a.valueId ?? null,
660
- text: a.text ?? null,
661
- num: a.num ?? null,
662
- at: a.at ?? null,
663
- bool: a.bool ?? null,
664
- by: a.by,
665
- };
666
- }));
667
- }
530
+ .delete(schema.space)
531
+ .where(and(eq(schema.space.id, spaceId), eq(schema.space.tenantId, currentTenant())));
532
+ spaceChanged("space.deleted", spaceId);
533
+ pushPages();
668
534
  }