@ultrst-armada/kloks 2.0.3 → 2.0.5

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 (81) hide show
  1. package/package.json +6 -1
  2. package/packages/backend/dist/api/index.js +2 -1
  3. package/packages/backend/dist/{chunk-5F5V7NAG.js → chunk-5Y7K7HAT.js} +4 -1
  4. package/packages/backend/dist/{chunk-SQKG3S6P.js → chunk-AUNIGE6Q.js} +2 -2
  5. package/packages/backend/dist/chunk-BRNWUIH5.js +197 -0
  6. package/packages/backend/dist/{chunk-NY2SQOXI.js → chunk-CDRHYO44.js} +4 -1
  7. package/packages/backend/dist/{chunk-ZBNSK26X.js → chunk-CV55JMT7.js} +6 -5
  8. package/packages/backend/dist/{chunk-OWMQLML7.js → chunk-EMSSTOOK.js} +33 -2
  9. package/packages/backend/dist/chunk-FSOOAU6G.js +1132 -0
  10. package/packages/backend/dist/chunk-GVMVYC6C.js +0 -0
  11. package/packages/backend/dist/chunk-I6T64MLT.js +171 -0
  12. package/packages/backend/dist/chunk-ICVDGH2I.js +889 -0
  13. package/packages/backend/dist/chunk-IP6XWQU2.js +48 -0
  14. package/packages/backend/dist/chunk-IRNQXVYA.js +746 -0
  15. package/packages/backend/dist/{chunk-POLVHTHJ.js → chunk-KCPQWJBO.js} +4 -1
  16. package/packages/backend/dist/chunk-LC6ULEM2.js +125 -0
  17. package/packages/backend/dist/{chunk-NTKUQVCQ.js → chunk-LMUMMVTU.js} +14 -2
  18. package/packages/backend/dist/chunk-LMY6MGFD.js +78 -0
  19. package/packages/backend/dist/{chunk-OQRQCDS6.js → chunk-TRJVVNO7.js} +2 -2
  20. package/packages/backend/dist/{chunk-KPLDYX5Z.js → chunk-TRP76UR2.js} +33 -26
  21. package/packages/backend/dist/{chunk-FK3OAUXM.js → chunk-WYEVA4RC.js} +4 -2
  22. package/packages/backend/dist/{chunk-Z6G32NQQ.js → chunk-XKUWLO2M.js} +12 -9
  23. package/packages/backend/dist/{chunk-OXEP3AP6.js → chunk-Z2CT2MJ2.js} +158 -1
  24. package/packages/backend/dist/control-plane/index.js +3 -1
  25. package/packages/backend/dist/core/b2DirectCore.test.d.ts +1 -0
  26. package/packages/backend/dist/core/cloudflareIntegrationCore.test.d.ts +1 -0
  27. package/packages/backend/dist/core/googleDriveOAuthCore.d.ts +51 -0
  28. package/packages/backend/dist/core/googleDriveOAuthCore.test.d.ts +1 -0
  29. package/packages/backend/dist/core/index.d.ts +3 -0
  30. package/packages/backend/dist/core/storageConnectionCore.d.ts +136 -0
  31. package/packages/backend/dist/core/storageConnectionCore.test.d.ts +1 -0
  32. package/packages/backend/dist/core/storageConnectionRuntimeCore.d.ts +57 -0
  33. package/packages/backend/dist/core/storageConnectionRuntimeCore.test.d.ts +1 -0
  34. package/packages/backend/dist/core/storageContracts.d.ts +77 -0
  35. package/packages/backend/dist/core/storageProviderRegistry.d.ts +7 -0
  36. package/packages/backend/dist/core/systemCredentialsCore.d.ts +46 -0
  37. package/packages/backend/dist/core/unifiedDb.d.ts +12 -2
  38. package/packages/backend/dist/core/unifiedDb.errors.test.d.ts +1 -0
  39. package/packages/backend/dist/core/unifiedDbNodeAdapter.d.ts +6 -0
  40. package/packages/backend/dist/core/workspaceBucketSyncCore.d.ts +3 -4
  41. package/packages/backend/dist/core/workspaceBucketSyncCore.test.d.ts +1 -0
  42. package/packages/backend/dist/core/workspaceCore.d.ts +25 -6
  43. package/packages/backend/dist/core/workspaceDataCore.test.d.ts +1 -0
  44. package/packages/backend/dist/core/workspaceFileCore.d.ts +25 -7
  45. package/packages/backend/dist/core/workspaceFileCore.test.d.ts +1 -0
  46. package/packages/backend/dist/core/workspaceFileNodeAdapter.d.ts +6 -0
  47. package/packages/backend/dist/core/workspaceStorageDetailsCore.d.ts +4 -8
  48. package/packages/backend/dist/core/workspaceStorageDetailsCore.test.d.ts +1 -0
  49. package/packages/backend/dist/development/index.js +1 -1
  50. package/packages/backend/dist/development/playwrightInspectionService.js +1 -1
  51. package/packages/backend/dist/development/playwrightInspectionSupport.d.ts +1 -0
  52. package/packages/backend/dist/index.js +22 -16
  53. package/packages/backend/dist/krnl-services.d.ts +0 -22
  54. package/packages/backend/dist/krnl-services.js +8 -19
  55. package/packages/backend/dist/krnl-services.node.d.ts +28 -0
  56. package/packages/backend/dist/node.d.ts +3 -0
  57. package/packages/backend/dist/node.js +645 -463
  58. package/packages/backend/dist/resolver/index.js +13 -0
  59. package/packages/backend/dist/resolver/systemDatabaseUrl.d.ts +16 -12
  60. package/packages/backend/dist/services/node.js +12 -10
  61. package/packages/backend/dist/srkl/index.js +6 -4
  62. package/packages/backend/dist/storage/B2DirectClient.d.ts +7 -13
  63. package/packages/backend/dist/storage/B2DirectClient.test.d.ts +1 -0
  64. package/packages/backend/dist/storage/GoogleDriveWorkspaceService.d.ts +5 -0
  65. package/packages/backend/dist/storage/index.js +4 -3
  66. package/packages/backend/dist/storage/node.js +7 -6
  67. package/packages/backend/dist/storage-workspace.js +1 -1
  68. package/packages/backend/dist/workspace/index.js +2 -1
  69. package/packages/backend/dist/workspace/node.js +12 -7
  70. package/packages/backend/dist/workspaceFileCore-UURQPP62.js +28 -0
  71. package/packages/backend/package.json +8 -3
  72. package/packages/services/dist/index.js +8 -2
  73. package/packages/state-graph/dist/browser.js +16 -16
  74. package/packages/state-graph/dist/index.js +16 -16
  75. package/packages/backend/dist/chunk-4QEMALXF.js +0 -90
  76. package/packages/backend/dist/chunk-AOZSDRNY.js +0 -159
  77. package/packages/backend/dist/chunk-GYSZ6CAX.js +0 -19
  78. package/packages/backend/dist/chunk-JCMB7BIM.js +0 -211
  79. package/packages/backend/dist/chunk-JGUWYVOL.js +0 -570
  80. package/packages/backend/dist/chunk-LMOM7CST.js +0 -427
  81. package/packages/state-graph/dist/{chunk-UKTICGGV.js → chunk-YUJC367F.js} +3 -3
