@engenty/wizards-runtime 0.9.7 → 0.10.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (124) hide show
  1. package/apps/runtime/dist/agents/architect.js +4 -2
  2. package/apps/runtime/dist/agents/company.js +1 -1
  3. package/apps/runtime/dist/agents/studio-assistant.js +1 -1
  4. package/apps/runtime/dist/app.js +18 -1
  5. package/apps/runtime/dist/assistant/primer.js +1 -1
  6. package/apps/runtime/dist/auth/index.js +10 -1
  7. package/apps/runtime/dist/authoring/example.js +2 -2
  8. package/apps/runtime/dist/authoring/guide.js +11 -11
  9. package/apps/runtime/dist/credits/estimate.js +5 -5
  10. package/apps/runtime/dist/db/adopt.js +4 -3
  11. package/apps/runtime/dist/db/client.js +9 -1
  12. package/apps/runtime/dist/db/migrations/control/0011_model_classes.sql +11 -0
  13. package/apps/runtime/dist/db/migrations/control/meta/0011_snapshot.json +600 -0
  14. package/apps/runtime/dist/db/migrations/control/meta/_journal.json +7 -0
  15. package/apps/runtime/dist/db/migrations/tenant/0021_model_classes.sql +41 -0
  16. package/apps/runtime/dist/db/migrations/tenant/0022_sync.sql +247 -0
  17. package/apps/runtime/dist/db/migrations/tenant/meta/0021_snapshot.json +3475 -0
  18. package/apps/runtime/dist/db/migrations/tenant/meta/0022_snapshot.json +3792 -0
  19. package/apps/runtime/dist/db/migrations/tenant/meta/_journal.json +14 -0
  20. package/apps/runtime/dist/db/schema.js +60 -0
  21. package/apps/runtime/dist/docs/dev/plugins/quick-start.md +2 -2
  22. package/apps/runtime/dist/docs/dev/plugins/server.md +2 -2
  23. package/apps/runtime/dist/docs/dev/wizard-format/agent-steps.md +9 -5
  24. package/apps/runtime/dist/docs/dev/wizard-format/film-steps.md +2 -2
  25. package/apps/runtime/dist/docs/dev/wizard-format/index.md +14 -8
  26. package/apps/runtime/dist/docs/user-guide/cloud-sync.md +85 -0
  27. package/apps/runtime/dist/docs/user-guide/data.md +4 -4
  28. package/apps/runtime/dist/docs/user-guide/meta.json +1 -0
  29. package/apps/runtime/dist/docs/user-guide/models.md +22 -13
  30. package/apps/runtime/dist/docs/user-guide/steps.md +6 -6
  31. package/apps/runtime/dist/docs/user-guide/test-and-share.md +4 -14
  32. package/apps/runtime/dist/documents/parse.js +1 -1
  33. package/apps/runtime/dist/engine/requirements.js +11 -11
  34. package/apps/runtime/dist/engine/steps.js +4 -4
  35. package/apps/runtime/dist/env.js +4 -4
  36. package/apps/runtime/dist/files/blobs.js +13 -0
  37. package/apps/runtime/dist/film/step.js +1 -1
  38. package/apps/runtime/dist/harness/antigravity.js +3 -3
  39. package/apps/runtime/dist/harness/apple.js +1 -1
  40. package/apps/runtime/dist/harness/claude.js +2 -2
  41. package/apps/runtime/dist/harness/codex.js +3 -3
  42. package/apps/runtime/dist/harness/cursor.js +1 -1
  43. package/apps/runtime/dist/index.js +7 -1
  44. package/apps/runtime/dist/mcp/tools.js +6 -3
  45. package/apps/runtime/dist/models.js +64 -10
  46. package/apps/runtime/dist/plugins/jobs.js +7 -0
  47. package/apps/runtime/dist/plugins/loader.js +1 -1
  48. package/apps/runtime/dist/routes/api.js +107 -0
  49. package/apps/runtime/dist/routes/studio.js +78 -5
  50. package/apps/runtime/dist/services/assistant-chats.js +1 -1
  51. package/apps/runtime/dist/services/brand.js +1 -1
  52. package/apps/runtime/dist/services/cloud.js +39 -5
  53. package/apps/runtime/dist/services/knowledge-model.js +1 -1
  54. package/apps/runtime/dist/services/marketplace.js +3 -1
  55. package/apps/runtime/dist/services/project-files.js +1 -1
  56. package/apps/runtime/dist/services/projects.js +11 -0
  57. package/apps/runtime/dist/services/translations.js +2 -2
  58. package/apps/runtime/dist/services/wizards.js +2 -2
  59. package/apps/runtime/dist/sharing/agent.js +1 -1
  60. package/apps/runtime/dist/sync/apply.js +39 -0
  61. package/apps/runtime/dist/sync/client.js +828 -0
  62. package/apps/runtime/dist/sync/hub.js +324 -0
  63. package/apps/runtime/dist/sync/log.js +74 -0
  64. package/apps/runtime/dist/sync/records.js +943 -0
  65. package/apps/runtime/dist/sync/state.js +17 -0
  66. package/apps/runtime/dist/texts.js +12 -0
  67. package/apps/web/dist/assets/{AboutDialog-B3tljxg5.js → AboutDialog-D1YHT0jc.js} +1 -1
  68. package/apps/web/dist/assets/{ChangelogDialog-DfWTNzyl.js → ChangelogDialog-Bv02g8av.js} +1 -1
  69. package/apps/web/dist/assets/{EditorPage-XDdz2UM4.js → EditorPage-BThoZwqO.js} +4 -4
  70. package/apps/web/dist/assets/{FlowPreview-CKNVCFbp.js → FlowPreview-dc5C92kK.js} +1 -1
  71. package/apps/web/dist/assets/{Harness-BCec49Cq.js → Harness-D0nFOIVx.js} +1 -1
  72. package/apps/web/dist/assets/{Marketplace-BuYeaxK2.js → Marketplace-Cnd8BF3q.js} +2 -2
  73. package/apps/web/dist/assets/{NewWizardChannels-DRNji-bk.js → NewWizardChannels-i62Y_2DZ.js} +1 -1
  74. package/apps/web/dist/assets/{NewWizardPage-4TpgYOaI.js → NewWizardPage-BcpRA1fx.js} +1 -1
  75. package/apps/web/dist/assets/{OnboardingPage-Cf52NOIt.js → OnboardingPage-BcMDEXNq.js} +1 -1
  76. package/apps/web/dist/assets/PreviewPane-GHcVV2Hu.js +4 -0
  77. package/apps/web/dist/assets/{ProjectPage-D6Tah3QK.js → ProjectPage-TDywzUOd.js} +1 -1
  78. package/apps/web/dist/assets/{PublicRunner-Bftc1c4m.js → PublicRunner-B6JINLpR.js} +1 -1
  79. package/apps/web/dist/assets/{ReadOnly-DVQm9IYx.js → ReadOnly-Mv5M2OV9.js} +1 -1
  80. package/apps/web/dist/assets/SettingsPage-B-F1dLgt.js +2 -0
  81. package/apps/web/dist/assets/SetupPage-CVdsdVBW.js +1 -0
  82. package/apps/web/dist/assets/{SharePage-Cn-bqSyr.js → SharePage-CBSRK0wF.js} +1 -1
  83. package/apps/web/dist/assets/changelog-BR1lxaWv.js +1 -0
  84. package/apps/web/dist/assets/{coins-DgDTBbeg.js → coins-BGZKYmu6.js} +1 -1
  85. package/apps/web/dist/assets/index-D3-kv1WF.js +14 -0
  86. package/apps/web/dist/assets/index-DcUL6teA.css +1 -0
  87. package/apps/web/dist/assets/{phone-D1Drdiio.js → phone-BzHhwehj.js} +1 -1
  88. package/apps/web/dist/assets/{runners-CTd0YAiA.js → runners-C1-zIlry.js} +1 -1
  89. package/apps/web/dist/assets/{session-DX2BcTfz.js → session-B_JeZnJ0.js} +1 -1
  90. package/apps/web/dist/assets/{settings-menu-ay9jNbQu.js → settings-menu-BZRGhsIO.js} +1 -1
  91. package/apps/web/dist/assets/theme-HcCfZDzS.js +11 -0
  92. package/apps/web/dist/assets/{ui-CJCF3Mhe.js → ui-BI1RPFWT.js} +26 -26
  93. package/apps/web/dist/assets/{upload-Dj7KPL--.js → upload-CwT8oMz0.js} +1 -1
  94. package/apps/web/dist/assets/{useMutation-CUSQpD-i.js → useMutation-byk81dDj.js} +1 -1
  95. package/apps/web/dist/assets/{volume-2-CcHZOU2m.js → volume-2-B1Pz6Iwt.js} +1 -1
  96. package/apps/web/dist/assets/{wrench-CfJTFnMJ.js → wrench-CvzXRbWN.js} +1 -1
  97. package/apps/web/dist/index.html +8 -8
  98. package/apps/web/dist/mcp/flow.html +56 -56
  99. package/node_modules/@engenty/wizards/dist/plugin/index.d.ts +2 -2
  100. package/node_modules/@engenty/wizards-shared/dist/definition.d.ts +872 -18
  101. package/node_modules/@engenty/wizards-shared/dist/definition.js +52 -11
  102. package/node_modules/@engenty/wizards-shared/dist/feature-flags.d.ts +6 -0
  103. package/node_modules/@engenty/wizards-shared/dist/feature-flags.js +6 -0
  104. package/node_modules/@engenty/wizards-shared/dist/json-schema.js +3 -3
  105. package/node_modules/@engenty/wizards-shared/dist/providers.d.ts +37 -0
  106. package/node_modules/@engenty/wizards-shared/dist/providers.js +64 -12
  107. package/node_modules/@engenty/wizards-shared/dist/run.d.ts +6 -0
  108. package/node_modules/@engenty/wizards-shared/dist/run.js +12 -0
  109. package/node_modules/@engenty/wizards-shared/dist/sync-merge.d.ts +55 -0
  110. package/node_modules/@engenty/wizards-shared/dist/sync-merge.js +214 -0
  111. package/node_modules/@engenty/wizards-shared/dist/sync.d.ts +166 -0
  112. package/node_modules/@engenty/wizards-shared/dist/sync.js +40 -0
  113. package/node_modules/@engenty/wizards-shared/dist/text-merge.d.ts +14 -0
  114. package/node_modules/@engenty/wizards-shared/dist/text-merge.js +137 -0
  115. package/package.json +1 -1
  116. package/plugin/.claude-plugin/plugin.json +1 -1
  117. package/plugin/plugin.json +1 -1
  118. package/apps/web/dist/assets/PreviewPane-C4yMcZPM.js +0 -4
  119. package/apps/web/dist/assets/SettingsPage-Cd-osLDu.js +0 -2
  120. package/apps/web/dist/assets/SetupPage-Dc8U5k5P.js +0 -1
  121. package/apps/web/dist/assets/changelog-CjSBB-a4.js +0 -1
  122. package/apps/web/dist/assets/index-DS3zUVw_.css +0 -1
  123. package/apps/web/dist/assets/index-Da7hPToW.js +0 -14
  124. package/apps/web/dist/assets/theme-DanjuO1H.js +0 -11
