@ultrst-armada/kloks 2.0.4 → 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 +636 -456
  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
@@ -1,570 +0,0 @@
1
- import {
2
- b2DeleteFileVersion,
3
- b2DeleteFolder,
4
- b2DownloadFile,
5
- b2ListBuckets,
6
- b2ListFileNames,
7
- b2UploadFile,
8
- queryUnifiedDb
9
- } from "./chunk-JCMB7BIM.js";
10
-
11
- // src/core/workspaceFileCore.ts
12
- async function getFs() {
13
- if (typeof process !== "undefined" && process.versions?.node) {
14
- try {
15
- const mod = await import("fs");
16
- return mod.promises || mod.default?.promises || mod;
17
- } catch {
18
- }
19
- }
20
- return null;
21
- }
22
- async function getPath() {
23
- if (typeof process !== "undefined" && process.versions?.node) {
24
- try {
25
- const mod = await import("path");
26
- return mod.default || mod;
27
- } catch {
28
- }
29
- }
30
- return null;
31
- }
32
- function getWorkspaceFolderPrefix(workspace) {
33
- return workspace.localFolderKey || workspace.localFolderName || (workspace.workspacePath ? workspace.workspacePath.replace(/^\.\//, "") : workspace.id);
34
- }
35
- function isB2Workspace(workspace, connection) {
36
- return connection?.provider === "backblaze_b2" || connection?.provider === "BACKBLAZE_B2" || workspace?.storageProvider === "backblaze_b2";
37
- }
38
- async function writeWorkspaceFile(workspace, connection, relativePath, content, contentType = "application/json") {
39
- const cleanRel = relativePath.replace(/^\/+/, "");
40
- const prefix = getWorkspaceFolderPrefix(workspace);
41
- const buffer = typeof content === "string" ? new TextEncoder().encode(content) : content;
42
- if (isB2Workspace(workspace, connection)) {
43
- const keyId = connection.b2KeyId || connection.keyId;
44
- const appKey = connection.b2ApplicationKey || connection.appKey;
45
- const bucketName = connection.b2BucketName || workspace.b2BucketName || "ultrst-apps";
46
- const fullKey = `${prefix}/${cleanRel}`;
47
- await b2UploadFile(keyId, appKey, bucketName, fullKey, buffer, contentType);
48
- return;
49
- }
50
- const fs = await getFs();
51
- const path = await getPath();
52
- if (!fs || !path) throw new Error("Local filesystem operations not supported in this runtime.");
53
- const localDir = path.resolve(process.cwd(), prefix, path.dirname(cleanRel));
54
- await fs.mkdir(localDir, { recursive: true });
55
- await fs.writeFile(path.resolve(process.cwd(), prefix, cleanRel), buffer);
56
- }
57
- async function readWorkspaceFile(workspace, connection, relativePath) {
58
- const cleanRel = relativePath.replace(/^\/+/, "");
59
- const prefix = getWorkspaceFolderPrefix(workspace);
60
- if (isB2Workspace(workspace, connection)) {
61
- const keyId = connection.b2KeyId || connection.keyId;
62
- const appKey = connection.b2ApplicationKey || connection.appKey;
63
- const bucketName = connection.b2BucketName || workspace.b2BucketName || "ultrst-apps";
64
- const fullKey = `${prefix}/${cleanRel}`;
65
- return await b2DownloadFile(keyId, appKey, bucketName, fullKey);
66
- }
67
- const fs = await getFs();
68
- const path = await getPath();
69
- if (!fs || !path) return null;
70
- const fullPath = path.resolve(process.cwd(), prefix, cleanRel);
71
- try {
72
- const buf = await fs.readFile(fullPath);
73
- return new Uint8Array(buf);
74
- } catch {
75
- return null;
76
- }
77
- }
78
- async function deleteWorkspaceFile(workspace, connection, relativePath) {
79
- const cleanRel = relativePath.replace(/^\/+/, "");
80
- const prefix = getWorkspaceFolderPrefix(workspace);
81
- if (isB2Workspace(workspace, connection)) {
82
- const keyId = connection.b2KeyId || connection.keyId;
83
- const appKey = connection.b2ApplicationKey || connection.appKey;
84
- const bucketName = connection.b2BucketName || workspace.b2BucketName || "ultrst-apps";
85
- const fullKey = `${prefix}/${cleanRel}`;
86
- const files = await b2ListFileNames(keyId, appKey, bucketName, fullKey);
87
- const match = files.find((f) => f.fileName === fullKey);
88
- if (match) {
89
- await b2DeleteFileVersion(keyId, appKey, match.fileName, match.fileId);
90
- return true;
91
- }
92
- return false;
93
- }
94
- const fs = await getFs();
95
- const path = await getPath();
96
- if (!fs || !path) return false;
97
- const fullPath = path.resolve(process.cwd(), prefix, cleanRel);
98
- try {
99
- await fs.unlink(fullPath);
100
- return true;
101
- } catch {
102
- return false;
103
- }
104
- }
105
- async function listWorkspaceFiles(workspace, connection, subPrefix = "") {
106
- const folderPrefix = getWorkspaceFolderPrefix(workspace);
107
- const targetPrefix = subPrefix ? `${folderPrefix}/${subPrefix.replace(/^\/+/, "")}` : `${folderPrefix}/`;
108
- if (isB2Workspace(workspace, connection)) {
109
- const keyId = connection.b2KeyId || connection.keyId;
110
- const appKey = connection.b2ApplicationKey || connection.appKey;
111
- const bucketName = connection.b2BucketName || workspace.b2BucketName || "ultrst-apps";
112
- const rawFiles = await b2ListFileNames(keyId, appKey, bucketName, targetPrefix);
113
- return rawFiles.map((f) => ({
114
- fileName: f.fileName.slice(folderPrefix.length + 1),
115
- sizeBytes: f.contentLength,
116
- uploadTimestamp: f.uploadTimestamp
117
- }));
118
- }
119
- const fs = await getFs();
120
- const path = await getPath();
121
- if (!fs || !path) return [];
122
- const baseDir = path.resolve(process.cwd(), folderPrefix, subPrefix);
123
- try {
124
- const entries = await fs.readdir(baseDir, { withFileTypes: true, recursive: true });
125
- const result = [];
126
- for (const entry of entries) {
127
- if (entry.isFile()) {
128
- const full = path.join(entry.parentPath || baseDir, entry.name);
129
- const st = await fs.stat(full);
130
- result.push({
131
- fileName: path.relative(path.resolve(process.cwd(), folderPrefix), full),
132
- sizeBytes: st.size
133
- });
134
- }
135
- }
136
- return result;
137
- } catch {
138
- return [];
139
- }
140
- }
141
- async function deleteWorkspaceFolder(workspace, connection) {
142
- const prefix = getWorkspaceFolderPrefix(workspace);
143
- if (isB2Workspace(workspace, connection)) {
144
- const keyId = connection.b2KeyId || connection.keyId;
145
- const appKey = connection.b2ApplicationKey || connection.appKey;
146
- const bucketName = connection.b2BucketName || workspace.b2BucketName || "ultrst-apps";
147
- await b2DeleteFolder(keyId, appKey, bucketName, prefix);
148
- return;
149
- }
150
- const fs = await getFs();
151
- const path = await getPath();
152
- if (!fs || !path) return;
153
- const localDir = path.resolve(process.cwd(), prefix);
154
- try {
155
- await fs.rm(localDir, { recursive: true, force: true });
156
- } catch {
157
- }
158
- }
159
-
160
- // src/core/workspaceBucketSyncCore.ts
161
- function resolveWorkspaceConnection(profiles, workspace) {
162
- const depm = profiles.depm || {};
163
- const conns = depm.storage_connections?.length ? depm.storage_connections : profiles.srkl?.storage_connections || profiles.docustack?.storage_connections || [];
164
- return conns.find((c) => c.id === workspace.storageConnectionId) || conns.find((c) => c.role === "primary") || conns[0] || null;
165
- }
166
- async function syncWorkspaceCreateToBucket(workspace, connection, env) {
167
- if (!connection || connection.provider !== "backblaze_b2" && connection.provider !== "BACKBLAZE_B2") return;
168
- try {
169
- const wsMeta = {
170
- id: workspace.id,
171
- name: workspace.name,
172
- createdAt: workspace.createdAt,
173
- updatedAt: workspace.updatedAt,
174
- storageProvider: "backblaze_b2",
175
- bucket: connection.b2BucketName || "ultrst-apps"
176
- };
177
- await writeWorkspaceFile(workspace, connection, ".bzEmpty", new Uint8Array(0), "application/x-empty");
178
- await writeWorkspaceFile(workspace, connection, "workspace.json", JSON.stringify(wsMeta, null, 2), "application/json");
179
- await writeWorkspaceFile(
180
- workspace,
181
- connection,
182
- "ecosystem.json",
183
- JSON.stringify({ apps: [], nodes: [], edges: [], ecosystems: [] }, null, 2),
184
- "application/json"
185
- );
186
- } catch (err) {
187
- console.warn("[WorkspaceBucketSync] Create sync error:", err.message);
188
- }
189
- }
190
- async function syncWorkspaceDeleteToBucket(workspace, connection, env) {
191
- if (!connection || connection.provider !== "backblaze_b2" && connection.provider !== "BACKBLAZE_B2") return;
192
- try {
193
- await deleteWorkspaceFolder(workspace, connection);
194
- } catch (err) {
195
- console.warn("[WorkspaceBucketSync] Delete sync error:", err.message);
196
- }
197
- }
198
- async function syncWorkspaceDataToBucket(workspace, connection, data, env) {
199
- if (!connection || connection.provider !== "backblaze_b2" && connection.provider !== "BACKBLAZE_B2") return;
200
- try {
201
- await writeWorkspaceFile(workspace, connection, "ecosystem.json", JSON.stringify(data, null, 2), "application/json");
202
- } catch (err) {
203
- console.warn("[WorkspaceBucketSync] Data sync error:", err.message);
204
- }
205
- }
206
-
207
- // src/core/workspaceDataCore.ts
208
- async function resolveUserRow(userId, env) {
209
- if (userId) {
210
- const res = await queryUnifiedDb(`SELECT * FROM "ultrst-users" WHERE id = $1 OR email = $1 LIMIT 1`, [userId], env);
211
- if (res.rows.length > 0) return res.rows[0];
212
- }
213
- return null;
214
- }
215
- async function loadWorkspaceData(userId, workspaceId, env) {
216
- if (!workspaceId) return { success: false, error: "workspaceId required", workspace: null };
217
- const user = await resolveUserRow(userId, env);
218
- if (!user) return { success: false, error: "User not found", workspace: null };
219
- const profiles = typeof user.app_profiles === "string" ? JSON.parse(user.app_profiles) : user.app_profiles || {};
220
- const depm = profiles.depm || {};
221
- const workspaceDataMap = depm.workspace_data || {};
222
- let data = workspaceDataMap[workspaceId];
223
- const isEmptyData = !data || (!data.nodes || data.nodes.length === 0) && (!data.apps || data.apps.length === 0);
224
- if (isEmptyData) {
225
- const ws = (depm.workspaces || []).find((w) => w.id === workspaceId);
226
- if (ws) {
227
- const conn = resolveWorkspaceConnection(profiles, ws);
228
- if (conn) {
229
- try {
230
- const fileBuf = await readWorkspaceFile(ws, conn, "ecosystem.json");
231
- if (fileBuf && fileBuf.length > 0) {
232
- const parsed = JSON.parse(new TextDecoder().decode(fileBuf));
233
- if (parsed.nodes && parsed.nodes.length > 0 || parsed.apps && parsed.apps.length > 0) {
234
- if (!profiles.depm) profiles.depm = {};
235
- if (!profiles.depm.workspace_data) profiles.depm.workspace_data = {};
236
- profiles.depm.workspace_data[workspaceId] = parsed;
237
- data = parsed;
238
- await queryUnifiedDb(
239
- `UPDATE "ultrst-users" SET app_profiles = $1, updated_at = NOW() WHERE id = $2`,
240
- [JSON.stringify(profiles), user.id],
241
- env
242
- );
243
- return { success: true, workspace: data, workspaceId };
244
- }
245
- }
246
- } catch (err) {
247
- console.warn("[WorkspaceDataCore] Storage recovery check:", err.message);
248
- }
249
- }
250
- }
251
- }
252
- if (!data) {
253
- const ws = (depm.workspaces || []).find((w) => w.id === workspaceId);
254
- const ecoName = ws?.ecosystemName || `${ws?.name || "Workspace"} Ecosystem`;
255
- const fallback = {
256
- apps: [],
257
- accounts: [],
258
- deployments: [],
259
- nodes: [],
260
- edges: [],
261
- ecosystems: [
262
- {
263
- id: `eco_${workspaceId}`,
264
- name: ecoName,
265
- icon: "Globe",
266
- health: "HEALTHY",
267
- status: "SYSTEM ONLINE",
268
- connectedAppsCount: 0,
269
- meshLinkCount: 0,
270
- createdAt: (/* @__PURE__ */ new Date()).toISOString(),
271
- updatedAt: (/* @__PURE__ */ new Date()).toISOString()
272
- }
273
- ],
274
- ecosystemName: ecoName,
275
- ecosystemNodes: [
276
- {
277
- id: `node_eco_root_${workspaceId}`,
278
- type: "ECOSYSTEM",
279
- name: ecoName,
280
- x: 0,
281
- y: 0,
282
- appId: "__ecosystem__",
283
- icon: "Globe",
284
- ecosystemData: { connectedAppsCount: 0, health: "HEALTHY", status: "SYSTEM ONLINE" }
285
- }
286
- ],
287
- ecosystemEdges: []
288
- };
289
- return { success: true, workspace: fallback, workspaceId };
290
- }
291
- return { success: true, workspace: data, workspaceId };
292
- }
293
- async function saveWorkspaceData(userId, workspaceId, data, env) {
294
- if (!workspaceId) return { success: false, error: "workspaceId required" };
295
- const user = await resolveUserRow(userId, env);
296
- if (!user) return { success: false, error: "User not found" };
297
- const profiles = typeof user.app_profiles === "string" ? JSON.parse(user.app_profiles) : user.app_profiles || {};
298
- if (!profiles.depm) profiles.depm = {};
299
- if (!profiles.depm.workspace_data) profiles.depm.workspace_data = {};
300
- const existing = profiles.depm.workspace_data[workspaceId];
301
- const incomingEmpty = (!data.nodes || data.nodes.length === 0) && (!data.apps || data.apps.length === 0);
302
- const existingHasData = existing && (existing.nodes && existing.nodes.length > 0 || existing.apps && existing.apps.length > 0);
303
- if (incomingEmpty && existingHasData && !data._forceEmptySave) {
304
- console.warn(`[WorkspaceDataCore] Blocked empty overwrite for workspace ${workspaceId}.`);
305
- return { success: true, workspaceId, workspace: existing, protected: true };
306
- }
307
- profiles.depm.workspace_data[workspaceId] = data;
308
- if (Array.isArray(profiles.depm.workspaces)) {
309
- const ws2 = profiles.depm.workspaces.find((w) => w.id === workspaceId);
310
- if (ws2) {
311
- ws2.appsCount = Array.isArray(data.apps) ? data.apps.length : 0;
312
- ws2.updatedAt = (/* @__PURE__ */ new Date()).toISOString();
313
- }
314
- }
315
- await queryUnifiedDb(
316
- `UPDATE "ultrst-users" SET app_profiles = $1, updated_at = NOW() WHERE id = $2`,
317
- [JSON.stringify(profiles), user.id],
318
- env
319
- );
320
- const ws = Array.isArray(profiles.depm?.workspaces) ? profiles.depm.workspaces.find((w) => w.id === workspaceId) : null;
321
- if (ws) {
322
- const conn = resolveWorkspaceConnection(profiles, ws);
323
- await syncWorkspaceDataToBucket(ws, conn, data, env);
324
- }
325
- return { success: true, workspaceId, workspace: data };
326
- }
327
- async function renameAppInWorkspaceData(userId, workspaceId, appId, newName, env) {
328
- if (!workspaceId || !appId || !newName) {
329
- return { success: false, error: "workspaceId, appId and newName required" };
330
- }
331
- const loadRes = await loadWorkspaceData(userId, workspaceId, env);
332
- if (!loadRes.success || !loadRes.workspace) return loadRes;
333
- const wsData = loadRes.workspace;
334
- const trimmed = newName.trim();
335
- const folderName = trimmed.replace(/[/\\?%*:|"<>]/g, "_");
336
- if (Array.isArray(wsData.apps)) {
337
- const targetApp = wsData.apps.find((a) => a.id === appId);
338
- if (targetApp) {
339
- targetApp.name = trimmed;
340
- targetApp.folderName = folderName;
341
- targetApp.updatedAt = (/* @__PURE__ */ new Date()).toISOString();
342
- }
343
- }
344
- if (Array.isArray(wsData.nodes)) {
345
- wsData.nodes = wsData.nodes.map((n) => {
346
- if (n.appId === appId && (n.type === "APP" || n.type === "APP_NODE" || n.type === "APP_GRAPH_NODE")) {
347
- return { ...n, name: trimmed, appData: n.appData ? { ...n.appData, name: trimmed, folderName } : void 0 };
348
- }
349
- return n;
350
- });
351
- }
352
- return await saveWorkspaceData(userId, workspaceId, wsData, env);
353
- }
354
-
355
- // src/core/workspaceCore.ts
356
- function workspaceAppId(env) {
357
- const value = String(env?.WORKSPACE_APP_ID ?? "depm").trim().toLowerCase();
358
- return value || "depm";
359
- }
360
- function appProfile(profiles, appId) {
361
- if (!profiles[appId] || typeof profiles[appId] !== "object") profiles[appId] = {};
362
- return profiles[appId];
363
- }
364
- async function findUserWorkspace(workspaceId, env) {
365
- const res = await queryUnifiedDb(`SELECT id, email, username, app_profiles FROM "ultrst-users"`, [], env);
366
- for (const user of res.rows) {
367
- const profiles = typeof user.app_profiles === "string" ? JSON.parse(user.app_profiles) : user.app_profiles || {};
368
- const app = appProfile(profiles, workspaceAppId(env));
369
- const workspaces = Array.isArray(app.workspaces) ? app.workspaces : [];
370
- const ws = workspaces.find((w) => w.id === workspaceId);
371
- if (ws) {
372
- const conns = app.storage_connections || profiles.srkl?.storage_connections || profiles.docustack?.storage_connections || [];
373
- const conn = conns.find((c) => c.id === ws.storageConnectionId) || conns.find((c) => c.role === "primary") || conns[0] || null;
374
- return { user, workspace: ws, connection: conn };
375
- }
376
- }
377
- return { user: null, workspace: null, connection: null };
378
- }
379
- async function getWorkspaces(userId, env) {
380
- if (!userId) {
381
- return { success: true, workspaces: [], activeWorkspaceId: null, storage_connections: [] };
382
- }
383
- const res = await queryUnifiedDb(`SELECT * FROM "ultrst-users" WHERE id = $1 OR email = $1 LIMIT 1`, [userId], env);
384
- const userRow = res.rows[0];
385
- if (!userRow) {
386
- return { success: true, workspaces: [], activeWorkspaceId: null, storage_connections: [] };
387
- }
388
- const profiles = typeof userRow.app_profiles === "string" ? JSON.parse(userRow.app_profiles) : userRow.app_profiles || {};
389
- const app = appProfile(profiles, workspaceAppId(env));
390
- const workspaces = Array.isArray(app.workspaces) ? app.workspaces : [];
391
- const activeWorkspaceId = app.activeWorkspaceId || null;
392
- const conns = app.storage_connections?.length ? app.storage_connections : profiles.srkl?.storage_connections || [];
393
- return { success: true, workspaces, activeWorkspaceId, storage_connections: conns };
394
- }
395
- async function createWorkspace(userId, wsData, env) {
396
- const uRes = await queryUnifiedDb(`SELECT * FROM "ultrst-users" WHERE id = $1`, [userId], env);
397
- const user = uRes.rows[0];
398
- if (!user) throw new Error("User account not found.");
399
- const profiles = typeof user.app_profiles === "string" ? JSON.parse(user.app_profiles) : user.app_profiles || {};
400
- const app = appProfile(profiles, workspaceAppId(env));
401
- const workspaces = Array.isArray(app.workspaces) ? app.workspaces : [];
402
- const appId = workspaceAppId(env);
403
- const wsName = (wsData.name || "New Workspace").trim();
404
- const wsId = wsData.id || `ws-${appId}-${Date.now()}`;
405
- const userName = user.username || user.name || "user";
406
- const folderKey = `ultrst_${appId}_${userName.toLowerCase().replace(/[^a-z0-9]/g, "_")}_${wsName.toLowerCase().replace(/[^a-z0-9]/g, "_")}`;
407
- const newWs = {
408
- ...wsData,
409
- id: wsId,
410
- name: wsName,
411
- localFolderName: folderKey,
412
- localFolderKey: folderKey,
413
- workspacePath: `./${folderKey}`,
414
- storageProvider: wsData.storageProvider || "backblaze_b2",
415
- b2BucketName: wsData.b2BucketName || void 0,
416
- createdAt: (/* @__PURE__ */ new Date()).toISOString(),
417
- updatedAt: (/* @__PURE__ */ new Date()).toISOString()
418
- };
419
- workspaces.push(newWs);
420
- app.workspaces = workspaces;
421
- app.activeWorkspaceId = wsId;
422
- await queryUnifiedDb(`UPDATE "ultrst-users" SET app_profiles = $1, updated_at = NOW() WHERE id = $2`, [JSON.stringify(profiles), user.id], env);
423
- const conn = resolveWorkspaceConnection(profiles, newWs);
424
- await syncWorkspaceCreateToBucket(newWs, conn, env);
425
- return { success: true, workspace: newWs, workspaces };
426
- }
427
- async function updateWorkspace(userId, params, env) {
428
- const uRes = await queryUnifiedDb(`SELECT * FROM "ultrst-users" WHERE id = $1`, [userId], env);
429
- const user = uRes.rows[0];
430
- if (!user) throw new Error("User not found.");
431
- const profiles = typeof user.app_profiles === "string" ? JSON.parse(user.app_profiles) : user.app_profiles || {};
432
- const app = appProfile(profiles, workspaceAppId(env));
433
- const workspaces = Array.isArray(app.workspaces) ? app.workspaces : [];
434
- const { action, workspaceId, updates } = params;
435
- const targetId = workspaceId || updates?.id;
436
- const match = workspaces.find((w) => w.id === targetId);
437
- if (!match) throw new Error("Workspace not found.");
438
- if (action === "switch") {
439
- app.activeWorkspaceId = targetId;
440
- } else {
441
- const safeUpdates = { ...updates || params };
442
- delete safeUpdates.storageProvider;
443
- delete safeUpdates.storageConnectionId;
444
- delete safeUpdates.b2BucketName;
445
- delete safeUpdates.b2Endpoint;
446
- delete safeUpdates.b2Region;
447
- delete safeUpdates.localFolderName;
448
- delete safeUpdates.localFolderKey;
449
- delete safeUpdates.workspacePath;
450
- delete safeUpdates.primaryStorage;
451
- delete safeUpdates.id;
452
- delete safeUpdates.action;
453
- delete safeUpdates.workspaceId;
454
- Object.assign(match, safeUpdates, { updatedAt: (/* @__PURE__ */ new Date()).toISOString() });
455
- }
456
- await queryUnifiedDb(`UPDATE "ultrst-users" SET app_profiles = $1, updated_at = NOW() WHERE id = $2`, [JSON.stringify(profiles), user.id], env);
457
- return { success: true, workspace: match, workspaces };
458
- }
459
- async function deleteWorkspace(userId, wsId, env) {
460
- const uRes = await queryUnifiedDb(`SELECT * FROM "ultrst-users" WHERE id = $1`, [userId], env);
461
- const user = uRes.rows[0];
462
- if (!user) throw new Error("User not found.");
463
- const profiles = typeof user.app_profiles === "string" ? JSON.parse(user.app_profiles) : user.app_profiles || {};
464
- const app = appProfile(profiles, workspaceAppId(env));
465
- if (!app.workspaces) return { success: true, workspaces: [] };
466
- const targetWs = app.workspaces.find((w) => w.id === wsId);
467
- const conn = targetWs ? resolveWorkspaceConnection(profiles, targetWs) : null;
468
- app.workspaces = app.workspaces.filter((w) => w.id !== wsId);
469
- if (app.activeWorkspaceId === wsId) {
470
- app.activeWorkspaceId = app.workspaces[0]?.id || null;
471
- }
472
- if (app.workspace_data?.[wsId]) {
473
- delete app.workspace_data[wsId];
474
- }
475
- await queryUnifiedDb(`UPDATE "ultrst-users" SET app_profiles = $1, updated_at = NOW() WHERE id = $2`, [JSON.stringify(profiles), user.id], env);
476
- if (targetWs && conn) {
477
- await syncWorkspaceDeleteToBucket(targetWs, conn, env);
478
- }
479
- return { success: true, workspaces: app.workspaces };
480
- }
481
-
482
- // src/core/workspaceStorageDetailsCore.ts
483
- async function getWorkspaceStorageDetails(workspaceId, env) {
484
- if (!workspaceId) return { success: false, error: "workspaceId is required" };
485
- const { workspace, connection } = await findUserWorkspace(workspaceId, env);
486
- const folderPrefix = workspace?.localFolderKey || workspace?.localFolderName || (workspace?.workspacePath ? workspace.workspacePath.replace(/^\.\//, "") : workspaceId);
487
- if (!connection || connection.provider !== "backblaze_b2" && connection.provider !== "BACKBLAZE_B2") {
488
- return {
489
- success: true,
490
- workspaceId,
491
- storageProvider: workspace?.storageProvider || "local_fs",
492
- connection: connection || null,
493
- folderPrefix,
494
- localStats: { exists: false, appsCount: 0, ecosystemsCount: 0 },
495
- bucket: null,
496
- files: []
497
- };
498
- }
499
- const keyId = connection.b2KeyId || connection.keyId;
500
- const applicationKey = connection.b2ApplicationKey || connection.appKey;
501
- const bucketName = connection.b2BucketName || workspace.b2BucketName || "ultrst-apps";
502
- try {
503
- const buckets = await b2ListBuckets(keyId, applicationKey, void 0, bucketName);
504
- const bucketObj = buckets.find((b) => b.bucketName === bucketName);
505
- if (!bucketObj) {
506
- return {
507
- success: true,
508
- workspaceId,
509
- storageProvider: "backblaze_b2",
510
- connection: { id: connection.id, label: connection.label, provider: connection.provider },
511
- folderPrefix,
512
- bucket: { name: bucketName, status: "BUCKET_NOT_FOUND" },
513
- files: []
514
- };
515
- }
516
- const rawFiles = await b2ListFileNames(keyId, applicationKey, bucketName, `${folderPrefix}/`);
517
- return {
518
- success: true,
519
- workspaceId,
520
- storageProvider: "backblaze_b2",
521
- connection: { id: connection.id, label: connection.label, provider: connection.provider },
522
- folderPrefix,
523
- bucket: {
524
- id: bucketObj.bucketId,
525
- name: bucketObj.bucketName,
526
- type: bucketObj.bucketType,
527
- endpoint: connection.b2Endpoint || "s3.eu-central-003.backblazeb2.com",
528
- region: connection.b2Region || "eu-central-003",
529
- status: "CONNECTED"
530
- },
531
- fileCount: rawFiles.length,
532
- files: rawFiles.map((f) => ({
533
- fileName: f.fileName,
534
- sizeBytes: f.contentLength,
535
- uploadTimestamp: f.uploadTimestamp
536
- }))
537
- };
538
- } catch (err) {
539
- return {
540
- success: false,
541
- workspaceId,
542
- storageProvider: "backblaze_b2",
543
- error: err.message,
544
- folderPrefix
545
- };
546
- }
547
- }
548
-
549
- export {
550
- getWorkspaceFolderPrefix,
551
- isB2Workspace,
552
- writeWorkspaceFile,
553
- readWorkspaceFile,
554
- deleteWorkspaceFile,
555
- listWorkspaceFiles,
556
- deleteWorkspaceFolder,
557
- resolveWorkspaceConnection,
558
- syncWorkspaceCreateToBucket,
559
- syncWorkspaceDeleteToBucket,
560
- syncWorkspaceDataToBucket,
561
- loadWorkspaceData,
562
- saveWorkspaceData,
563
- renameAppInWorkspaceData,
564
- getWorkspaceStorageDetails,
565
- findUserWorkspace,
566
- getWorkspaces,
567
- createWorkspace,
568
- updateWorkspace,
569
- deleteWorkspace
570
- };