@@ -0,0 +1,746 @@
1
+ import {
2
+ deleteWorkspaceFolder,
3
+ readWorkspaceFile,
4
+ writeWorkspaceFile
5
+ } from "./chunk-BRNWUIH5.js";
6
+ import {
7
+ createGoogleDriveWorkspaceClient,
8
+ listUserStorageConnections,
9
+ queryUnifiedDb,
10
+ resolveUserStorageConnectionSecret,
11
+ resolveUserWorkspaceStorageAssociation,
12
+ testBackblazeCredentials,
13
+ toPublicStorageConnection
14
+ } from "./chunk-FSOOAU6G.js";
15
+ import {
16
+ b2ListBuckets,
17
+ b2ListFileNames
18
+ } from "./chunk-I6T64MLT.js";
19
+
20
+ // src/core/workspaceBucketSyncCore.ts
21
+ function resolveWorkspaceConnection(profiles, workspace, appId = "depm") {
22
+ const collections = [];
23
+ const preferred = profiles?.[String(appId || "depm").toLowerCase()]?.storage_connections;
24
+ if (Array.isArray(preferred)) collections.push(preferred);
25
+ for (const value of Object.values(profiles || {})) {
26
+ if (value && typeof value === "object" && Array.isArray(value.storage_connections)) {
27
+ collections.push(value.storage_connections);
28
+ }
29
+ }
30
+ const byId = /* @__PURE__ */ new Map();
31
+ for (const connection2 of collections.flat()) {
32
+ if (connection2 && typeof connection2.id === "string" && !byId.has(connection2.id)) {
33
+ byId.set(connection2.id, connection2);
34
+ }
35
+ }
36
+ const connections = [...byId.values()];
37
+ const connectionId = String(workspace?.storageConnectionId || "").trim();
38
+ if (!connectionId) return null;
39
+ const connection = connections.find((item) => item.id === connectionId) || null;
40
+ if (!connection) return null;
41
+ const provider = String(workspace?.storageProvider || "").toLowerCase();
42
+ if (provider && String(connection.provider || "").toLowerCase() !== provider) return null;
43
+ return connection;
44
+ }
45
+ function isPersistentCloudConnection(connection) {
46
+ return connection?.provider === "backblaze_b2" || connection?.provider === "google_drive";
47
+ }
48
+ function requireVerifiedWorkspaceOwner(workspace, connection) {
49
+ const connectionOwner = String(connection?.__ownerUserId || "").trim();
50
+ const workspaceOwner = String(workspace?.__ownerUserId || "").trim();
51
+ if (!connectionOwner) {
52
+ throw new Error("Cloud workspace synchronization requires a connection resolved for a verified owner.");
53
+ }
54
+ if (workspaceOwner && connectionOwner !== workspaceOwner) {
55
+ throw new Error("Cloud workspace synchronization owner does not match the persisted workspace owner.");
56
+ }
57
+ return connectionOwner;
58
+ }
59
+ async function assertPersistedWorkspaceAssociation(workspace, connection, env) {
60
+ const ownerId = requireVerifiedWorkspaceOwner(workspace, connection);
61
+ const folderPrefix = String(
62
+ workspace?.localFolderKey || workspace?.localFolderName || workspace?.workspacePath || ""
63
+ ).replace(/^\.\//, "");
64
+ const persisted = await resolveUserWorkspaceStorageAssociation(
65
+ ownerId,
66
+ String(connection.id),
67
+ folderPrefix,
68
+ (sql, params) => queryUnifiedDb(sql, params, env)
69
+ );
70
+ if (!persisted || String(persisted.id) !== String(workspace?.id)) {
71
+ throw new Error("Cloud workspace synchronization requires the persisted workspace-to-connection association.");
72
+ }
73
+ if (String(persisted.storageProvider || "").toLowerCase() !== String(connection.provider || "").toLowerCase()) {
74
+ throw new Error("Persisted workspace provider does not match the resolved storage connection.");
75
+ }
76
+ if (connection.provider === "backblaze_b2") {
77
+ const persistedBucket = String(persisted.b2BucketName || persisted.bucketName || "").trim();
78
+ const selectedBucket = String(workspace.b2BucketName || connection.b2BucketName || connection.bucketName || "").trim();
79
+ if (persistedBucket && selectedBucket && persistedBucket !== selectedBucket) {
80
+ throw new Error("Persisted workspace B2 bucket does not match the synchronization target.");
81
+ }
82
+ }
83
+ if (connection.provider === "google_drive") {
84
+ const persistedRoot = String(persisted.googleRootFolderId || connection.googleRootFolderId || "").trim();
85
+ const selectedRoot = String(workspace.googleRootFolderId || connection.googleRootFolderId || "").trim();
86
+ if (persistedRoot && selectedRoot && persistedRoot !== selectedRoot) {
87
+ throw new Error("Persisted workspace Google Drive root does not match the synchronization target.");
88
+ }
89
+ }
90
+ }
91
+ async function syncWorkspaceCreateToBucket(workspace, connection, env) {
92
+ const provider = String(connection?.provider || workspace?.storageProvider || "").toLowerCase();
93
+ if (provider === "local_fs") return;
94
+ if (!isPersistentCloudConnection(connection) || workspace?.storageConnectionId !== connection?.id) {
95
+ throw new Error("Workspace initialization requires its exact, verified persistent storage connection.");
96
+ }
97
+ await assertPersistedWorkspaceAssociation(workspace, connection, env);
98
+ if (String(workspace?.storageProvider || "").toLowerCase() !== provider) {
99
+ throw new Error("Workspace initialization storage provider does not match its saved connection.");
100
+ }
101
+ const metadata = {
102
+ id: workspace.id,
103
+ name: workspace.name,
104
+ createdAt: workspace.createdAt,
105
+ updatedAt: workspace.updatedAt,
106
+ storageProvider: provider,
107
+ storageConnectionId: connection.id,
108
+ ...provider === "backblaze_b2" ? {
109
+ bucket: connection.b2BucketName || connection.bucketName || workspace.b2BucketName
110
+ } : {
111
+ rootFolderId: workspace.googleRootFolderId || connection.googleRootFolderId
112
+ }
113
+ };
114
+ if (provider === "backblaze_b2" && !metadata.bucket) {
115
+ throw new Error("Backblaze B2 workspace initialization requires a selected bucket.");
116
+ }
117
+ if (provider === "google_drive" && !metadata.rootFolderId) {
118
+ throw new Error("Google Drive workspace initialization requires a selected root folder.");
119
+ }
120
+ await writeWorkspaceFile(workspace, connection, ".bzEmpty", new Uint8Array(0), "application/x-empty", env);
121
+ await writeWorkspaceFile(workspace, connection, "workspace.json", JSON.stringify(metadata, null, 2), "application/json", env);
122
+ await writeWorkspaceFile(
123
+ workspace,
124
+ connection,
125
+ "ecosystem.json",
126
+ JSON.stringify({ apps: [], nodes: [], edges: [], ecosystems: [] }, null, 2),
127
+ "application/json",
128
+ env
129
+ );
130
+ }
131
+ async function syncWorkspaceDeleteToBucket(workspace, connection, env) {
132
+ if (!isPersistentCloudConnection(connection)) return;
133
+ if (!workspace?.storageConnectionId || workspace.storageConnectionId !== connection.id) {
134
+ throw new Error("Workspace deletion requires its exact, owner-resolved storage connection.");
135
+ }
136
+ await assertPersistedWorkspaceAssociation(workspace, connection, env);
137
+ if (String(workspace?.storageProvider || "").toLowerCase() !== String(connection.provider || "").toLowerCase()) {
138
+ throw new Error("Workspace deletion storage provider does not match its saved connection.");
139
+ }
140
+ await deleteWorkspaceFolder(workspace, connection, env);
141
+ }
142
+ async function syncWorkspaceDataToBucket(workspace, connection, data, env) {
143
+ if (!isPersistentCloudConnection(connection)) return;
144
+ if (!workspace?.storageConnectionId || workspace.storageConnectionId !== connection.id) {
145
+ throw new Error("Workspace data synchronization requires its exact, owner-resolved storage connection.");
146
+ }
147
+ await assertPersistedWorkspaceAssociation(workspace, connection, env);
148
+ if (String(workspace?.storageProvider || "").toLowerCase() !== String(connection.provider || "").toLowerCase()) {
149
+ throw new Error("Workspace data synchronization storage provider does not match its saved connection.");
150
+ }
151
+ await writeWorkspaceFile(
152
+ workspace,
153
+ connection,
154
+ "ecosystem.json",
155
+ JSON.stringify(data, null, 2),
156
+ "application/json",
157
+ env
158
+ );
159
+ }
160
+
161
+ // src/core/workspaceDataCore.ts
162
+ async function resolveWorkspaceConnectionForOwner(user, workspace, env) {
163
+ const userId = String(user?.id || "").trim();
164
+ const connectionId = String(workspace?.storageConnectionId || "").trim();
165
+ const provider = String(workspace?.storageProvider || "").toLowerCase();
166
+ if (!userId || !connectionId || !["backblaze_b2", "google_drive"].includes(provider)) return null;
167
+ const connection = await resolveUserStorageConnectionSecret(
168
+ userId,
169
+ connectionId,
170
+ (sql, params) => queryUnifiedDb(sql, params, env),
171
+ provider
172
+ );
173
+ if (!connection || connection.enabled === false || String(connection.provider || "").toLowerCase() !== provider) {
174
+ return null;
175
+ }
176
+ return { ...connection, __ownerUserId: userId };
177
+ }
178
+ async function resolveUserRow(userId, env) {
179
+ if (!userId) return null;
180
+ const query = (sql, params) => queryUnifiedDb(sql, params, env);
181
+ await listUserStorageConnections(userId, query);
182
+ try {
183
+ const canonical = await queryUnifiedDb(
184
+ `SELECT * FROM "ultrst-users" WHERE id = $1 OR email = $1 LIMIT 1`,
185
+ [userId],
186
+ env
187
+ );
188
+ if (canonical.rows.length > 0) return canonical.rows[0];
189
+ } catch (error) {
190
+ const value = error;
191
+ const missing = value?.code === "42P01" || value?.code === "PGRST205" || typeof value?.message === "string" && /(?:relation|table).*(?:does not exist|not found)/i.test(value.message);
192
+ if (!missing) throw error;
193
+ }
194
+ const legacy = await queryUnifiedDb(
195
+ `SELECT * FROM "srkl_application_profiles" WHERE id = $1 OR email = $1 LIMIT 1`,
196
+ [userId],
197
+ env
198
+ );
199
+ return legacy.rows[0] || null;
200
+ }
201
+ async function loadWorkspaceData(userId, workspaceId, env) {
202
+ if (!workspaceId) return { success: false, error: "workspaceId required", workspace: null };
203
+ const user = await resolveUserRow(userId, env);
204
+ if (!user) return { success: false, error: "User not found", workspace: null };
205
+ const profiles = typeof user.app_profiles === "string" ? JSON.parse(user.app_profiles) : user.app_profiles || {};
206
+ const depm = profiles.depm || {};
207
+ const workspaceDataMap = depm.workspace_data || {};
208
+ let data = workspaceDataMap[workspaceId];
209
+ const isEmptyData = !data || (!data.nodes || data.nodes.length === 0) && (!data.apps || data.apps.length === 0);
210
+ if (isEmptyData) {
211
+ const ws = (depm.workspaces || []).find((w) => w.id === workspaceId);
212
+ if (ws) {
213
+ const conn = await resolveWorkspaceConnectionForOwner(user, ws, env);
214
+ if (conn) {
215
+ try {
216
+ const fileBuf = await readWorkspaceFile(ws, conn, "ecosystem.json");
217
+ if (fileBuf && fileBuf.length > 0) {
218
+ const parsed = JSON.parse(new TextDecoder().decode(fileBuf));
219
+ if (parsed.nodes && parsed.nodes.length > 0 || parsed.apps && parsed.apps.length > 0) {
220
+ if (!profiles.depm) profiles.depm = {};
221
+ if (!profiles.depm.workspace_data) profiles.depm.workspace_data = {};
222
+ profiles.depm.workspace_data[workspaceId] = parsed;
223
+ data = parsed;
224
+ await queryUnifiedDb(
225
+ `UPDATE "ultrst-users" SET app_profiles = $1, updated_at = NOW() WHERE id = $2`,
226
+ [JSON.stringify(profiles), user.id],
227
+ env
228
+ );
229
+ return { success: true, workspace: data, workspaceId };
230
+ }
231
+ }
232
+ } catch (err) {
233
+ console.warn("[WorkspaceDataCore] Storage recovery check:", err.message);
234
+ }
235
+ }
236
+ }
237
+ }
238
+ if (!data) {
239
+ const ws = (depm.workspaces || []).find((w) => w.id === workspaceId);
240
+ const ecoName = ws?.ecosystemName || `${ws?.name || "Workspace"} Ecosystem`;
241
+ const fallback = {
242
+ apps: [],
243
+ accounts: [],
244
+ deployments: [],
245
+ nodes: [],
246
+ edges: [],
247
+ ecosystems: [
248
+ {
249
+ id: `eco_${workspaceId}`,
250
+ name: ecoName,
251
+ icon: "Globe",
252
+ health: "HEALTHY",
253
+ status: "SYSTEM ONLINE",
254
+ connectedAppsCount: 0,
255
+ meshLinkCount: 0,
256
+ createdAt: (/* @__PURE__ */ new Date()).toISOString(),
257
+ updatedAt: (/* @__PURE__ */ new Date()).toISOString()
258
+ }
259
+ ],
260
+ ecosystemName: ecoName,
261
+ ecosystemNodes: [
262
+ {
263
+ id: `node_eco_root_${workspaceId}`,
264
+ type: "ECOSYSTEM",
265
+ name: ecoName,
266
+ x: 0,
267
+ y: 0,
268
+ appId: "__ecosystem__",
269
+ icon: "Globe",
270
+ ecosystemData: { connectedAppsCount: 0, health: "HEALTHY", status: "SYSTEM ONLINE" }
271
+ }
272
+ ],
273
+ ecosystemEdges: []
274
+ };
275
+ return { success: true, workspace: fallback, workspaceId };
276
+ }
277
+ return { success: true, workspace: data, workspaceId };
278
+ }
279
+ async function saveWorkspaceData(userId, workspaceId, data, env) {
280
+ if (!workspaceId) return { success: false, error: "workspaceId required" };
281
+ const user = await resolveUserRow(userId, env);
282
+ if (!user) return { success: false, error: "User not found" };
283
+ const profiles = typeof user.app_profiles === "string" ? JSON.parse(user.app_profiles) : user.app_profiles || {};
284
+ if (!profiles.depm) profiles.depm = {};
285
+ if (!profiles.depm.workspace_data) profiles.depm.workspace_data = {};
286
+ const existing = profiles.depm.workspace_data[workspaceId];
287
+ const incomingEmpty = (!data.nodes || data.nodes.length === 0) && (!data.apps || data.apps.length === 0);
288
+ const existingHasData = existing && (existing.nodes && existing.nodes.length > 0 || existing.apps && existing.apps.length > 0);
289
+ if (incomingEmpty && existingHasData && !data._forceEmptySave) {
290
+ console.warn(`[WorkspaceDataCore] Blocked empty overwrite for workspace ${workspaceId}.`);
291
+ return { success: true, workspaceId, workspace: existing, protected: true };
292
+ }
293
+ profiles.depm.workspace_data[workspaceId] = data;
294
+ if (Array.isArray(profiles.depm.workspaces)) {
295
+ const ws2 = profiles.depm.workspaces.find((w) => w.id === workspaceId);
296
+ if (ws2) {
297
+ ws2.appsCount = Array.isArray(data.apps) ? data.apps.length : 0;
298
+ ws2.updatedAt = (/* @__PURE__ */ new Date()).toISOString();
299
+ }
300
+ }
301
+ await queryUnifiedDb(
302
+ `UPDATE "ultrst-users" SET app_profiles = $1, updated_at = NOW() WHERE id = $2`,
303
+ [JSON.stringify(profiles), user.id],
304
+ env
305
+ );
306
+ const ws = Array.isArray(profiles.depm?.workspaces) ? profiles.depm.workspaces.find((w) => w.id === workspaceId) : null;
307
+ if (ws) {
308
+ const provider = String(ws.storageProvider || "").toLowerCase();
309
+ if (provider === "backblaze_b2" || provider === "google_drive") {
310
+ const conn = await resolveWorkspaceConnectionForOwner(user, ws, env);
311
+ if (!conn) {
312
+ throw new Error("Workspace data synchronization requires its exact owner-owned storage connection.");
313
+ }
314
+ await syncWorkspaceDataToBucket(
315
+ { ...ws, __ownerUserId: String(user.id) },
316
+ conn,
317
+ data,
318
+ env
319
+ );
320
+ }
321
+ }
322
+ return { success: true, workspaceId, workspace: data };
323
+ }
324
+ async function renameAppInWorkspaceData(userId, workspaceId, appId, newName, env) {
325
+ if (!workspaceId || !appId || !newName) {
326
+ return { success: false, error: "workspaceId, appId and newName required" };
327
+ }
328
+ const loadRes = await loadWorkspaceData(userId, workspaceId, env);
329
+ if (!loadRes.success || !loadRes.workspace) return loadRes;
330
+ const wsData = loadRes.workspace;
331
+ const trimmed = newName.trim();
332
+ const folderName = trimmed.replace(/[/\\?%*:|"<>]/g, "_");
333
+ if (Array.isArray(wsData.apps)) {
334
+ const targetApp = wsData.apps.find((a) => a.id === appId);
335
+ if (targetApp) {
336
+ targetApp.name = trimmed;
337
+ targetApp.folderName = folderName;
338
+ targetApp.updatedAt = (/* @__PURE__ */ new Date()).toISOString();
339
+ }
340
+ }
341
+ if (Array.isArray(wsData.nodes)) {
342
+ wsData.nodes = wsData.nodes.map((n) => {
343
+ if (n.appId === appId && (n.type === "APP" || n.type === "APP_NODE" || n.type === "APP_GRAPH_NODE")) {
344
+ return { ...n, name: trimmed, appData: n.appData ? { ...n.appData, name: trimmed, folderName } : void 0 };
345
+ }
346
+ return n;
347
+ });
348
+ }
349
+ return await saveWorkspaceData(userId, workspaceId, wsData, env);
350
+ }
351
+
352
+ // src/core/workspaceCore.ts
353
+ function workspaceAppId(env) {
354
+ const value = String(env?.WORKSPACE_APP_ID ?? "depm").trim().toLowerCase();
355
+ return value || "depm";
356
+ }
357
+ function appProfile(profiles, appId) {
358
+ if (!profiles[appId] || typeof profiles[appId] !== "object") profiles[appId] = {};
359
+ return profiles[appId];
360
+ }
361
+ async function resolveWorkspaceConnectionForUser(userId, _profiles, workspace, env) {
362
+ const provider = String(workspace?.storageProvider || "").trim().toLowerCase();
363
+ const connectionId = String(workspace?.storageConnectionId || "").trim();
364
+ if (!connectionId || !["backblaze_b2", "google_drive"].includes(provider)) return null;
365
+ const connection = await resolveUserStorageConnectionSecret(
366
+ userId,
367
+ connectionId,
368
+ (sql, params) => queryUnifiedDb(sql, params, env),
369
+ provider
370
+ );
371
+ if (!connection || connection.enabled === false || connection.provider !== provider) return null;
372
+ return { ...connection, __ownerUserId: userId };
373
+ }
374
+ function isMissingProfileRelation(error) {
375
+ if (!error || typeof error !== "object") return false;
376
+ const value = error;
377
+ if (value.code === "42P01" || value.code === "PGRST205") return true;
378
+ return typeof value.message === "string" && /(?:relation|table).*(?:does not exist|not found)|schema cache.*(?:relation|table)/i.test(value.message);
379
+ }
380
+ async function findUserWorkspace(workspaceId, env, verifiedUserId) {
381
+ const ownerId = String(verifiedUserId || "").trim();
382
+ if (!ownerId) return { user: null, workspace: null, connection: null };
383
+ let user;
384
+ try {
385
+ const result = await queryUnifiedDb(
386
+ `SELECT id, email, username, app_profiles FROM "ultrst-users" WHERE id = $1 OR email = $1 LIMIT 1`,
387
+ [ownerId],
388
+ env
389
+ );
390
+ user = result.rows[0];
391
+ } catch (error) {
392
+ if (!isMissingProfileRelation(error)) throw error;
393
+ }
394
+ if (user) {
395
+ await listUserStorageConnections(
396
+ String(user.id),
397
+ (sql, params) => queryUnifiedDb(sql, params, env)
398
+ );
399
+ const refreshed = await queryUnifiedDb(
400
+ `SELECT id, email, username, app_profiles FROM "ultrst-users" WHERE id = $1 LIMIT 1`,
401
+ [user.id],
402
+ env
403
+ );
404
+ if (refreshed.rows[0]) user = refreshed.rows[0];
405
+ } else {
406
+ try {
407
+ const legacy = await queryUnifiedDb(
408
+ `SELECT id, email, username, app_profiles FROM "srkl_application_profiles" WHERE id = $1 OR email = $1 LIMIT 1`,
409
+ [ownerId],
410
+ env
411
+ );
412
+ user = legacy.rows[0];
413
+ } catch (error) {
414
+ if (!isMissingProfileRelation(error)) throw error;
415
+ }
416
+ }
417
+ if (!user) return { user: null, workspace: null, connection: null };
418
+ const profiles = typeof user.app_profiles === "string" ? JSON.parse(user.app_profiles) : user.app_profiles || {};
419
+ const app = appProfile(profiles, workspaceAppId(env));
420
+ const workspaces = Array.isArray(app.workspaces) ? app.workspaces : [];
421
+ const workspace = workspaces.find((candidate) => candidate.id === workspaceId) || null;
422
+ if (!workspace) return { user: null, workspace: null, connection: null };
423
+ const connection = await resolveWorkspaceConnectionForUser(String(user.id), profiles, workspace, env);
424
+ return { user, workspace, connection };
425
+ }
426
+ async function getWorkspaces(userId, env) {
427
+ if (!userId) {
428
+ return { success: true, workspaces: [], activeWorkspaceId: null, storage_connections: [] };
429
+ }
430
+ let userRow;
431
+ try {
432
+ const canonical = await queryUnifiedDb(
433
+ `SELECT * FROM "ultrst-users" WHERE id = $1 OR email = $1 LIMIT 1`,
434
+ [userId],
435
+ env
436
+ );
437
+ userRow = canonical.rows[0];
438
+ } catch (error) {
439
+ if (!isMissingProfileRelation(error)) throw error;
440
+ }
441
+ const publicConnections = await listUserStorageConnections(
442
+ String(userRow?.id || userId),
443
+ (sql, params) => queryUnifiedDb(sql, params, env)
444
+ );
445
+ if (userRow) {
446
+ const refreshed = await queryUnifiedDb(
447
+ `SELECT * FROM "ultrst-users" WHERE id = $1 LIMIT 1`,
448
+ [userRow.id],
449
+ env
450
+ );
451
+ if (refreshed.rows[0]) userRow = refreshed.rows[0];
452
+ } else {
453
+ try {
454
+ const legacy = await queryUnifiedDb(
455
+ `SELECT * FROM "srkl_application_profiles" WHERE id = $1 OR email = $1 LIMIT 1`,
456
+ [userId],
457
+ env
458
+ );
459
+ userRow = legacy.rows[0];
460
+ } catch (error) {
461
+ if (!isMissingProfileRelation(error)) throw error;
462
+ }
463
+ }
464
+ if (!userRow) {
465
+ return { success: true, workspaces: [], activeWorkspaceId: null, storage_connections: publicConnections };
466
+ }
467
+ const profiles = typeof userRow.app_profiles === "string" ? JSON.parse(userRow.app_profiles) : userRow.app_profiles || {};
468
+ const app = appProfile(profiles, workspaceAppId(env));
469
+ const workspaces = Array.isArray(app.workspaces) ? app.workspaces : [];
470
+ const activeWorkspaceId = app.activeWorkspaceId || null;
471
+ return { success: true, workspaces, activeWorkspaceId, storage_connections: publicConnections };
472
+ }
473
+ async function createWorkspace(userId, wsData, env) {
474
+ await listUserStorageConnections(
475
+ userId,
476
+ (sql, params) => queryUnifiedDb(sql, params, env)
477
+ );
478
+ const uRes = await queryUnifiedDb(`SELECT * FROM "ultrst-users" WHERE id = $1`, [userId], env);
479
+ const user = uRes.rows[0];
480
+ if (!user) throw new Error("User account not found.");
481
+ const profiles = typeof user.app_profiles === "string" ? JSON.parse(user.app_profiles) : user.app_profiles || {};
482
+ const appId = workspaceAppId(env);
483
+ const app = appProfile(profiles, appId);
484
+ const workspaces = Array.isArray(app.workspaces) ? app.workspaces : [];
485
+ const wsName = String(wsData?.name || "New Workspace").trim();
486
+ if (!wsName) throw new Error("Workspace name is required.");
487
+ const wsId = String(wsData?.id || `ws-${appId}-${crypto.randomUUID()}`);
488
+ const userName = String(user.username || user.name || "user");
489
+ const folderKey = `ultrst_${appId}_${userName.toLowerCase().replace(/[^a-z0-9]/g, "_")}_${wsName.toLowerCase().replace(/[^a-z0-9]/g, "_")}`;
490
+ const requestedStorage = wsData?.storage && typeof wsData.storage === "object" ? wsData.storage : {};
491
+ const storageProvider = String(wsData?.storageProvider || requestedStorage.provider || "local_fs").toLowerCase();
492
+ if (!["local_fs", "backblaze_b2", "google_drive"].includes(storageProvider)) {
493
+ throw new Error(`Unsupported workspace storage provider: ${storageProvider}`);
494
+ }
495
+ const storageConnectionId = String(
496
+ wsData?.storageConnectionId || requestedStorage.connectionId || ""
497
+ ).trim();
498
+ let connection = null;
499
+ let bucketName = "";
500
+ let googleRootFolder;
501
+ if (storageProvider !== "local_fs") {
502
+ if (!storageConnectionId) {
503
+ throw new Error(`Select an existing ${storageProvider === "backblaze_b2" ? "Backblaze B2" : "Google Drive"} connection before creating this workspace.`);
504
+ }
505
+ connection = await resolveUserStorageConnectionSecret(
506
+ userId,
507
+ storageConnectionId,
508
+ (sql, params) => queryUnifiedDb(sql, params, env)
509
+ );
510
+ if (!connection || connection.enabled === false || connection.provider !== storageProvider) {
511
+ throw new Error("The selected storage connection is unavailable or does not match the selected provider.");
512
+ }
513
+ connection = { ...connection, __ownerUserId: userId };
514
+ if (storageProvider === "backblaze_b2") {
515
+ const keyId = String(connection.b2KeyId || connection.keyId || connection.accessKeyId || "").trim();
516
+ const applicationKey = String(
517
+ connection.b2ApplicationKey || connection.applicationKey || connection.appKey || connection.secretAccessKey || ""
518
+ ).trim();
519
+ bucketName = String(
520
+ wsData?.b2BucketName || requestedStorage.b2BucketName || requestedStorage.bucketName || connection.b2BucketName || connection.bucketName || ""
521
+ ).trim();
522
+ if (!keyId || !applicationKey) {
523
+ throw new Error("The selected Backblaze connection is missing its server-side credentials.");
524
+ }
525
+ if (!bucketName) throw new Error("Select a Backblaze B2 bucket for this workspace.");
526
+ const validated = await testBackblazeCredentials(keyId, applicationKey);
527
+ if (!validated.success) {
528
+ throw new Error(validated.error || "The selected Backblaze connection could not be validated.");
529
+ }
530
+ if (!validated.buckets.some((bucket) => bucket.name === bucketName)) {
531
+ throw new Error("The selected Backblaze B2 bucket is not accessible to this connection.");
532
+ }
533
+ }
534
+ if (storageProvider === "google_drive") {
535
+ const requestedRootFolderId = String(
536
+ wsData?.googleRootFolderId || requestedStorage.googleRootFolderId || connection.googleRootFolderId || ""
537
+ ).trim();
538
+ if (!requestedRootFolderId) {
539
+ throw new Error("Select a Google Drive folder before creating this workspace.");
540
+ }
541
+ const drive = await createGoogleDriveWorkspaceClient(
542
+ userId,
543
+ storageConnectionId,
544
+ (sql, params) => queryUnifiedDb(sql, params, env),
545
+ requestedRootFolderId
546
+ );
547
+ await drive.getAccountIdentity();
548
+ const folder = await drive.selectRootFolder(requestedRootFolderId);
549
+ googleRootFolder = { id: folder.id, name: folder.name };
550
+ }
551
+ }
552
+ const now = (/* @__PURE__ */ new Date()).toISOString();
553
+ const newWs = {
554
+ id: wsId,
555
+ name: wsName,
556
+ ...typeof wsData?.description === "string" && wsData.description.trim() ? { description: wsData.description.trim() } : {},
557
+ localFolderName: folderKey,
558
+ localFolderKey: folderKey,
559
+ workspacePath: `./${folderKey}`,
560
+ storageProvider,
561
+ ...storageConnectionId ? { storageConnectionId } : {},
562
+ ...storageProvider === "backblaze_b2" ? { b2BucketName: bucketName } : {},
563
+ ...googleRootFolder ? {
564
+ googleRootFolderId: googleRootFolder.id,
565
+ googleRootFolderName: googleRootFolder.name
566
+ } : {},
567
+ createdAt: now,
568
+ updatedAt: now
569
+ };
570
+ workspaces.push(newWs);
571
+ app.workspaces = workspaces;
572
+ app.activeWorkspaceId = wsId;
573
+ await queryUnifiedDb(`UPDATE "ultrst-users" SET app_profiles = $1, updated_at = NOW() WHERE id = $2`, [JSON.stringify(profiles), user.id], env);
574
+ try {
575
+ if (storageProvider !== "local_fs" && !connection) {
576
+ throw new Error("A verified storage connection is required to initialize this workspace.");
577
+ }
578
+ await syncWorkspaceCreateToBucket(newWs, connection, env);
579
+ } catch (error) {
580
+ app.workspaces = workspaces.filter((workspace) => workspace.id !== wsId);
581
+ app.activeWorkspaceId = app.activeWorkspaceId === wsId ? app.workspaces[0]?.id || null : app.activeWorkspaceId;
582
+ await queryUnifiedDb(
583
+ `UPDATE "ultrst-users" SET app_profiles = $1, updated_at = NOW() WHERE id = $2`,
584
+ [JSON.stringify(profiles), user.id],
585
+ env
586
+ );
587
+ throw error;
588
+ }
589
+ return { success: true, workspace: newWs, workspaces: app.workspaces };
590
+ }
591
+ async function updateWorkspace(userId, params, env) {
592
+ await listUserStorageConnections(
593
+ userId,
594
+ (sql, params2) => queryUnifiedDb(sql, params2, env)
595
+ );
596
+ const uRes = await queryUnifiedDb(`SELECT * FROM "ultrst-users" WHERE id = $1`, [userId], env);
597
+ const user = uRes.rows[0];
598
+ if (!user) throw new Error("User not found.");
599
+ const profiles = typeof user.app_profiles === "string" ? JSON.parse(user.app_profiles) : user.app_profiles || {};
600
+ const app = appProfile(profiles, workspaceAppId(env));
601
+ const workspaces = Array.isArray(app.workspaces) ? app.workspaces : [];
602
+ const { action, workspaceId, updates } = params;
603
+ const targetId = workspaceId || updates?.id;
604
+ const match = workspaces.find((w) => w.id === targetId);
605
+ if (!match) throw new Error("Workspace not found.");
606
+ if (action === "switch") {
607
+ app.activeWorkspaceId = targetId;
608
+ } else {
609
+ const safeUpdates = { ...updates || params };
610
+ delete safeUpdates.storageProvider;
611
+ delete safeUpdates.storageConnectionId;
612
+ delete safeUpdates.b2BucketName;
613
+ delete safeUpdates.b2Endpoint;
614
+ delete safeUpdates.b2Region;
615
+ delete safeUpdates.googleRootFolderId;
616
+ delete safeUpdates.googleRootFolderName;
617
+ delete safeUpdates.localFolderName;
618
+ delete safeUpdates.localFolderKey;
619
+ delete safeUpdates.workspacePath;
620
+ delete safeUpdates.primaryStorage;
621
+ delete safeUpdates.id;
622
+ delete safeUpdates.action;
623
+ delete safeUpdates.workspaceId;
624
+ Object.assign(match, safeUpdates, { updatedAt: (/* @__PURE__ */ new Date()).toISOString() });
625
+ }
626
+ await queryUnifiedDb(`UPDATE "ultrst-users" SET app_profiles = $1, updated_at = NOW() WHERE id = $2`, [JSON.stringify(profiles), user.id], env);
627
+ return { success: true, workspace: match, workspaces };
628
+ }
629
+ async function deleteWorkspace(userId, wsId, env) {
630
+ await listUserStorageConnections(
631
+ userId,
632
+ (sql, params) => queryUnifiedDb(sql, params, env)
633
+ );
634
+ const uRes = await queryUnifiedDb(`SELECT * FROM "ultrst-users" WHERE id = $1`, [userId], env);
635
+ const user = uRes.rows[0];
636
+ if (!user) throw new Error("User not found.");
637
+ const profiles = typeof user.app_profiles === "string" ? JSON.parse(user.app_profiles) : user.app_profiles || {};
638
+ const app = appProfile(profiles, workspaceAppId(env));
639
+ if (!app.workspaces) return { success: true, workspaces: [] };
640
+ const targetWs = app.workspaces.find((w) => w.id === wsId);
641
+ const provider = String(targetWs?.storageProvider || "").toLowerCase();
642
+ const requiresOwnedCloudConnection = ["backblaze_b2", "google_drive"].includes(provider);
643
+ const conn = targetWs ? await resolveWorkspaceConnectionForUser(String(user.id), profiles, targetWs, env) : null;
644
+ if (targetWs && requiresOwnedCloudConnection && !conn) {
645
+ throw new Error("The workspace storage connection could not be resolved for its verified owner; deletion was not performed.");
646
+ }
647
+ if (targetWs && conn) {
648
+ await syncWorkspaceDeleteToBucket(targetWs, conn, env);
649
+ }
650
+ app.workspaces = app.workspaces.filter((w) => w.id !== wsId);
651
+ if (app.activeWorkspaceId === wsId) {
652
+ app.activeWorkspaceId = app.workspaces[0]?.id || null;
653
+ }
654
+ if (app.workspace_data?.[wsId]) {
655
+ delete app.workspace_data[wsId];
656
+ }
657
+ await queryUnifiedDb(`UPDATE "ultrst-users" SET app_profiles = $1, updated_at = NOW() WHERE id = $2`, [JSON.stringify(profiles), user.id], env);
658
+ return { success: true, workspaces: app.workspaces };
659
+ }
660
+
661
+ // src/core/workspaceStorageDetailsCore.ts
662
+ async function getWorkspaceStorageDetails(workspaceId, env, verifiedUserId) {
663
+ if (!workspaceId) return { success: false, error: "workspaceId is required" };
664
+ const ownerId = String(verifiedUserId || "").trim();
665
+ if (!ownerId) return { success: false, error: "A verified workspace owner is required." };
666
+ const { workspace, connection } = await findUserWorkspace(workspaceId, env, ownerId);
667
+ if (!workspace) return { success: false, error: "Workspace was not found for this owner." };
668
+ const safeConnection = connection ? toPublicStorageConnection(connection) : null;
669
+ const folderPrefix = workspace?.localFolderKey || workspace?.localFolderName || (workspace?.workspacePath ? workspace.workspacePath.replace(/^\.\//, "") : workspaceId);
670
+ if (!connection || connection.provider !== "backblaze_b2" && connection.provider !== "BACKBLAZE_B2") {
671
+ return {
672
+ success: true,
673
+ workspaceId,
674
+ storageProvider: workspace?.storageProvider || "local_fs",
675
+ connection: safeConnection,
676
+ folderPrefix,
677
+ localStats: { exists: false, appsCount: 0, ecosystemsCount: 0 },
678
+ bucket: null,
679
+ files: []
680
+ };
681
+ }
682
+ const keyId = connection.b2KeyId || connection.keyId;
683
+ const applicationKey = connection.b2ApplicationKey || connection.appKey;
684
+ const bucketName = connection.b2BucketName || workspace.b2BucketName || "ultrst-apps";
685
+ try {
686
+ const buckets = await b2ListBuckets(keyId, applicationKey, void 0, bucketName);
687
+ const bucketObj = buckets.find((b) => b.bucketName === bucketName);
688
+ if (!bucketObj) {
689
+ return {
690
+ success: true,
691
+ workspaceId,
692
+ storageProvider: "backblaze_b2",
693
+ connection: safeConnection,
694
+ folderPrefix,
695
+ bucket: { name: bucketName, status: "BUCKET_NOT_FOUND" },
696
+ files: []
697
+ };
698
+ }
699
+ const rawFiles = await b2ListFileNames(keyId, applicationKey, bucketName, `${folderPrefix}/`);
700
+ return {
701
+ success: true,
702
+ workspaceId,
703
+ storageProvider: "backblaze_b2",
704
+ connection: { id: connection.id, label: connection.label, provider: connection.provider },
705
+ folderPrefix,
706
+ bucket: {
707
+ id: bucketObj.bucketId,
708
+ name: bucketObj.bucketName,
709
+ type: bucketObj.bucketType,
710
+ endpoint: connection.b2Endpoint || "s3.eu-central-003.backblazeb2.com",
711
+ region: connection.b2Region || "eu-central-003",
712
+ status: "CONNECTED"
713
+ },
714
+ fileCount: rawFiles.length,
715
+ files: rawFiles.map((f) => ({
716
+ fileName: f.fileName,
717
+ sizeBytes: f.contentLength,
718
+ uploadTimestamp: f.uploadTimestamp
719
+ }))
720
+ };
721
+ } catch (err) {
722
+ return {
723
+ success: false,
724
+ workspaceId,
725
+ storageProvider: "backblaze_b2",
726
+ error: "Unable to inspect workspace storage. Verify the selected connection and try again.",
727
+ folderPrefix
728
+ };
729
+ }
730
+ }
731
+
732
+ export {
733
+ resolveWorkspaceConnection,
734
+ syncWorkspaceCreateToBucket,
735
+ syncWorkspaceDeleteToBucket,
736
+ syncWorkspaceDataToBucket,
737
+ loadWorkspaceData,
738
+ saveWorkspaceData,
739
+ renameAppInWorkspaceData,
740
+ getWorkspaceStorageDetails,
741
+ findUserWorkspace,
742
+ getWorkspaces,
743
+ createWorkspace,
744
+ updateWorkspace,
745
+ deleteWorkspace
746
+ };