@@ -0,0 +1,943 @@
1
+ import { validateWizard } from "@engenty/wizards-shared/definition";
2
+ import { tableColumnsSchema } from "@engenty/wizards-shared/engenty/data-tables";
3
+ import { themeSchema } from "@engenty/wizards-shared/theme";
4
+ import { and, asc, eq, inArray, isNull, ne, sql } from "drizzle-orm";
5
+ import { nanoid } from "nanoid";
6
+ import { z } from "zod";
7
+ import { db, schema } from "../db/client.js";
8
+ import { getBlob, putBlob } from "../files/blobs.js";
9
+ import { objects } from "../files/objects.js";
10
+ import { extFor } from "../files/storage.js";
11
+ import { spaceChanged } from "../plugins/events.js";
12
+ import { asSync } from "../services/access.js";
13
+ import { emitDraftChanged } from "../services/draft-events.js";
14
+ import { forgetWizardLinks } from "../services/links.js";
15
+ import { pushPages } from "../services/pages.js";
16
+ import { removeProjectFile } from "../services/project-files.js";
17
+ import { dropIndex, queueIndex } from "../services/project-index.js";
18
+ import { removeProject } from "../services/projects.js";
19
+ import { parseDraft } from "../services/wizards.js";
20
+ import { putLink } from "../tenants/control.js";
21
+ import { currentTenant } from "../tenants/tenant.js";
22
+ const ms = (d) => (d ? d.getTime() : null);
23
+ const str = (v) => (typeof v === "string" ? v : null);
24
+ const num = (v) => (typeof v === "number" ? v : null);
25
+ const bool = (v, fallback = false) => (typeof v === "boolean" ? v : fallback);
26
+ const arr = (v) => (Array.isArray(v) ? v : []);
27
+ const obj = (v) => typeof v === "object" && v !== null && !Array.isArray(v) ? v : {};
28
+ /** The categories set on a page, a row, a table or a file, keyed so a merge goes value by value. */
29
+ async function categoriesOf(column, id) {
30
+ const rows = await db.query.spaceItemCategory.findMany({
31
+ where: eq(schema.spaceItemCategory[column], id),
32
+ orderBy: [asc(schema.spaceItemCategory.id)],
33
+ });
34
+ return rows.map((r) => ({
35
+ id: `${r.categoryId}/${r.valueId ?? "-"}`,
36
+ categoryId: r.categoryId,
37
+ valueId: r.valueId,
38
+ text: r.text,
39
+ num: r.num,
40
+ at: r.at,
41
+ bool: r.bool,
42
+ by: r.by,
43
+ }));
44
+ }
45
+ async function writeCategories(projectId, column, id, list) {
46
+ await db.delete(schema.spaceItemCategory).where(eq(schema.spaceItemCategory[column], id));
47
+ const rows = arr(list).filter((a) => str(a.categoryId));
48
+ if (!rows.length) {
49
+ return;
50
+ }
51
+ await db.insert(schema.spaceItemCategory).values(rows.map((a) => ({
52
+ projectId,
53
+ categoryId: a.categoryId,
54
+ pageId: column === "pageId" ? id : null,
55
+ rowId: column === "rowId" ? id : null,
56
+ tableId: column === "tableId" ? id : null,
57
+ fileId: column === "fileId" ? id : null,
58
+ valueId: str(a.valueId),
59
+ text: str(a.text),
60
+ num: num(a.num),
61
+ at: num(a.at),
62
+ bool: typeof a.bool === "boolean" ? a.bool : null,
63
+ by: (["person", "origin", "model"].includes(a.by) ? a.by : "person"),
64
+ })));
65
+ }
66
+ /** An item a plugin wrote under a key: another one under the same key here gives way to it. */
67
+ async function clearOrigin(table, projectId, id, record) {
68
+ const origin = str(record.origin);
69
+ const key = str(record.originKey);
70
+ if (!origin || !key) {
71
+ return;
72
+ }
73
+ await db
74
+ .delete(table)
75
+ .where(and(eq(table.projectId, projectId), eq(table.origin, origin), eq(table.originKey, key), ne(table.id, id)));
76
+ }
77
+ // --- the kinds ----------------------------------------------------------------------------
78
+ const space = {
79
+ async read(id) {
80
+ const p = await db.query.project.findFirst({
81
+ where: and(eq(schema.project.id, id), eq(schema.project.tenantId, currentTenant())),
82
+ });
83
+ if (!p) {
84
+ return null;
85
+ }
86
+ return {
87
+ projectId: p.id,
88
+ record: {
89
+ name: p.name,
90
+ brand: p.brand,
91
+ facts: p.facts,
92
+ themes: p.themes,
93
+ page: p.page ?? null,
94
+ // A server's headers hold keys: they are entered on each side, like API keys.
95
+ mcpServers: p.mcpServers.map(({ headers: _, ...s }) => s),
96
+ },
97
+ };
98
+ },
99
+ async write(id, _item, r) {
100
+ const before = await db.query.project.findFirst({ where: eq(schema.project.id, id) });
101
+ const mcpServers = arr(r.mcpServers).map((s) => ({
102
+ id: String(s.id),
103
+ name: String(s.name ?? ""),
104
+ url: String(s.url ?? ""),
105
+ headers: before?.mcpServers.find((x) => x.id === s.id)?.headers,
106
+ }));
107
+ const values = {
108
+ name: str(r.name) ?? before?.name ?? "Space",
109
+ brand: obj(r.brand),
110
+ facts: arr(r.facts),
111
+ themes: arr(r.themes),
112
+ page: (r.page ?? null),
113
+ mcpServers,
114
+ };
115
+ if (before) {
116
+ await db
117
+ .update(schema.project)
118
+ .set({ ...values, updatedAt: new Date() })
119
+ .where(eq(schema.project.id, id));
120
+ }
121
+ else {
122
+ await db.insert(schema.project).values({ id, tenantId: currentTenant(), ...values });
123
+ }
124
+ return () => {
125
+ spaceChanged(before ? "space.updated" : "space.created", id);
126
+ pushPages();
127
+ };
128
+ },
129
+ async remove(id) {
130
+ await asSync(() => removeProject(id));
131
+ return undefined;
132
+ },
133
+ list: async (projectId) => [projectId],
134
+ title: (r, item) => str(r?.name) ?? item,
135
+ check(merged) {
136
+ const issues = [];
137
+ if (!z.array(themeSchema).safeParse(merged.themes ?? []).success) {
138
+ issues.push("themes");
139
+ }
140
+ return issues;
141
+ },
142
+ };
143
+ const wizard = {
144
+ async read(id) {
145
+ const w = await db.query.wizard.findFirst({
146
+ where: and(eq(schema.wizard.id, id), eq(schema.wizard.tenantId, currentTenant())),
147
+ });
148
+ if (!w) {
149
+ return null;
150
+ }
151
+ const files = await db.query.wizardFile.findMany({
152
+ where: eq(schema.wizardFile.wizardId, id),
153
+ orderBy: [asc(schema.wizardFile.path)],
154
+ });
155
+ return {
156
+ projectId: w.projectId,
157
+ record: {
158
+ projectId: w.projectId,
159
+ // The title is the draft's: it travels once, in the draft.
160
+ draft: w.draft,
161
+ shareEnabled: w.shareEnabled,
162
+ dailyRunLimit: w.dailyRunLimit,
163
+ starter: w.starter,
164
+ starterRevision: w.starterRevision,
165
+ runners: w.runners,
166
+ translate: w.translate,
167
+ // Keyed by path, so a merge goes file by file.
168
+ files: files.map((f) => ({
169
+ id: f.path,
170
+ path: f.path,
171
+ hash: f.hash,
172
+ mime: f.mime,
173
+ size: f.size,
174
+ })),
175
+ },
176
+ };
177
+ },
178
+ async write(projectId, id, r) {
179
+ const files = arr(r.files).filter((f) => str(f.path) && str(f.hash));
180
+ const { draft } = parseDraft(r.draft, files.map((f) => f.path));
181
+ const before = await db.query.wizard.findFirst({ where: eq(schema.wizard.id, id) });
182
+ const values = {
183
+ projectId,
184
+ title: draft.title,
185
+ draft,
186
+ shareEnabled: bool(r.shareEnabled, true),
187
+ ...(num(r.dailyRunLimit) ? { dailyRunLimit: num(r.dailyRunLimit) } : {}),
188
+ starter: str(r.starter),
189
+ starterRevision: num(r.starterRevision),
190
+ runners: (r.runners ?? null),
191
+ translate: bool(r.translate, true),
192
+ };
193
+ let shareToken = before?.shareToken;
194
+ if (before) {
195
+ await db
196
+ .update(schema.wizard)
197
+ .set({ ...values, revision: sql `${schema.wizard.revision} + 1`, updatedAt: new Date() })
198
+ .where(eq(schema.wizard.id, id));
199
+ }
200
+ else {
201
+ // The link is each side's own: a token from elsewhere could be one another tenant holds.
202
+ shareToken = nanoid(14);
203
+ await db
204
+ .insert(schema.wizard)
205
+ .values({ id, tenantId: currentTenant(), shareToken, ...values });
206
+ }
207
+ await db.delete(schema.wizardFile).where(eq(schema.wizardFile.wizardId, id));
208
+ if (files.length) {
209
+ await db.insert(schema.wizardFile).values(files.map((f) => ({
210
+ wizardId: id,
211
+ path: f.path,
212
+ hash: f.hash,
213
+ mime: str(f.mime) ?? "application/octet-stream",
214
+ size: num(f.size) ?? 0,
215
+ })));
216
+ }
217
+ return async () => {
218
+ if (!before && shareToken) {
219
+ await putLink(shareToken, "wizard", id);
220
+ }
221
+ const row = await db.query.wizard.findFirst({
222
+ where: eq(schema.wizard.id, id),
223
+ columns: { revision: true },
224
+ });
225
+ emitDraftChanged({
226
+ wizardId: id,
227
+ kind: "draft",
228
+ revision: row?.revision ?? 0,
229
+ source: "mcp",
230
+ client: "sync",
231
+ note: null,
232
+ touched: [],
233
+ });
234
+ };
235
+ },
236
+ async remove(_projectId, id) {
237
+ await forgetWizardLinks(id);
238
+ await db
239
+ .delete(schema.wizard)
240
+ .where(and(eq(schema.wizard.id, id), eq(schema.wizard.tenantId, currentTenant())));
241
+ return () => pushPages();
242
+ },
243
+ async list(projectId) {
244
+ const rows = await db
245
+ .select({ id: schema.wizard.id })
246
+ .from(schema.wizard)
247
+ .where(eq(schema.wizard.projectId, projectId));
248
+ return rows.map((r) => r.id);
249
+ },
250
+ title: (r, item) => str(obj(r?.draft).title) ?? item,
251
+ blobs: (r) => arr(r.files).map((f) => String(f.hash)),
252
+ check(merged, local, remote) {
253
+ const paths = (r) => arr(r?.files).map((f) => String(f.path));
254
+ let issues;
255
+ try {
256
+ issues = parseDraft(merged.draft, paths(merged)).issues.map((i) => i.message);
257
+ }
258
+ catch {
259
+ return ["draft"];
260
+ }
261
+ // Only what the merge broke: a draft may be unfinished on either side already.
262
+ const had = new Set([local, remote].flatMap((r) => {
263
+ try {
264
+ return r ? validateWizard(r.draft, paths(r)).map((i) => i.message) : [];
265
+ }
266
+ catch {
267
+ return [];
268
+ }
269
+ }));
270
+ return issues.filter((m) => !had.has(m));
271
+ },
272
+ };
273
+ /** `<wizard id>:<language>`. */
274
+ const splitTwo = (item) => {
275
+ const at = item.indexOf(":");
276
+ return [item.slice(0, at), item.slice(at + 1)];
277
+ };
278
+ const translation = {
279
+ async read(item) {
280
+ const [wizardId, lang] = splitTwo(item);
281
+ const row = await db.query.wizardTranslation.findFirst({
282
+ where: and(eq(schema.wizardTranslation.wizardId, wizardId), eq(schema.wizardTranslation.lang, lang)),
283
+ });
284
+ const w = row
285
+ ? await db.query.wizard.findFirst({
286
+ where: eq(schema.wizard.id, wizardId),
287
+ columns: { projectId: true },
288
+ })
289
+ : null;
290
+ return row && w
291
+ ? { projectId: w.projectId, record: { wizardId, lang, texts: row.texts } }
292
+ : null;
293
+ },
294
+ async write(_projectId, item, r) {
295
+ const [wizardId, lang] = splitTwo(item);
296
+ const texts = obj(r.texts);
297
+ await db
298
+ .insert(schema.wizardTranslation)
299
+ .values({ wizardId, lang, texts })
300
+ .onConflictDoUpdate({
301
+ target: [schema.wizardTranslation.wizardId, schema.wizardTranslation.lang],
302
+ set: { texts, updatedAt: new Date() },
303
+ });
304
+ return undefined;
305
+ },
306
+ async remove(_projectId, item) {
307
+ const [wizardId, lang] = splitTwo(item);
308
+ await db
309
+ .delete(schema.wizardTranslation)
310
+ .where(and(eq(schema.wizardTranslation.wizardId, wizardId), eq(schema.wizardTranslation.lang, lang)));
311
+ return undefined;
312
+ },
313
+ async list(projectId) {
314
+ const rows = await db
315
+ .select({ wizardId: schema.wizardTranslation.wizardId, lang: schema.wizardTranslation.lang })
316
+ .from(schema.wizardTranslation)
317
+ .innerJoin(schema.wizard, eq(schema.wizard.id, schema.wizardTranslation.wizardId))
318
+ .where(eq(schema.wizard.projectId, projectId));
319
+ return rows.map((r) => `${r.wizardId}:${r.lang}`);
320
+ },
321
+ title: (_r, item) => splitTwo(item)[1],
322
+ };
323
+ const message = {
324
+ async read(id) {
325
+ const m = await db.query.wizardMessage.findFirst({ where: eq(schema.wizardMessage.id, id) });
326
+ const w = m
327
+ ? await db.query.wizard.findFirst({
328
+ where: eq(schema.wizard.id, m.wizardId),
329
+ columns: { projectId: true },
330
+ })
331
+ : null;
332
+ if (!m || !w) {
333
+ return null;
334
+ }
335
+ return {
336
+ projectId: w.projectId,
337
+ record: {
338
+ wizardId: m.wizardId,
339
+ role: m.role,
340
+ content: m.content,
341
+ changed: m.changed,
342
+ source: m.source,
343
+ client: m.client,
344
+ createdAt: ms(m.createdAt),
345
+ },
346
+ };
347
+ },
348
+ async write(_projectId, id, r) {
349
+ const values = {
350
+ wizardId: String(r.wizardId),
351
+ role: (r.role === "assistant" ? "assistant" : "user"),
352
+ content: String(r.content ?? ""),
353
+ changed: bool(r.changed),
354
+ source: (r.source === "mcp" ? "mcp" : "studio"),
355
+ client: str(r.client),
356
+ createdAt: new Date(num(r.createdAt) ?? Date.now()),
357
+ };
358
+ await db
359
+ .insert(schema.wizardMessage)
360
+ .values({ id, ...values })
361
+ .onConflictDoUpdate({ target: schema.wizardMessage.id, set: values });
362
+ return undefined;
363
+ },
364
+ async remove(_projectId, id) {
365
+ await db.delete(schema.wizardMessage).where(eq(schema.wizardMessage.id, id));
366
+ return undefined;
367
+ },
368
+ async list(projectId) {
369
+ const rows = await db
370
+ .select({ id: schema.wizardMessage.id })
371
+ .from(schema.wizardMessage)
372
+ .innerJoin(schema.wizard, eq(schema.wizard.id, schema.wizardMessage.wizardId))
373
+ .where(eq(schema.wizard.projectId, projectId));
374
+ return rows.map((r) => r.id);
375
+ },
376
+ title: (r) => (str(r?.content) ?? "").slice(0, 60),
377
+ };
378
+ const page = {
379
+ async read(id) {
380
+ const p = await db.query.spacePage.findFirst({
381
+ where: and(eq(schema.spacePage.id, id), eq(schema.spacePage.tenantId, currentTenant())),
382
+ });
383
+ if (!p) {
384
+ return null;
385
+ }
386
+ // A wizard's pages are what its runs keep: they stay where the runs write them.
387
+ if (p.wizardId) {
388
+ return "skip";
389
+ }
390
+ return {
391
+ projectId: p.projectId,
392
+ record: {
393
+ projectId: p.projectId,
394
+ title: p.title,
395
+ slug: p.slug,
396
+ markdown: p.markdown,
397
+ parentId: p.parentId,
398
+ position: p.position,
399
+ origin: p.origin,
400
+ originKey: p.originKey,
401
+ originLabel: p.originLabel,
402
+ kept: p.kept,
403
+ review: p.review,
404
+ fileId: p.fileId,
405
+ categories: await categoriesOf("pageId", id),
406
+ },
407
+ };
408
+ },
409
+ async write(projectId, id, r) {
410
+ await clearOrigin(schema.spacePage, projectId, id, r);
411
+ const values = {
412
+ projectId,
413
+ title: str(r.title) ?? "",
414
+ slug: str(r.slug),
415
+ markdown: str(r.markdown) ?? "",
416
+ parentId: str(r.parentId),
417
+ position: num(r.position) ?? 0,
418
+ origin: str(r.origin),
419
+ originKey: str(r.originKey),
420
+ originLabel: str(r.originLabel),
421
+ kept: bool(r.kept),
422
+ review: str(r.review),
423
+ fileId: str(r.fileId),
424
+ };
425
+ await db
426
+ .insert(schema.spacePage)
427
+ .values({ id, tenantId: currentTenant(), ...values })
428
+ .onConflictDoUpdate({
429
+ target: schema.spacePage.id,
430
+ set: { ...values, updatedAt: new Date() },
431
+ });
432
+ await writeCategories(projectId, "pageId", id, r.categories);
433
+ return () => queueIndex(`P:${id}`);
434
+ },
435
+ async remove(_projectId, id) {
436
+ await db.delete(schema.spacePage).where(eq(schema.spacePage.id, id));
437
+ return undefined;
438
+ },
439
+ async list(projectId) {
440
+ const rows = await db
441
+ .select({ id: schema.spacePage.id })
442
+ .from(schema.spacePage)
443
+ .where(and(eq(schema.spacePage.projectId, projectId), isNull(schema.spacePage.wizardId)));
444
+ return rows.map((r) => r.id);
445
+ },
446
+ title: (r, item) => str(r?.title) ?? item,
447
+ };
448
+ const table = {
449
+ async read(id) {
450
+ const t = await db.query.spaceTable.findFirst({
451
+ where: and(eq(schema.spaceTable.id, id), eq(schema.spaceTable.tenantId, currentTenant())),
452
+ });
453
+ if (!t) {
454
+ return null;
455
+ }
456
+ if (t.wizardId) {
457
+ return "skip";
458
+ }
459
+ return {
460
+ projectId: t.projectId,
461
+ record: {
462
+ projectId: t.projectId,
463
+ title: t.title,
464
+ slug: t.slug,
465
+ format: t.format,
466
+ columns: t.columns,
467
+ origin: t.origin,
468
+ originKey: t.originKey,
469
+ originLabel: t.originLabel,
470
+ kept: t.kept,
471
+ review: t.review,
472
+ fileId: t.fileId,
473
+ categories: await categoriesOf("tableId", id),
474
+ },
475
+ };
476
+ },
477
+ async write(projectId, id, r) {
478
+ await clearOrigin(schema.spaceTable, projectId, id, r);
479
+ const values = {
480
+ projectId,
481
+ title: str(r.title) ?? "",
482
+ slug: str(r.slug),
483
+ format: (r.format === "faq" ? "faq" : null),
484
+ columns: tableColumnsSchema.parse(r.columns ?? []),
485
+ origin: str(r.origin),
486
+ originKey: str(r.originKey),
487
+ originLabel: str(r.originLabel),
488
+ kept: bool(r.kept),
489
+ review: str(r.review),
490
+ fileId: str(r.fileId),
491
+ };
492
+ await db
493
+ .insert(schema.spaceTable)
494
+ .values({ id, tenantId: currentTenant(), ...values })
495
+ .onConflictDoUpdate({
496
+ target: schema.spaceTable.id,
497
+ set: { ...values, updatedAt: new Date() },
498
+ });
499
+ await writeCategories(projectId, "tableId", id, r.categories);
500
+ return () => queueIndex(`t:${id}`);
501
+ },
502
+ async remove(_projectId, id) {
503
+ await db.delete(schema.spaceTable).where(eq(schema.spaceTable.id, id));
504
+ return undefined;
505
+ },
506
+ async list(projectId) {
507
+ const rows = await db
508
+ .select({ id: schema.spaceTable.id })
509
+ .from(schema.spaceTable)
510
+ .where(and(eq(schema.spaceTable.projectId, projectId), isNull(schema.spaceTable.wizardId)));
511
+ return rows.map((r) => r.id);
512
+ },
513
+ title: (r, item) => str(r?.title) ?? item,
514
+ check(merged) {
515
+ return tableColumnsSchema.safeParse(merged.columns ?? []).success ? [] : ["columns"];
516
+ },
517
+ };
518
+ const row = {
519
+ async read(id) {
520
+ const r = await db.query.spaceTableRow.findFirst({ where: eq(schema.spaceTableRow.id, id) });
521
+ const t = r
522
+ ? await db.query.spaceTable.findFirst({
523
+ where: and(eq(schema.spaceTable.id, r.tableId), eq(schema.spaceTable.tenantId, currentTenant())),
524
+ columns: { projectId: true, wizardId: true },
525
+ })
526
+ : null;
527
+ if (!r || !t) {
528
+ return null;
529
+ }
530
+ if (t.wizardId) {
531
+ return "skip";
532
+ }
533
+ return {
534
+ projectId: t.projectId,
535
+ record: {
536
+ projectId: t.projectId,
537
+ tableId: r.tableId,
538
+ key: r.key,
539
+ cells: r.cells,
540
+ createdAt: ms(r.createdAt),
541
+ categories: await categoriesOf("rowId", id),
542
+ },
543
+ };
544
+ },
545
+ async write(projectId, id, r) {
546
+ const values = {
547
+ tableId: String(r.tableId),
548
+ key: str(r.key),
549
+ cells: obj(r.cells),
550
+ createdAt: new Date(num(r.createdAt) ?? Date.now()),
551
+ };
552
+ await db
553
+ .insert(schema.spaceTableRow)
554
+ .values({ id, ...values })
555
+ .onConflictDoUpdate({
556
+ target: schema.spaceTableRow.id,
557
+ set: { ...values, updatedAt: new Date() },
558
+ });
559
+ await writeCategories(projectId, "rowId", id, r.categories);
560
+ return () => queueIndex(`r:${id}`);
561
+ },
562
+ async remove(_projectId, id) {
563
+ await db.delete(schema.spaceTableRow).where(eq(schema.spaceTableRow.id, id));
564
+ return undefined;
565
+ },
566
+ async list(projectId) {
567
+ const rows = await db
568
+ .select({ id: schema.spaceTableRow.id })
569
+ .from(schema.spaceTableRow)
570
+ .innerJoin(schema.spaceTable, eq(schema.spaceTable.id, schema.spaceTableRow.tableId))
571
+ .where(and(eq(schema.spaceTable.projectId, projectId), isNull(schema.spaceTable.wizardId)));
572
+ return rows.map((r) => r.id);
573
+ },
574
+ title(r, item) {
575
+ const first = Object.values(obj(r?.cells)).find((v) => typeof v === "string" && v.trim());
576
+ return typeof first === "string" ? first.slice(0, 80) : item;
577
+ },
578
+ };
579
+ /**
580
+ * Gives an existing row of a unique name the id that arrives for it, with what points to it:
581
+ * two sides that made "Region" each under an id of their own end up with one category.
582
+ */
583
+ async function rekeyCategory(from, to) {
584
+ await db.update(schema.spaceCategory).set({ id: to }).where(eq(schema.spaceCategory.id, from));
585
+ await db
586
+ .update(schema.spaceCategoryValue)
587
+ .set({ categoryId: to })
588
+ .where(eq(schema.spaceCategoryValue.categoryId, from));
589
+ await db
590
+ .update(schema.spaceItemCategory)
591
+ .set({ categoryId: to })
592
+ .where(eq(schema.spaceItemCategory.categoryId, from));
593
+ }
594
+ async function rekeyValue(from, to) {
595
+ await db
596
+ .update(schema.spaceCategoryValue)
597
+ .set({ id: to })
598
+ .where(eq(schema.spaceCategoryValue.id, from));
599
+ await db
600
+ .update(schema.spaceItemCategory)
601
+ .set({ valueId: to })
602
+ .where(eq(schema.spaceItemCategory.valueId, from));
603
+ await db
604
+ .update(schema.projectChunk)
605
+ .set({ valueId: to })
606
+ .where(eq(schema.projectChunk.valueId, from));
607
+ }
608
+ const category = {
609
+ async read(id) {
610
+ const c = await db.query.spaceCategory.findFirst({
611
+ where: and(eq(schema.spaceCategory.id, id), eq(schema.spaceCategory.tenantId, currentTenant())),
612
+ });
613
+ if (!c) {
614
+ return null;
615
+ }
616
+ const values = await db.query.spaceCategoryValue.findMany({
617
+ where: eq(schema.spaceCategoryValue.categoryId, id),
618
+ orderBy: [asc(schema.spaceCategoryValue.position), asc(schema.spaceCategoryValue.id)],
619
+ });
620
+ return {
621
+ projectId: c.projectId,
622
+ record: {
623
+ projectId: c.projectId,
624
+ name: c.name,
625
+ type: c.type,
626
+ unit: c.unit,
627
+ multiple: c.multiple,
628
+ ordered: c.ordered,
629
+ hint: c.hint,
630
+ origin: c.origin,
631
+ proposed: c.proposed,
632
+ tableId: c.tableId,
633
+ columnId: c.columnId,
634
+ position: c.position,
635
+ values: values.map((v) => ({
636
+ id: v.id,
637
+ value: v.value,
638
+ position: v.position,
639
+ summary: v.summary,
640
+ })),
641
+ },
642
+ };
643
+ },
644
+ async write(projectId, id, r) {
645
+ const name = str(r.name) ?? "";
646
+ const same = await db.query.spaceCategory.findFirst({
647
+ where: and(eq(schema.spaceCategory.projectId, projectId), eq(schema.spaceCategory.name, name), ne(schema.spaceCategory.id, id)),
648
+ columns: { id: true },
649
+ });
650
+ if (same) {
651
+ await db.delete(schema.spaceCategory).where(eq(schema.spaceCategory.id, id));
652
+ await rekeyCategory(same.id, id);
653
+ }
654
+ const type = r.type ?? "text";
655
+ const values = {
656
+ projectId,
657
+ name,
658
+ type: (["choice", "date", "number", "text", "boolean"].includes(type) ? type : "text"),
659
+ unit: str(r.unit),
660
+ multiple: bool(r.multiple),
661
+ ordered: bool(r.ordered),
662
+ hint: str(r.hint),
663
+ origin: str(r.origin),
664
+ proposed: bool(r.proposed),
665
+ tableId: str(r.tableId),
666
+ columnId: str(r.columnId),
667
+ position: num(r.position) ?? 0,
668
+ };
669
+ await db
670
+ .insert(schema.spaceCategory)
671
+ .values({ id, tenantId: currentTenant(), ...values })
672
+ .onConflictDoUpdate({
673
+ target: schema.spaceCategory.id,
674
+ set: { ...values, updatedAt: new Date() },
675
+ });
676
+ const list = arr(r.values).filter((v) => str(v.id) && str(v.value));
677
+ const keep = list.map((v) => v.id);
678
+ for (const v of list) {
679
+ const twin = await db.query.spaceCategoryValue.findFirst({
680
+ where: and(eq(schema.spaceCategoryValue.categoryId, id), eq(schema.spaceCategoryValue.value, v.value), ne(schema.spaceCategoryValue.id, v.id)),
681
+ columns: { id: true },
682
+ });
683
+ if (twin && !keep.includes(twin.id)) {
684
+ await db
685
+ .delete(schema.spaceCategoryValue)
686
+ .where(eq(schema.spaceCategoryValue.id, v.id));
687
+ await rekeyValue(twin.id, v.id);
688
+ }
689
+ }
690
+ const here = await db.query.spaceCategoryValue.findMany({
691
+ where: eq(schema.spaceCategoryValue.categoryId, id),
692
+ columns: { id: true },
693
+ });
694
+ const gone = here.map((v) => v.id).filter((v) => !keep.includes(v));
695
+ if (gone.length) {
696
+ await db.delete(schema.spaceCategoryValue).where(inArray(schema.spaceCategoryValue.id, gone));
697
+ }
698
+ const summarized = [];
699
+ for (const v of list) {
700
+ const set = {
701
+ value: v.value,
702
+ position: num(v.position) ?? 0,
703
+ summary: str(v.summary),
704
+ summaryAt: str(v.summary) ? new Date() : null,
705
+ };
706
+ await db
707
+ .insert(schema.spaceCategoryValue)
708
+ .values({ id: v.id, categoryId: id, ...set })
709
+ .onConflictDoUpdate({ target: schema.spaceCategoryValue.id, set });
710
+ if (set.summary) {
711
+ summarized.push(v.id);
712
+ }
713
+ }
714
+ return () => {
715
+ for (const v of summarized) {
716
+ queueIndex(`v:${v}`);
717
+ }
718
+ };
719
+ },
720
+ async remove(_projectId, id) {
721
+ await db.delete(schema.spaceCategory).where(eq(schema.spaceCategory.id, id));
722
+ return undefined;
723
+ },
724
+ async list(projectId) {
725
+ const rows = await db
726
+ .select({ id: schema.spaceCategory.id })
727
+ .from(schema.spaceCategory)
728
+ .where(eq(schema.spaceCategory.projectId, projectId));
729
+ return rows.map((r) => r.id);
730
+ },
731
+ title: (r, item) => str(r?.name) ?? item,
732
+ };
733
+ const assetKey = (path) => `assets/${path}`;
734
+ const file = {
735
+ async read(id) {
736
+ const f = await db.query.projectFile.findFirst({ where: eq(schema.projectFile.id, id) });
737
+ const p = f
738
+ ? await db.query.project.findFirst({
739
+ where: and(eq(schema.project.id, f.projectId), eq(schema.project.tenantId, currentTenant())),
740
+ columns: { id: true },
741
+ })
742
+ : null;
743
+ if (!f || !p) {
744
+ return null;
745
+ }
746
+ // A file still being read and described goes when it is ready.
747
+ if (f.status !== "ready") {
748
+ return "skip";
749
+ }
750
+ const asset = await db.query.asset.findFirst({ where: eq(schema.asset.id, id) });
751
+ const bytes = asset ? await objects.get(assetKey(asset.path)) : null;
752
+ if (!bytes) {
753
+ return "skip";
754
+ }
755
+ return {
756
+ projectId: f.projectId,
757
+ record: {
758
+ projectId: f.projectId,
759
+ kind: f.kind,
760
+ name: f.name,
761
+ mime: f.mime,
762
+ size: f.size,
763
+ description: f.description,
764
+ source: f.source,
765
+ position: f.position,
766
+ textHash: f.textHash,
767
+ pages: f.pages,
768
+ chars: f.chars,
769
+ origin: f.origin,
770
+ originKey: f.originKey,
771
+ originLabel: f.originLabel,
772
+ content: await putBlob(bytes),
773
+ categories: await categoriesOf("fileId", id),
774
+ },
775
+ };
776
+ },
777
+ async write(projectId, id, r) {
778
+ await clearOrigin(schema.projectFile, projectId, id, r);
779
+ const mime = str(r.mime) ?? "application/octet-stream";
780
+ const name = str(r.name) ?? "file";
781
+ const kind = (["logo", "asset", "document", "pattern"].includes(r.kind) ? r.kind : "asset");
782
+ const bytes = await getBlob(String(r.content));
783
+ const before = await db.query.asset.findFirst({ where: eq(schema.asset.id, id) });
784
+ const path = `${id}-${nanoid(6)}.${extFor(mime)}`;
785
+ await objects.put(assetKey(path), bytes);
786
+ const assetValues = {
787
+ kind: kind === "logo" ? "logo" : "project",
788
+ mime,
789
+ name,
790
+ path,
791
+ size: bytes.byteLength,
792
+ };
793
+ await db
794
+ .insert(schema.asset)
795
+ .values({ id, tenantId: currentTenant(), ...assetValues })
796
+ .onConflictDoUpdate({ target: schema.asset.id, set: assetValues });
797
+ const values = {
798
+ projectId,
799
+ kind,
800
+ name,
801
+ mime,
802
+ size: bytes.byteLength,
803
+ description: str(r.description) ?? "",
804
+ source: str(r.source),
805
+ position: num(r.position) ?? 0,
806
+ status: "ready",
807
+ error: null,
808
+ textHash: str(r.textHash),
809
+ pages: num(r.pages),
810
+ chars: num(r.chars),
811
+ origin: str(r.origin),
812
+ originKey: str(r.originKey),
813
+ originLabel: str(r.originLabel),
814
+ };
815
+ await db
816
+ .insert(schema.projectFile)
817
+ .values({ id, ...values })
818
+ .onConflictDoUpdate({
819
+ target: schema.projectFile.id,
820
+ set: { ...values, updatedAt: new Date() },
821
+ });
822
+ await writeCategories(projectId, "fileId", id, r.categories);
823
+ return async () => {
824
+ if (before && before.path !== path) {
825
+ await objects.remove(assetKey(before.path));
826
+ }
827
+ if (kind === "logo") {
828
+ await putLink(id, "logo", id);
829
+ }
830
+ if (mime.startsWith("font/")) {
831
+ await putLink(id, "font", id);
832
+ }
833
+ if (kind === "document") {
834
+ await dropIndex(id);
835
+ queueIndex(`f:${id}`);
836
+ }
837
+ };
838
+ },
839
+ async remove(projectId, id) {
840
+ await asSync(() => removeProjectFile(projectId, id)).catch(() => undefined);
841
+ return undefined;
842
+ },
843
+ async list(projectId) {
844
+ const rows = await db
845
+ .select({ id: schema.projectFile.id })
846
+ .from(schema.projectFile)
847
+ .where(and(eq(schema.projectFile.projectId, projectId), eq(schema.projectFile.status, "ready")));
848
+ return rows.map((r) => r.id);
849
+ },
850
+ title: (r, item) => str(r?.name) ?? item,
851
+ blobs: (r) => [r.content, r.textHash].filter((h) => typeof h === "string"),
852
+ };
853
+ const connector = {
854
+ async read(item) {
855
+ const [projectId, id] = splitTwo(item);
856
+ const c = await db.query.projectConnector.findFirst({
857
+ where: and(eq(schema.projectConnector.projectId, projectId), eq(schema.projectConnector.id, id)),
858
+ });
859
+ const p = c
860
+ ? await db.query.project.findFirst({
861
+ where: and(eq(schema.project.id, projectId), eq(schema.project.tenantId, currentTenant())),
862
+ columns: { id: true },
863
+ })
864
+ : null;
865
+ return c && p ? { projectId, record: { projectId, record: c.record } } : null;
866
+ },
867
+ async write(projectId, item, r) {
868
+ const [, id] = splitTwo(item);
869
+ const record = obj(r.record);
870
+ await db
871
+ .insert(schema.projectConnector)
872
+ .values({ projectId, id, record })
873
+ .onConflictDoUpdate({
874
+ target: [schema.projectConnector.projectId, schema.projectConnector.id],
875
+ set: { record, updatedAt: new Date() },
876
+ });
877
+ return undefined;
878
+ },
879
+ async remove(projectId, item) {
880
+ const [, id] = splitTwo(item);
881
+ await db
882
+ .delete(schema.projectConnector)
883
+ .where(and(eq(schema.projectConnector.projectId, projectId), eq(schema.projectConnector.id, id)));
884
+ return undefined;
885
+ },
886
+ async list(projectId) {
887
+ const rows = await db
888
+ .select({ id: schema.projectConnector.id })
889
+ .from(schema.projectConnector)
890
+ .where(eq(schema.projectConnector.projectId, projectId));
891
+ return rows.map((r) => `${projectId}:${r.id}`);
892
+ },
893
+ title: (r, item) => str(obj(r?.record).name) ?? splitTwo(item)[1],
894
+ };
895
+ export const KINDS = {
896
+ space,
897
+ wizard,
898
+ translation,
899
+ message,
900
+ page,
901
+ table,
902
+ row,
903
+ category,
904
+ file,
905
+ connector,
906
+ };
907
+ /**
908
+ * The order items are written in, so what one points to is there first: the space, its files,
909
+ * tables and categories, then rows, pages, connectors, wizards and what belongs to them.
910
+ */
911
+ export const KIND_ORDER = [
912
+ "space",
913
+ "file",
914
+ "table",
915
+ "category",
916
+ "row",
917
+ "page",
918
+ "connector",
919
+ "wizard",
920
+ "translation",
921
+ "message",
922
+ ];
923
+ /** A record as both sides compare it: keys in one order, so the same item reads the same. */
924
+ export function canonical(record) {
925
+ return JSON.stringify(record, (_k, v) => v && typeof v === "object" && !Array.isArray(v)
926
+ ? Object.fromEntries(Object.entries(v).sort(([a], [b]) => a.localeCompare(b)))
927
+ : v);
928
+ }
929
+ /**
930
+ * What still points nowhere once a batch is written: a page's parent or file, a table's file,
931
+ * a category's table, categories set with a value or category that is gone. Points are let go
932
+ * rather than the write refused: the next change of the item sends it again.
933
+ */
934
+ export async function letDanglingGo() {
935
+ await db.run(sql `UPDATE space_page SET parent_id = NULL WHERE parent_id IS NOT NULL AND parent_id NOT IN (SELECT id FROM space_page)`);
936
+ await db.run(sql `UPDATE space_page SET file_id = NULL WHERE file_id IS NOT NULL AND file_id NOT IN (SELECT id FROM project_file)`);
937
+ await db.run(sql `UPDATE space_table SET file_id = NULL WHERE file_id IS NOT NULL AND file_id NOT IN (SELECT id FROM project_file)`);
938
+ await db.run(sql `UPDATE space_category SET table_id = NULL, column_id = NULL WHERE table_id IS NOT NULL AND table_id NOT IN (SELECT id FROM space_table)`);
939
+ await db.run(sql `DELETE FROM space_item_category WHERE category_id NOT IN (SELECT id FROM space_category) OR (value_id IS NOT NULL AND value_id NOT IN (SELECT id FROM space_category_value)) OR (page_id IS NOT NULL AND page_id NOT IN (SELECT id FROM space_page)) OR (row_id IS NOT NULL AND row_id NOT IN (SELECT id FROM space_table_row)) OR (table_id IS NOT NULL AND table_id NOT IN (SELECT id FROM space_table)) OR (file_id IS NOT NULL AND file_id NOT IN (SELECT id FROM project_file))`);
940
+ await db.run(sql `DELETE FROM space_table_row WHERE table_id NOT IN (SELECT id FROM space_table)`);
941
+ await db.run(sql `DELETE FROM wizard_translation WHERE wizard_id NOT IN (SELECT id FROM wizard)`);
942
+ await db.run(sql `DELETE FROM wizard_message WHERE wizard_id NOT IN (SELECT id FROM wizard)`);
943
+ }