skillverse 0.1.0 → 0.1.2

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 (77) hide show
  1. package/dist/bin.js +2421 -0
  2. package/dist/bin.js.map +1 -0
  3. package/dist/index.js +1907 -0
  4. package/dist/index.js.map +1 -0
  5. package/package.json +52 -26
  6. package/prisma/dev.db +0 -0
  7. package/.prettierrc +0 -10
  8. package/README.md +0 -369
  9. package/client/README.md +0 -73
  10. package/client/eslint.config.js +0 -23
  11. package/client/index.html +0 -13
  12. package/client/package.json +0 -41
  13. package/client/postcss.config.js +0 -6
  14. package/client/src/App.css +0 -42
  15. package/client/src/App.tsx +0 -26
  16. package/client/src/assets/react.svg +0 -1
  17. package/client/src/components/AddSkillDialog.tsx +0 -249
  18. package/client/src/components/Layout.tsx +0 -134
  19. package/client/src/components/LinkWorkspaceDialog.tsx +0 -196
  20. package/client/src/components/LoadingSpinner.tsx +0 -57
  21. package/client/src/components/SkillCard.tsx +0 -269
  22. package/client/src/components/Toast.tsx +0 -44
  23. package/client/src/components/Tooltip.tsx +0 -132
  24. package/client/src/index.css +0 -168
  25. package/client/src/lib/api.ts +0 -196
  26. package/client/src/main.tsx +0 -10
  27. package/client/src/pages/Dashboard.tsx +0 -209
  28. package/client/src/pages/Marketplace.tsx +0 -282
  29. package/client/src/pages/Settings.tsx +0 -136
  30. package/client/src/pages/SkillLibrary.tsx +0 -163
  31. package/client/src/pages/Workspaces.tsx +0 -662
  32. package/client/src/stores/appStore.ts +0 -222
  33. package/client/tailwind.config.js +0 -82
  34. package/client/tsconfig.app.json +0 -28
  35. package/client/tsconfig.json +0 -7
  36. package/client/tsconfig.node.json +0 -26
  37. package/client/vite.config.ts +0 -26
  38. package/registry/.env.example +0 -5
  39. package/registry/Dockerfile +0 -42
  40. package/registry/docker-compose.yml +0 -33
  41. package/registry/package.json +0 -37
  42. package/registry/prisma/schema.prisma +0 -59
  43. package/registry/src/index.ts +0 -34
  44. package/registry/src/lib/db.ts +0 -3
  45. package/registry/src/middleware/errorHandler.ts +0 -35
  46. package/registry/src/routes/auth.ts +0 -152
  47. package/registry/src/routes/skills.ts +0 -295
  48. package/registry/tsconfig.json +0 -23
  49. package/server/.env.example +0 -11
  50. package/server/package.json +0 -60
  51. package/server/public/vite.svg +0 -1
  52. package/server/src/bin.ts +0 -428
  53. package/server/src/config.ts +0 -39
  54. package/server/src/index.ts +0 -112
  55. package/server/src/lib/db.ts +0 -14
  56. package/server/src/middleware/errorHandler.ts +0 -40
  57. package/server/src/middleware/logger.ts +0 -12
  58. package/server/src/routes/dashboard.ts +0 -102
  59. package/server/src/routes/marketplace.ts +0 -273
  60. package/server/src/routes/skills.ts +0 -294
  61. package/server/src/routes/workspaces.ts +0 -168
  62. package/server/src/services/bundleService.ts +0 -123
  63. package/server/src/services/skillService.ts +0 -722
  64. package/server/src/services/workspaceService.ts +0 -521
  65. package/server/src/verify-sync.ts +0 -91
  66. package/server/tsconfig.json +0 -19
  67. package/server/tsup.config.ts +0 -18
  68. package/shared/package.json +0 -21
  69. package/shared/pnpm-lock.yaml +0 -24
  70. package/shared/src/index.ts +0 -169
  71. package/shared/tsconfig.json +0 -10
  72. package/tsconfig.json +0 -25
  73. /package/{server/prisma → prisma}/schema.prisma +0 -0
  74. /package/{server/public → public}/assets/index-BsYtpZSa.css +0 -0
  75. /package/{server/public → public}/assets/index-Dfr_6UV8.js +0 -0
  76. /package/{server/public → public}/index.html +0 -0
  77. /package/{client/public → public}/vite.svg +0 -0
package/dist/index.js ADDED
@@ -0,0 +1,1907 @@
1
+ // src/index.ts
2
+ import express from "express";
3
+ import cors from "cors";
4
+ import dotenv2 from "dotenv";
5
+ import { fileURLToPath as fileURLToPath2 } from "url";
6
+ import { dirname as dirname2, join as join6 } from "path";
7
+ import { mkdir as mkdir5 } from "fs/promises";
8
+ import { existsSync as existsSync7 } from "fs";
9
+
10
+ // src/routes/skills.ts
11
+ import { Router } from "express";
12
+ import multer from "multer";
13
+ import { join as join4 } from "path";
14
+ import { existsSync as existsSync4 } from "fs";
15
+ import { mkdir as mkdir3, rm as rm3 } from "fs/promises";
16
+
17
+ // src/services/skillService.ts
18
+ import { join as join2, basename } from "path";
19
+ import { existsSync as existsSync2 } from "fs";
20
+ import { mkdir, rm, cp, readFile, unlink } from "fs/promises";
21
+ import matter from "gray-matter";
22
+ import simpleGit from "simple-git";
23
+ import AdmZip from "adm-zip";
24
+
25
+ // src/config.ts
26
+ import { join, dirname } from "path";
27
+ import { existsSync, mkdirSync } from "fs";
28
+ import { fileURLToPath } from "url";
29
+ import dotenv from "dotenv";
30
+ dotenv.config();
31
+ var __filename = fileURLToPath(import.meta.url);
32
+ var __dirname = dirname(__filename);
33
+ function setupEnvironment() {
34
+ const home = process.env.HOME || process.env.USERPROFILE || "";
35
+ const skillverseHome = process.env.SKILLVERSE_HOME || join(home, ".skillverse");
36
+ const dbUrl = process.env.DATABASE_URL;
37
+ if (!existsSync(skillverseHome)) {
38
+ try {
39
+ mkdirSync(skillverseHome, { recursive: true });
40
+ } catch (error) {
41
+ console.error("Failed to create .skillverse directory:", error);
42
+ }
43
+ }
44
+ if (!dbUrl) {
45
+ const dbPath = join(skillverseHome, "skillverse.db");
46
+ process.env.DATABASE_URL = `file:${dbPath}`;
47
+ }
48
+ return {
49
+ skillverseHome,
50
+ databaseUrl: process.env.DATABASE_URL
51
+ };
52
+ }
53
+ var config = setupEnvironment();
54
+
55
+ // src/lib/db.ts
56
+ import { PrismaClient } from "@prisma/client";
57
+ var globalForPrisma = globalThis;
58
+ var prisma = globalForPrisma.prisma ?? new PrismaClient({
59
+ log: process.env.NODE_ENV === "development" ? ["error", "warn"] : ["error"]
60
+ });
61
+ if (process.env.NODE_ENV !== "production") globalForPrisma.prisma = prisma;
62
+
63
+ // ../shared/dist/index.js
64
+ var WORKSPACE_SKILLS_PATHS = {
65
+ vscode: {
66
+ project: ".github/skills",
67
+ global: "~/.copilot/skills"
68
+ },
69
+ cursor: {
70
+ project: ".cursor/skills",
71
+ global: "~/.cursor/skills"
72
+ },
73
+ "claude-desktop": {
74
+ project: ".claude/skills",
75
+ global: "~/.claude/skills"
76
+ },
77
+ codex: {
78
+ project: ".codex/skills",
79
+ global: "~/.codex/skills"
80
+ },
81
+ antigravity: {
82
+ project: ".agent/skills",
83
+ global: "~/.agent/skills"
84
+ },
85
+ custom: {
86
+ project: "skills",
87
+ global: ""
88
+ }
89
+ };
90
+ var ErrorCode = {
91
+ VALIDATION_ERROR: "VALIDATION_ERROR",
92
+ NOT_FOUND: "NOT_FOUND",
93
+ ALREADY_EXISTS: "ALREADY_EXISTS",
94
+ INTERNAL_ERROR: "INTERNAL_ERROR",
95
+ GIT_ERROR: "GIT_ERROR",
96
+ FILE_SYSTEM_ERROR: "FILE_SYSTEM_ERROR",
97
+ PERMISSION_ERROR: "PERMISSION_ERROR",
98
+ SYMLINK_ERROR: "SYMLINK_ERROR"
99
+ };
100
+
101
+ // src/middleware/errorHandler.ts
102
+ var AppError = class extends Error {
103
+ constructor(code, message, statusCode = 500, details) {
104
+ super(message);
105
+ this.code = code;
106
+ this.statusCode = statusCode;
107
+ this.details = details;
108
+ this.name = "AppError";
109
+ }
110
+ };
111
+ function errorHandler(err, req, res, next) {
112
+ console.error("Error:", err);
113
+ if (err instanceof AppError) {
114
+ return res.status(err.statusCode).json({
115
+ success: false,
116
+ error: err.message,
117
+ code: err.code,
118
+ details: err.details
119
+ });
120
+ }
121
+ return res.status(500).json({
122
+ success: false,
123
+ error: "Internal server error",
124
+ code: ErrorCode.INTERNAL_ERROR,
125
+ message: process.env.NODE_ENV === "development" ? err.message : void 0
126
+ });
127
+ }
128
+
129
+ // src/services/skillService.ts
130
+ var SKILLVERSE_HOME = process.env.SKILLVERSE_HOME || join2(process.env.HOME || "", ".skillverse");
131
+ var SKILLS_DIR = process.env.SKILLS_DIR || join2(SKILLVERSE_HOME, "skills");
132
+ var TEMP_DIR = process.env.TEMP_DIR || join2(SKILLVERSE_HOME, "temp");
133
+ function parseGitUrl(url) {
134
+ if (!url.includes("/tree/")) {
135
+ const urlParts = url.split("/");
136
+ const repoName = urlParts[urlParts.length - 1].replace(".git", "");
137
+ return { repoUrl: url, skillName: repoName };
138
+ }
139
+ const parts = url.split("/tree/");
140
+ const repoUrl = parts[0] + (parts[0].endsWith(".git") ? "" : ".git");
141
+ const pathParts = parts[1].split("/");
142
+ const branch = pathParts[0];
143
+ const subdir = pathParts.slice(1).join("/");
144
+ const skillName = pathParts[pathParts.length - 1];
145
+ return { repoUrl, subdir, skillName };
146
+ }
147
+ var SkillService = class {
148
+ async getAllSkills() {
149
+ const skills = await prisma.skill.findMany({
150
+ include: {
151
+ linkedWorkspaces: {
152
+ include: {
153
+ workspace: true
154
+ }
155
+ },
156
+ marketplaceEntry: true
157
+ },
158
+ orderBy: {
159
+ installDate: "desc"
160
+ }
161
+ });
162
+ return skills;
163
+ }
164
+ async getSkillById(id) {
165
+ const skill = await prisma.skill.findUnique({
166
+ where: { id },
167
+ include: {
168
+ linkedWorkspaces: {
169
+ include: {
170
+ workspace: true
171
+ }
172
+ },
173
+ marketplaceEntry: true
174
+ }
175
+ });
176
+ if (!skill) {
177
+ throw new AppError(ErrorCode.NOT_FOUND, "Skill not found", 404);
178
+ }
179
+ return skill;
180
+ }
181
+ async getSkillByName(name) {
182
+ const skill = await prisma.skill.findUnique({
183
+ where: { name },
184
+ include: {
185
+ linkedWorkspaces: {
186
+ include: {
187
+ workspace: true
188
+ }
189
+ },
190
+ marketplaceEntry: true
191
+ }
192
+ });
193
+ if (!skill) {
194
+ throw new AppError(ErrorCode.NOT_FOUND, `Skill "${name}" not found`, 404);
195
+ }
196
+ return skill;
197
+ }
198
+ async parseSkillMetadata(skillPath) {
199
+ try {
200
+ const skillMdPath = join2(skillPath, "SKILL.md");
201
+ let description = "";
202
+ let metadata = {};
203
+ if (existsSync2(skillMdPath)) {
204
+ const fileContent = await readFile(skillMdPath, "utf-8");
205
+ const parsed = matter(fileContent);
206
+ description = parsed.data.description || "";
207
+ metadata = parsed.data;
208
+ }
209
+ if (!description) {
210
+ const packageJsonPath = join2(skillPath, "package.json");
211
+ const skillJsonPath = join2(skillPath, "skill.json");
212
+ if (existsSync2(skillJsonPath)) {
213
+ const content = await readFile(skillJsonPath, "utf-8");
214
+ const json = JSON.parse(content);
215
+ description = json.description || "";
216
+ metadata = { ...metadata, ...json };
217
+ } else if (existsSync2(packageJsonPath)) {
218
+ const content = await readFile(packageJsonPath, "utf-8");
219
+ const pkg = JSON.parse(content);
220
+ description = pkg.description || "";
221
+ metadata = { ...metadata, name: pkg.name, version: pkg.version };
222
+ }
223
+ }
224
+ return { description, metadata };
225
+ } catch (error) {
226
+ console.warn("Failed to parse skill metadata:", error);
227
+ return { description: "", metadata: {} };
228
+ }
229
+ }
230
+ async createSkillFromGit(gitUrl, description) {
231
+ let tempPath = null;
232
+ try {
233
+ const { repoUrl, subdir, skillName } = parseGitUrl(gitUrl);
234
+ const existingSkill = await prisma.skill.findUnique({
235
+ where: { name: skillName }
236
+ });
237
+ if (existingSkill) {
238
+ throw new AppError(ErrorCode.ALREADY_EXISTS, `Skill "${skillName}" already exists`, 409);
239
+ }
240
+ const skillPath = join2(SKILLS_DIR, skillName);
241
+ if (existsSync2(skillPath)) {
242
+ throw new AppError(ErrorCode.ALREADY_EXISTS, `Skill directory "${skillName}" already exists`, 409);
243
+ }
244
+ let commitHash = "";
245
+ if (subdir) {
246
+ tempPath = join2(TEMP_DIR, `git-clone-${Date.now()}`);
247
+ await mkdir(tempPath, { recursive: true });
248
+ console.log(`Cloning ${repoUrl} to temp path for extraction...`);
249
+ const git = simpleGit();
250
+ await git.clone(repoUrl, tempPath);
251
+ try {
252
+ commitHash = await simpleGit(tempPath).revparse(["HEAD"]);
253
+ console.log(`Captured commit hash: ${commitHash}`);
254
+ } catch (e) {
255
+ console.warn("Failed to capture commit hash:", e);
256
+ }
257
+ const sourcePath = join2(tempPath, subdir);
258
+ if (!existsSync2(sourcePath)) {
259
+ throw new AppError(
260
+ ErrorCode.GIT_ERROR,
261
+ `Subdirectory "${subdir}" not found in repository`,
262
+ 400
263
+ );
264
+ }
265
+ const hasSkillMd = existsSync2(join2(sourcePath, "SKILL.md"));
266
+ const hasSkillJson = existsSync2(join2(sourcePath, "skill.json"));
267
+ const hasPackageJson = existsSync2(join2(sourcePath, "package.json"));
268
+ if (!hasSkillMd && !hasSkillJson && !hasPackageJson) {
269
+ throw new AppError(
270
+ ErrorCode.VALIDATION_ERROR,
271
+ `Invalid skill structure: "${subdir}" does not contain SKILL.md, skill.json, or package.json`,
272
+ 400
273
+ );
274
+ }
275
+ await mkdir(skillPath, { recursive: true });
276
+ await cp(sourcePath, skillPath, { recursive: true });
277
+ } else {
278
+ if (!existsSync2(skillPath)) {
279
+ await mkdir(skillPath, { recursive: true });
280
+ }
281
+ const git = simpleGit();
282
+ console.log(`Cloning ${gitUrl} to ${skillPath}...`);
283
+ await git.clone(gitUrl, skillPath);
284
+ try {
285
+ commitHash = await git.cwd(skillPath).revparse(["HEAD"]);
286
+ console.log(`Captured commit hash: ${commitHash}`);
287
+ } catch (e) {
288
+ console.warn("Failed to capture commit hash:", e);
289
+ }
290
+ }
291
+ const parsed = await this.parseSkillMetadata(skillPath);
292
+ const skill = await prisma.skill.create({
293
+ data: {
294
+ name: skillName,
295
+ source: "git",
296
+ sourceUrl: gitUrl,
297
+ repoUrl,
298
+ commitHash,
299
+ description: description || parsed.description || "",
300
+ storagePath: skillPath,
301
+ metadata: JSON.stringify(parsed.metadata)
302
+ }
303
+ });
304
+ return skill;
305
+ } catch (error) {
306
+ throw error;
307
+ } finally {
308
+ if (tempPath && existsSync2(tempPath)) {
309
+ await rm(tempPath, { recursive: true, force: true }).catch(console.error);
310
+ }
311
+ }
312
+ }
313
+ async createSkillFromDirectory(path, name, description) {
314
+ if (!existsSync2(path)) {
315
+ throw new AppError(ErrorCode.FILE_SYSTEM_ERROR, `Source path not found: ${path}`, 400);
316
+ }
317
+ const skillName = name || basename(path);
318
+ const skillPath = join2(SKILLS_DIR, skillName);
319
+ const existingSkill = await prisma.skill.findUnique({
320
+ where: { name: skillName }
321
+ });
322
+ if (existingSkill) {
323
+ throw new AppError(ErrorCode.ALREADY_EXISTS, `Skill "${skillName}" already exists`, 409);
324
+ }
325
+ if (existsSync2(skillPath)) {
326
+ throw new AppError(ErrorCode.ALREADY_EXISTS, `Skill directory "${skillName}" already exists`, 409);
327
+ }
328
+ try {
329
+ await mkdir(skillPath, { recursive: true });
330
+ await cp(path, skillPath, { recursive: true });
331
+ const parsed = await this.parseSkillMetadata(skillPath);
332
+ const skill = await prisma.skill.create({
333
+ data: {
334
+ name: skillName,
335
+ source: "local",
336
+ description: description || parsed.description || "",
337
+ storagePath: skillPath,
338
+ metadata: JSON.stringify(parsed.metadata)
339
+ }
340
+ });
341
+ return skill;
342
+ } catch (error) {
343
+ if (existsSync2(skillPath)) {
344
+ await rm(skillPath, { recursive: true, force: true }).catch(() => {
345
+ });
346
+ }
347
+ throw error;
348
+ }
349
+ }
350
+ /**
351
+ * Helper to handle cases where the archive contains a single top-level directory.
352
+ * Moves contents up one level if that's the case.
353
+ */
354
+ async stripTopLevelDirectory(targetPath) {
355
+ const { readdir: readdir2, rename, rmdir, stat: stat2 } = await import("fs/promises");
356
+ const items = await readdir2(targetPath);
357
+ const validItems = items.filter((i) => i !== ".DS_Store" && i !== "__MACOSX");
358
+ if (validItems.length === 1) {
359
+ const topLevelItem = validItems[0];
360
+ const topLevelPath = join2(targetPath, topLevelItem);
361
+ const stats = await stat2(topLevelPath);
362
+ if (stats.isDirectory()) {
363
+ console.log(`Striping top-level directory: ${topLevelItem}`);
364
+ const subItems = await readdir2(topLevelPath);
365
+ for (const item of subItems) {
366
+ await rename(join2(topLevelPath, item), join2(targetPath, item));
367
+ }
368
+ await rmdir(topLevelPath);
369
+ }
370
+ }
371
+ }
372
+ async createSkillFromLocal(name, zipPath, description) {
373
+ const skillPath = join2(SKILLS_DIR, name);
374
+ const existingSkill = await prisma.skill.findUnique({
375
+ where: { name }
376
+ });
377
+ if (existingSkill) {
378
+ throw new AppError(ErrorCode.ALREADY_EXISTS, `Skill "${name}" already exists`, 409);
379
+ }
380
+ if (existsSync2(skillPath)) {
381
+ throw new AppError(ErrorCode.ALREADY_EXISTS, `Skill directory "${name}" already exists`, 409);
382
+ }
383
+ const extractPath = join2(TEMP_DIR, `extract-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`);
384
+ await mkdir(extractPath, { recursive: true });
385
+ try {
386
+ const zip = new AdmZip(zipPath);
387
+ zip.extractAllTo(extractPath, true);
388
+ await this.stripTopLevelDirectory(extractPath);
389
+ const parsed = await this.parseSkillMetadata(extractPath);
390
+ if (existsSync2(skillPath)) {
391
+ throw new AppError(ErrorCode.ALREADY_EXISTS, `Skill directory "${name}" already exists`, 409);
392
+ }
393
+ await import("fs/promises").then((fs) => fs.rename(extractPath, skillPath));
394
+ const skill = await prisma.skill.create({
395
+ data: {
396
+ name,
397
+ source: "local",
398
+ description: description || parsed.description || "",
399
+ storagePath: skillPath,
400
+ metadata: JSON.stringify(parsed.metadata)
401
+ }
402
+ });
403
+ return skill;
404
+ } catch (error) {
405
+ if (existsSync2(skillPath)) {
406
+ await rm(skillPath, { recursive: true, force: true }).catch(() => {
407
+ });
408
+ }
409
+ if (existsSync2(extractPath)) {
410
+ await rm(extractPath, { recursive: true, force: true }).catch(() => {
411
+ });
412
+ }
413
+ throw error;
414
+ }
415
+ }
416
+ /**
417
+ * Create a skill from a tar.gz bundle (marketplace install)
418
+ * @param bundlePath - Path to the .tar.gz bundle
419
+ * @param originalName - Original skill name
420
+ * @param description - Optional skill description
421
+ */
422
+ async createSkillFromBundle(bundlePath, originalName, description) {
423
+ let name = originalName;
424
+ let counter = 1;
425
+ while (await prisma.skill.findUnique({ where: { name } })) {
426
+ name = `${originalName}-${counter}`;
427
+ counter++;
428
+ }
429
+ const skillPath = join2(SKILLS_DIR, name);
430
+ const extractPath = join2(TEMP_DIR, `extract-bundle-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`);
431
+ await mkdir(extractPath, { recursive: true });
432
+ try {
433
+ const { createReadStream: createReadStream2 } = await import("fs");
434
+ const { createGunzip: createGunzip2 } = await import("zlib");
435
+ const tar = await import("tar");
436
+ const { pipeline: pipeline2 } = await import("stream/promises");
437
+ await pipeline2(
438
+ createReadStream2(bundlePath),
439
+ createGunzip2(),
440
+ tar.extract({ cwd: extractPath })
441
+ );
442
+ await this.stripTopLevelDirectory(extractPath);
443
+ const parsed = await this.parseSkillMetadata(extractPath);
444
+ if (existsSync2(skillPath)) {
445
+ throw new AppError(ErrorCode.ALREADY_EXISTS, `Skill directory "${name}" already exists`, 409);
446
+ }
447
+ await import("fs/promises").then((fs) => fs.rename(extractPath, skillPath));
448
+ const skill = await prisma.skill.create({
449
+ data: {
450
+ name,
451
+ source: "local",
452
+ description: description || parsed.description || "",
453
+ storagePath: skillPath,
454
+ metadata: JSON.stringify(parsed.metadata)
455
+ }
456
+ });
457
+ console.log(`\u{1F4E6} Installed skill "${name}" from bundle`);
458
+ return skill;
459
+ } catch (error) {
460
+ if (existsSync2(skillPath)) {
461
+ await rm(skillPath, { recursive: true, force: true }).catch(() => {
462
+ });
463
+ }
464
+ if (existsSync2(extractPath)) {
465
+ await rm(extractPath, { recursive: true, force: true }).catch(() => {
466
+ });
467
+ }
468
+ throw error;
469
+ }
470
+ }
471
+ async updateSkill(id, data) {
472
+ const skill = await this.getSkillById(id);
473
+ const updatedSkill = await prisma.skill.update({
474
+ where: { id },
475
+ data: {
476
+ ...data.name && { name: data.name },
477
+ ...data.description !== void 0 && { description: data.description },
478
+ ...data.metadata && { metadata: JSON.stringify(data.metadata) }
479
+ }
480
+ });
481
+ return updatedSkill;
482
+ }
483
+ async deleteSkill(id, removeFiles = true) {
484
+ const skill = await this.getSkillById(id);
485
+ if (skill.linkedWorkspaces && skill.linkedWorkspaces.length > 0) {
486
+ for (const link of skill.linkedWorkspaces) {
487
+ try {
488
+ const workspacePath = link.workspace.path;
489
+ const symlinkPath = join2(workspacePath, skill.name);
490
+ if (existsSync2(symlinkPath)) {
491
+ const stats = await import("fs/promises").then((fs) => fs.lstat(symlinkPath));
492
+ if (stats.isSymbolicLink()) {
493
+ await unlink(symlinkPath);
494
+ console.log(`Removed symlink for ${skill.name} in workspace ${workspacePath}`);
495
+ }
496
+ }
497
+ } catch (error) {
498
+ console.warn(`Failed to remove symlink for ${skill.name} in workspace ${link.workspace.path}:`, error);
499
+ }
500
+ }
501
+ }
502
+ await prisma.skill.delete({
503
+ where: { id }
504
+ });
505
+ if (removeFiles && skill.storagePath) {
506
+ await rm(skill.storagePath, { recursive: true, force: true }).catch((err) => {
507
+ console.warn(`Failed to delete skill directory ${skill.storagePath}:`, err);
508
+ });
509
+ }
510
+ return { success: true, message: "Skill deleted successfully" };
511
+ }
512
+ // Check for updates
513
+ async checkForUpdate(id) {
514
+ const skill = await this.getSkillById(id);
515
+ if (skill.source !== "git" || !skill.repoUrl) {
516
+ return {
517
+ hasUpdate: false,
518
+ currentHash: skill.commitHash,
519
+ remoteHash: null,
520
+ message: "Not a git skill or missing repo URL"
521
+ };
522
+ }
523
+ const tempPath = join2(TEMP_DIR, `check-update-${Date.now()}`);
524
+ await mkdir(tempPath, { recursive: true });
525
+ try {
526
+ const git = simpleGit();
527
+ console.log(`Checking updates for ${skill.name} from ${skill.repoUrl}...`);
528
+ const remote = await git.listRemote([skill.repoUrl, "HEAD"]);
529
+ if (!remote) {
530
+ throw new Error("Failed to get remote HEAD");
531
+ }
532
+ const remoteHash = remote.split(" ")[0];
533
+ const hasUpdate = remoteHash !== skill.commitHash;
534
+ await prisma.skill.update({
535
+ where: { id },
536
+ data: {
537
+ lastUpdateCheck: /* @__PURE__ */ new Date(),
538
+ updateAvailable: hasUpdate
539
+ }
540
+ });
541
+ return {
542
+ hasUpdate,
543
+ currentHash: skill.commitHash,
544
+ remoteHash
545
+ };
546
+ } catch (error) {
547
+ console.error("Update check error:", error);
548
+ throw new AppError(ErrorCode.GIT_ERROR, `Failed to check for updates: ${error.message}`, 500);
549
+ } finally {
550
+ await rm(tempPath, { recursive: true, force: true }).catch(() => {
551
+ });
552
+ }
553
+ }
554
+ async checkUpdates(ids) {
555
+ const whereClause = {
556
+ source: "git",
557
+ repoUrl: { not: null }
558
+ };
559
+ if (ids && ids.length > 0) {
560
+ whereClause.id = { in: ids };
561
+ }
562
+ const skills = await prisma.skill.findMany({ where: whereClause });
563
+ const results = {};
564
+ console.log(`Checking updates for ${skills.length} skills...`);
565
+ await Promise.all(skills.map(async (skill) => {
566
+ try {
567
+ const result = await this.checkForUpdate(skill.id);
568
+ results[skill.id] = result;
569
+ } catch (e) {
570
+ results[skill.id] = { error: e.message };
571
+ }
572
+ }));
573
+ return results;
574
+ }
575
+ async refreshMetadata(id) {
576
+ const skill = await this.getSkillById(id);
577
+ const parsed = await this.parseSkillMetadata(skill.storagePath);
578
+ const updated = await prisma.skill.update({
579
+ where: { id },
580
+ data: {
581
+ description: parsed.description,
582
+ metadata: JSON.stringify(parsed.metadata)
583
+ }
584
+ });
585
+ return updated;
586
+ }
587
+ async upgradeSkill(id) {
588
+ const skill = await this.getSkillById(id);
589
+ if (skill.source !== "git" || !skill.sourceUrl) {
590
+ throw new AppError(ErrorCode.VALIDATION_ERROR, "Cannot upgrade non-git skill", 400);
591
+ }
592
+ let tempPath = null;
593
+ let tempSkillPath = null;
594
+ try {
595
+ const { repoUrl, subdir } = parseGitUrl(skill.sourceUrl);
596
+ tempPath = join2(TEMP_DIR, `upgrade-${Date.now()}`);
597
+ await mkdir(tempPath, { recursive: true });
598
+ const git = simpleGit();
599
+ console.log(`Cloning ${repoUrl} to temp for upgrade...`);
600
+ await git.clone(repoUrl, tempPath);
601
+ let commitHash = "";
602
+ try {
603
+ commitHash = await simpleGit(tempPath).revparse(["HEAD"]);
604
+ } catch (e) {
605
+ console.warn("Failed to capture commit hash during upgrade:", e);
606
+ }
607
+ let sourcePath = tempPath;
608
+ if (subdir) {
609
+ sourcePath = join2(tempPath, subdir);
610
+ if (!existsSync2(sourcePath)) {
611
+ throw new AppError(ErrorCode.GIT_ERROR, `Subdirectory "${subdir}" not found`, 400);
612
+ }
613
+ }
614
+ const hasSkillMd = existsSync2(join2(sourcePath, "SKILL.md"));
615
+ const hasSkillJson = existsSync2(join2(sourcePath, "skill.json"));
616
+ const hasPackageJson = existsSync2(join2(sourcePath, "package.json"));
617
+ if (!hasSkillMd && !hasSkillJson && !hasPackageJson) {
618
+ throw new AppError(ErrorCode.VALIDATION_ERROR, "Invalid skill structure in new version", 400);
619
+ }
620
+ const files = await import("fs/promises").then((fs) => fs.readdir(skill.storagePath));
621
+ for (const file of files) {
622
+ await rm(join2(skill.storagePath, file), { recursive: true, force: true });
623
+ }
624
+ await cp(sourcePath, skill.storagePath, { recursive: true });
625
+ const parsed = await this.parseSkillMetadata(skill.storagePath);
626
+ const updatedSkill = await prisma.skill.update({
627
+ where: { id },
628
+ data: {
629
+ commitHash,
630
+ updateAvailable: false,
631
+ lastUpdateCheck: /* @__PURE__ */ new Date(),
632
+ installDate: /* @__PURE__ */ new Date(),
633
+ // Considering upgrade as reinstall? Or user prefer generic updatedAt
634
+ // Keeping installDate as "last installed/upgraded"
635
+ description: parsed.description,
636
+ metadata: JSON.stringify(parsed.metadata)
637
+ }
638
+ });
639
+ return updatedSkill;
640
+ } catch (error) {
641
+ console.error("Upgrade error:", error);
642
+ throw new AppError(ErrorCode.GIT_ERROR, `Failed to upgrade skill: ${error.message}`, 500);
643
+ } finally {
644
+ if (tempPath) await rm(tempPath, { recursive: true, force: true }).catch(() => {
645
+ });
646
+ }
647
+ }
648
+ };
649
+ var skillService = new SkillService();
650
+
651
+ // src/services/workspaceService.ts
652
+ import { join as join3 } from "path";
653
+ import { homedir } from "os";
654
+ import { symlink, unlink as unlink2, rm as rm2, mkdir as mkdir2, appendFile, readFile as readFile2 } from "fs/promises";
655
+ import { existsSync as existsSync3, lstatSync } from "fs";
656
+ function computeSkillsPath(projectPath, type, scope) {
657
+ const pathConfig = WORKSPACE_SKILLS_PATHS[type];
658
+ if (scope === "global") {
659
+ return pathConfig.global.replace("~", homedir());
660
+ }
661
+ return join3(projectPath, pathConfig.project);
662
+ }
663
+ var WorkspaceService = class {
664
+ /**
665
+ * Helper to get expected skills path for a project
666
+ */
667
+ getSkillsPath(projectPath, type, scope) {
668
+ return computeSkillsPath(projectPath, type, scope);
669
+ }
670
+ /**
671
+ * Sync database links with filesystem state
672
+ * Removes links from DB if the symlink is missing from the workspace
673
+ */
674
+ async syncLinks(workspace) {
675
+ if (!workspace.linkedSkills || workspace.linkedSkills.length === 0) return;
676
+ for (const link of workspace.linkedSkills) {
677
+ if (!link.skill) continue;
678
+ const linkPath = join3(workspace.path, link.skill.name);
679
+ if (!existsSync3(linkPath)) {
680
+ console.log(`Link missing for skill "${link.skill.name}" in workspace "${workspace.name}". Removing from DB.`);
681
+ try {
682
+ await prisma.skillWorkspace.delete({
683
+ where: { id: link.id }
684
+ });
685
+ workspace.linkedSkills = workspace.linkedSkills.filter((l) => l.id !== link.id);
686
+ } catch (err) {
687
+ console.error(`Failed to sync link for ${link.skill.name}:`, err);
688
+ }
689
+ }
690
+ }
691
+ }
692
+ async findWorkspaceByPath(path) {
693
+ const workspace = await prisma.workspace.findUnique({
694
+ where: { path },
695
+ include: {
696
+ linkedSkills: {
697
+ include: {
698
+ skill: true
699
+ }
700
+ }
701
+ }
702
+ });
703
+ return workspace;
704
+ }
705
+ async getAllWorkspaces() {
706
+ const workspaces = await prisma.workspace.findMany({
707
+ include: {
708
+ linkedSkills: {
709
+ include: {
710
+ skill: true
711
+ }
712
+ }
713
+ },
714
+ orderBy: {
715
+ createdAt: "desc"
716
+ }
717
+ });
718
+ await Promise.all(workspaces.map((w) => this.syncLinks(w)));
719
+ return workspaces.map((workspace) => ({
720
+ ...workspace,
721
+ isPathValid: existsSync3(workspace.path)
722
+ }));
723
+ }
724
+ async getWorkspaceById(id) {
725
+ const workspace = await prisma.workspace.findUnique({
726
+ where: { id },
727
+ include: {
728
+ linkedSkills: {
729
+ include: {
730
+ skill: true
731
+ }
732
+ }
733
+ }
734
+ });
735
+ if (!workspace) {
736
+ throw new AppError(ErrorCode.NOT_FOUND, "Workspace not found", 404);
737
+ }
738
+ await this.syncLinks(workspace);
739
+ return {
740
+ ...workspace,
741
+ isPathValid: existsSync3(workspace.path)
742
+ };
743
+ }
744
+ async createWorkspace(name, projectPath, type, scope) {
745
+ const skillsPath = computeSkillsPath(projectPath, type, scope);
746
+ if (scope === "project" && projectPath && !existsSync3(projectPath)) {
747
+ throw new AppError(ErrorCode.FILE_SYSTEM_ERROR, `Project path does not exist: ${projectPath}`, 400);
748
+ }
749
+ if (!existsSync3(skillsPath)) {
750
+ try {
751
+ await mkdir2(skillsPath, { recursive: true });
752
+ } catch (err) {
753
+ throw new AppError(
754
+ ErrorCode.FILE_SYSTEM_ERROR,
755
+ `Failed to create skills directory: ${err.message}`,
756
+ 500
757
+ );
758
+ }
759
+ }
760
+ const existingWorkspace = await prisma.workspace.findUnique({
761
+ where: { path: skillsPath }
762
+ });
763
+ if (existingWorkspace) {
764
+ throw new AppError(ErrorCode.ALREADY_EXISTS, "Workspace already exists at this path", 409);
765
+ }
766
+ const workspace = await prisma.workspace.create({
767
+ data: {
768
+ name,
769
+ path: skillsPath,
770
+ type,
771
+ scope
772
+ }
773
+ });
774
+ if (scope === "project" && projectPath && existsSync3(projectPath)) {
775
+ try {
776
+ const gitignorePath = join3(projectPath, ".gitignore");
777
+ const relativeSkillsPath = WORKSPACE_SKILLS_PATHS[type].project;
778
+ let shouldAppend = false;
779
+ if (existsSync3(gitignorePath)) {
780
+ const content = await readFile2(gitignorePath, "utf-8");
781
+ if (!content.includes(relativeSkillsPath)) {
782
+ shouldAppend = true;
783
+ }
784
+ } else {
785
+ shouldAppend = true;
786
+ }
787
+ if (shouldAppend) {
788
+ const ignoreEntry = `
789
+
790
+ # SkillVerse
791
+ ${relativeSkillsPath}/
792
+ `;
793
+ await appendFile(gitignorePath, ignoreEntry);
794
+ console.log(`Added ${relativeSkillsPath}/ to .gitignore in ${projectPath}`);
795
+ }
796
+ } catch (err) {
797
+ console.warn("Failed to update .gitignore:", err);
798
+ }
799
+ }
800
+ return {
801
+ ...workspace,
802
+ isPathValid: true
803
+ };
804
+ }
805
+ async updateWorkspace(id, data) {
806
+ await this.getWorkspaceById(id);
807
+ const workspace = await prisma.workspace.update({
808
+ where: { id },
809
+ data
810
+ });
811
+ return {
812
+ ...workspace,
813
+ isPathValid: existsSync3(workspace.path)
814
+ };
815
+ }
816
+ async deleteWorkspace(id) {
817
+ const workspace = await this.getWorkspaceById(id);
818
+ const links = await prisma.skillWorkspace.findMany({
819
+ where: { workspaceId: id },
820
+ include: { skill: true }
821
+ });
822
+ for (const link of links) {
823
+ try {
824
+ const linkPath = join3(workspace.path, link.skill.name);
825
+ if (existsSync3(linkPath)) {
826
+ await rm2(linkPath, { recursive: true, force: true });
827
+ }
828
+ } catch (error) {
829
+ console.error(`Failed to remove symlink for ${link.skill.name}:`, error);
830
+ }
831
+ }
832
+ await prisma.workspace.delete({ where: { id } });
833
+ return { success: true, message: "Workspace deleted successfully" };
834
+ }
835
+ async linkSkillToWorkspace(skillId, workspaceId) {
836
+ const skill = await prisma.skill.findUnique({ where: { id: skillId } });
837
+ const workspace = await prisma.workspace.findUnique({ where: { id: workspaceId } });
838
+ if (!skill) {
839
+ throw new AppError(ErrorCode.NOT_FOUND, "Skill not found", 404);
840
+ }
841
+ if (!workspace) {
842
+ throw new AppError(ErrorCode.NOT_FOUND, "Workspace not found", 404);
843
+ }
844
+ if (!existsSync3(workspace.path)) {
845
+ throw new AppError(
846
+ ErrorCode.FILE_SYSTEM_ERROR,
847
+ `Workspace skills directory does not exist: ${workspace.path}. The folder may have been deleted. Please recreate it or remove this workspace.`,
848
+ 400
849
+ );
850
+ }
851
+ const existingLink = await prisma.skillWorkspace.findFirst({
852
+ where: {
853
+ skillId,
854
+ workspaceId
855
+ }
856
+ });
857
+ if (existingLink) {
858
+ throw new AppError(ErrorCode.ALREADY_EXISTS, "Skill is already linked to this workspace", 409);
859
+ }
860
+ const targetPath = join3(workspace.path, skill.name);
861
+ try {
862
+ if (existsSync3(targetPath)) {
863
+ const stats = lstatSync(targetPath);
864
+ if (stats.isSymbolicLink()) {
865
+ await unlink2(targetPath);
866
+ } else {
867
+ throw new AppError(
868
+ ErrorCode.FILE_SYSTEM_ERROR,
869
+ `A file or directory already exists at ${targetPath}`,
870
+ 409
871
+ );
872
+ }
873
+ }
874
+ await symlink(skill.storagePath, targetPath, "dir");
875
+ const link = await prisma.skillWorkspace.create({
876
+ data: {
877
+ skillId,
878
+ workspaceId
879
+ },
880
+ include: {
881
+ skill: true,
882
+ workspace: true
883
+ }
884
+ });
885
+ return link;
886
+ } catch (error) {
887
+ if (error instanceof AppError) throw error;
888
+ console.error("Symlink creation error:", error);
889
+ throw new AppError(
890
+ ErrorCode.SYMLINK_ERROR,
891
+ `Failed to create symlink: ${error.message}`,
892
+ 500,
893
+ error
894
+ );
895
+ }
896
+ }
897
+ async unlinkSkillFromWorkspace(skillId, workspaceId) {
898
+ const link = await prisma.skillWorkspace.findFirst({
899
+ where: {
900
+ skillId,
901
+ workspaceId
902
+ },
903
+ include: {
904
+ skill: true,
905
+ workspace: true
906
+ }
907
+ });
908
+ if (!link) {
909
+ throw new AppError(ErrorCode.NOT_FOUND, "Link not found", 404);
910
+ }
911
+ const linkPath = join3(link.workspace.path, link.skill.name);
912
+ try {
913
+ if (existsSync3(linkPath)) {
914
+ await rm2(linkPath, { recursive: true, force: true });
915
+ }
916
+ await prisma.skillWorkspace.delete({
917
+ where: { id: link.id }
918
+ });
919
+ return { success: true, message: "Skill unlinked successfully" };
920
+ } catch (error) {
921
+ console.error("Unlink error:", error);
922
+ throw new AppError(
923
+ ErrorCode.FILE_SYSTEM_ERROR,
924
+ `Failed to unlink skill: ${error.message}`,
925
+ 500,
926
+ error
927
+ );
928
+ }
929
+ }
930
+ /**
931
+ * Detect existing skills in a workspace skills directory
932
+ * Returns list of skill names that could be migrated
933
+ */
934
+ async detectExistingSkills(skillsPath) {
935
+ if (!existsSync3(skillsPath)) {
936
+ return [];
937
+ }
938
+ const { readdir: readdir2, stat: stat2, readFile: readFile3 } = await import("fs/promises");
939
+ const items = await readdir2(skillsPath);
940
+ const existingSkills = [];
941
+ for (const item of items) {
942
+ if (item.startsWith(".")) continue;
943
+ const itemPath = join3(skillsPath, item);
944
+ try {
945
+ const itemStat = await stat2(itemPath);
946
+ const lstats = lstatSync(itemPath);
947
+ if (lstats.isSymbolicLink()) continue;
948
+ if (itemStat.isDirectory()) {
949
+ const hasSkillMd = existsSync3(join3(itemPath, "SKILL.md"));
950
+ const hasSkillJson = existsSync3(join3(itemPath, "skill.json"));
951
+ const hasPackageJson = existsSync3(join3(itemPath, "package.json"));
952
+ if (hasSkillMd || hasSkillJson || hasPackageJson) {
953
+ existingSkills.push({
954
+ name: item,
955
+ hasSkillMd,
956
+ path: itemPath
957
+ });
958
+ }
959
+ }
960
+ } catch (error) {
961
+ console.warn(`Failed to check ${itemPath}:`, error);
962
+ }
963
+ }
964
+ return existingSkills;
965
+ }
966
+ /**
967
+ * Migrate existing skills from workspace to unified storage
968
+ * 1. Move skills to ~/.skillverse/skills/
969
+ * 2. Register in database
970
+ * 3. Create symlinks back to workspace
971
+ */
972
+ async migrateExistingSkills(workspaceId, skillNames) {
973
+ const workspace = await this.getWorkspaceById(workspaceId);
974
+ const SKILLVERSE_HOME2 = process.env.SKILLVERSE_HOME || join3(homedir(), ".skillverse");
975
+ const SKILLS_DIR2 = process.env.SKILLS_DIR || join3(SKILLVERSE_HOME2, "skills");
976
+ if (!existsSync3(SKILLS_DIR2)) {
977
+ await mkdir2(SKILLS_DIR2, { recursive: true });
978
+ }
979
+ const { rename, readFile: readFile3, cp: cp2 } = await import("fs/promises");
980
+ const migrated = [];
981
+ const errors = [];
982
+ for (const skillName of skillNames) {
983
+ const sourcePath = join3(workspace.path, skillName);
984
+ const targetPath = join3(SKILLS_DIR2, skillName);
985
+ try {
986
+ if (!existsSync3(sourcePath)) {
987
+ errors.push(`${skillName}: Source path not found`);
988
+ continue;
989
+ }
990
+ const lstats = lstatSync(sourcePath);
991
+ if (lstats.isSymbolicLink()) {
992
+ errors.push(`${skillName}: Already a symlink, skipping`);
993
+ continue;
994
+ }
995
+ if (existsSync3(targetPath)) {
996
+ errors.push(`${skillName}: Already exists in unified storage`);
997
+ continue;
998
+ }
999
+ const existingSkill = await prisma.skill.findUnique({
1000
+ where: { name: skillName }
1001
+ });
1002
+ if (existingSkill) {
1003
+ errors.push(`${skillName}: Already registered in database`);
1004
+ continue;
1005
+ }
1006
+ const skillMdPath = join3(sourcePath, "SKILL.md");
1007
+ let description = "";
1008
+ let metadata = {};
1009
+ if (existsSync3(skillMdPath)) {
1010
+ try {
1011
+ const matter2 = await import("gray-matter");
1012
+ const fileContent = await readFile3(skillMdPath, "utf-8");
1013
+ const parsed = matter2.default(fileContent);
1014
+ description = parsed.data.description || "";
1015
+ metadata = parsed.data;
1016
+ } catch (e) {
1017
+ console.warn(`Failed to parse SKILL.md for ${skillName}:`, e);
1018
+ }
1019
+ }
1020
+ await cp2(sourcePath, targetPath, { recursive: true });
1021
+ await rm2(sourcePath, { recursive: true, force: true });
1022
+ const skill = await prisma.skill.create({
1023
+ data: {
1024
+ name: skillName,
1025
+ source: "local",
1026
+ description,
1027
+ storagePath: targetPath,
1028
+ metadata: JSON.stringify(metadata)
1029
+ }
1030
+ });
1031
+ await symlink(targetPath, sourcePath, "dir");
1032
+ await prisma.skillWorkspace.create({
1033
+ data: {
1034
+ skillId: skill.id,
1035
+ workspaceId: workspace.id
1036
+ }
1037
+ });
1038
+ migrated.push(skillName);
1039
+ console.log(`\u2705 Migrated skill "${skillName}" to unified storage`);
1040
+ } catch (error) {
1041
+ console.error(`Failed to migrate ${skillName}:`, error);
1042
+ errors.push(`${skillName}: ${error.message}`);
1043
+ }
1044
+ }
1045
+ return {
1046
+ success: errors.length === 0,
1047
+ migrated,
1048
+ errors
1049
+ };
1050
+ }
1051
+ };
1052
+ var workspaceService = new WorkspaceService();
1053
+
1054
+ // src/routes/skills.ts
1055
+ var router = Router();
1056
+ var TEMP_DIR2 = process.env.TEMP_DIR || join4(process.env.HOME || "", ".skillverse", "temp");
1057
+ if (!existsSync4(TEMP_DIR2)) {
1058
+ mkdir3(TEMP_DIR2, { recursive: true });
1059
+ }
1060
+ var storage = multer.diskStorage({
1061
+ destination: (req, file, cb) => {
1062
+ cb(null, TEMP_DIR2);
1063
+ },
1064
+ filename: (req, file, cb) => {
1065
+ const uniqueSuffix = Date.now() + "-" + Math.round(Math.random() * 1e9);
1066
+ cb(null, uniqueSuffix + "-" + file.originalname);
1067
+ }
1068
+ });
1069
+ var upload = multer({
1070
+ storage,
1071
+ limits: {
1072
+ fileSize: 100 * 1024 * 1024
1073
+ // 100MB limit
1074
+ },
1075
+ fileFilter: (req, file, cb) => {
1076
+ if (file.mimetype === "application/zip" || file.originalname.endsWith(".zip")) {
1077
+ cb(null, true);
1078
+ } else {
1079
+ cb(new Error("Only ZIP files are allowed"));
1080
+ }
1081
+ }
1082
+ });
1083
+ router.get("/", async (req, res, next) => {
1084
+ try {
1085
+ const skills = await skillService.getAllSkills();
1086
+ res.json({
1087
+ success: true,
1088
+ data: skills
1089
+ });
1090
+ } catch (error) {
1091
+ next(error);
1092
+ }
1093
+ });
1094
+ router.get("/:id", async (req, res, next) => {
1095
+ try {
1096
+ const skill = await skillService.getSkillById(req.params.id);
1097
+ res.json({
1098
+ success: true,
1099
+ data: skill
1100
+ });
1101
+ } catch (error) {
1102
+ next(error);
1103
+ }
1104
+ });
1105
+ router.post("/from-git", async (req, res, next) => {
1106
+ try {
1107
+ const { gitUrl, description } = req.body;
1108
+ if (!gitUrl) {
1109
+ return res.status(400).json({
1110
+ success: false,
1111
+ error: "gitUrl is required"
1112
+ });
1113
+ }
1114
+ const skill = await skillService.createSkillFromGit(gitUrl, description);
1115
+ res.status(201).json({
1116
+ success: true,
1117
+ data: skill,
1118
+ message: "Skill created successfully from Git repository"
1119
+ });
1120
+ } catch (error) {
1121
+ next(error);
1122
+ }
1123
+ });
1124
+ router.post(
1125
+ "/from-local",
1126
+ upload.single("file"),
1127
+ async (req, res, next) => {
1128
+ try {
1129
+ const { name, description } = req.body;
1130
+ const file = req.file;
1131
+ if (!name) {
1132
+ if (file) {
1133
+ await rm3(file.path, { force: true });
1134
+ }
1135
+ return res.status(400).json({
1136
+ success: false,
1137
+ error: "name is required"
1138
+ });
1139
+ }
1140
+ if (!file) {
1141
+ return res.status(400).json({
1142
+ success: false,
1143
+ error: "ZIP file is required"
1144
+ });
1145
+ }
1146
+ const skill = await skillService.createSkillFromLocal(name, file.path, description);
1147
+ await rm3(file.path, { force: true });
1148
+ res.status(201).json({
1149
+ success: true,
1150
+ data: skill,
1151
+ message: "Skill created successfully from local file"
1152
+ });
1153
+ } catch (error) {
1154
+ if (req.file) {
1155
+ await rm3(req.file.path, { force: true }).catch(() => {
1156
+ });
1157
+ }
1158
+ next(error);
1159
+ }
1160
+ }
1161
+ );
1162
+ router.put("/:id", async (req, res, next) => {
1163
+ try {
1164
+ const { name, description, metadata } = req.body;
1165
+ const skill = await skillService.updateSkill(req.params.id, {
1166
+ name,
1167
+ description,
1168
+ metadata
1169
+ });
1170
+ res.json({
1171
+ success: true,
1172
+ data: skill,
1173
+ message: "Skill updated successfully"
1174
+ });
1175
+ } catch (error) {
1176
+ next(error);
1177
+ }
1178
+ });
1179
+ router.delete("/:id", async (req, res, next) => {
1180
+ try {
1181
+ const removeFiles = req.query.removeFiles !== "false";
1182
+ const result = await skillService.deleteSkill(req.params.id, removeFiles);
1183
+ res.json(result);
1184
+ } catch (error) {
1185
+ next(error);
1186
+ }
1187
+ });
1188
+ router.post("/:id/link", async (req, res, next) => {
1189
+ try {
1190
+ const { workspaceId } = req.body;
1191
+ if (!workspaceId) {
1192
+ return res.status(400).json({
1193
+ success: false,
1194
+ error: "workspaceId is required"
1195
+ });
1196
+ }
1197
+ const link = await workspaceService.linkSkillToWorkspace(req.params.id, workspaceId);
1198
+ res.status(201).json({
1199
+ success: true,
1200
+ data: link,
1201
+ message: "Skill linked to workspace successfully"
1202
+ });
1203
+ } catch (error) {
1204
+ next(error);
1205
+ }
1206
+ });
1207
+ router.delete(
1208
+ "/:id/unlink/:workspaceId",
1209
+ async (req, res, next) => {
1210
+ try {
1211
+ const result = await workspaceService.unlinkSkillFromWorkspace(
1212
+ req.params.id,
1213
+ req.params.workspaceId
1214
+ );
1215
+ res.json(result);
1216
+ } catch (error) {
1217
+ next(error);
1218
+ }
1219
+ }
1220
+ );
1221
+ router.get("/:id/check-update", async (req, res, next) => {
1222
+ try {
1223
+ const result = await skillService.checkForUpdate(req.params.id);
1224
+ res.json({
1225
+ success: true,
1226
+ data: result
1227
+ });
1228
+ } catch (error) {
1229
+ next(error);
1230
+ }
1231
+ });
1232
+ router.post("/:id/upgrade", async (req, res, next) => {
1233
+ try {
1234
+ const skill = await skillService.upgradeSkill(req.params.id);
1235
+ res.json({
1236
+ success: true,
1237
+ data: skill,
1238
+ message: "Skill upgraded successfully"
1239
+ });
1240
+ } catch (error) {
1241
+ next(error);
1242
+ }
1243
+ });
1244
+ router.post("/check-updates", async (req, res, next) => {
1245
+ try {
1246
+ const { ids } = req.body;
1247
+ const results = await skillService.checkUpdates(ids);
1248
+ res.json({
1249
+ success: true,
1250
+ data: results
1251
+ });
1252
+ } catch (error) {
1253
+ next(error);
1254
+ }
1255
+ });
1256
+ router.post("/:id/refresh-metadata", async (req, res, next) => {
1257
+ try {
1258
+ const skill = await skillService.refreshMetadata(req.params.id);
1259
+ res.json({
1260
+ success: true,
1261
+ data: skill,
1262
+ message: "Metadata refreshed successfully"
1263
+ });
1264
+ } catch (error) {
1265
+ next(error);
1266
+ }
1267
+ });
1268
+ router.get("/:id/skill-md", async (req, res, next) => {
1269
+ try {
1270
+ const { readFile: readFile3 } = await import("fs/promises");
1271
+ const skill = await skillService.getSkillById(req.params.id);
1272
+ const skillMdPath = join4(skill.storagePath, "SKILL.md");
1273
+ if (!existsSync4(skillMdPath)) {
1274
+ return res.json({
1275
+ success: true,
1276
+ data: {
1277
+ exists: false,
1278
+ content: null
1279
+ }
1280
+ });
1281
+ }
1282
+ const content = await readFile3(skillMdPath, "utf-8");
1283
+ res.json({
1284
+ success: true,
1285
+ data: {
1286
+ exists: true,
1287
+ content
1288
+ }
1289
+ });
1290
+ } catch (error) {
1291
+ next(error);
1292
+ }
1293
+ });
1294
+ var skills_default = router;
1295
+
1296
+ // src/routes/workspaces.ts
1297
+ import { Router as Router2 } from "express";
1298
+ var router2 = Router2();
1299
+ router2.get("/", async (req, res, next) => {
1300
+ try {
1301
+ const workspaces = await workspaceService.getAllWorkspaces();
1302
+ res.json({
1303
+ success: true,
1304
+ data: workspaces
1305
+ });
1306
+ } catch (error) {
1307
+ next(error);
1308
+ }
1309
+ });
1310
+ router2.get("/:id", async (req, res, next) => {
1311
+ try {
1312
+ const workspace = await workspaceService.getWorkspaceById(req.params.id);
1313
+ res.json({
1314
+ success: true,
1315
+ data: workspace
1316
+ });
1317
+ } catch (error) {
1318
+ next(error);
1319
+ }
1320
+ });
1321
+ router2.post("/", async (req, res, next) => {
1322
+ try {
1323
+ const { name, projectPath, type, scope } = req.body;
1324
+ if (!name || !type || !scope) {
1325
+ return res.status(400).json({
1326
+ success: false,
1327
+ error: "name, type, and scope are required"
1328
+ });
1329
+ }
1330
+ if (scope === "project" && !projectPath) {
1331
+ return res.status(400).json({
1332
+ success: false,
1333
+ error: "projectPath is required for project scope"
1334
+ });
1335
+ }
1336
+ const validTypes = ["vscode", "cursor", "claude-desktop", "codex", "antigravity", "custom"];
1337
+ if (!validTypes.includes(type)) {
1338
+ return res.status(400).json({
1339
+ success: false,
1340
+ error: `type must be one of: ${validTypes.join(", ")}`
1341
+ });
1342
+ }
1343
+ const validScopes = ["project", "global"];
1344
+ if (!validScopes.includes(scope)) {
1345
+ return res.status(400).json({
1346
+ success: false,
1347
+ error: `scope must be one of: ${validScopes.join(", ")}`
1348
+ });
1349
+ }
1350
+ const workspace = await workspaceService.createWorkspace(name, projectPath || "", type, scope);
1351
+ res.status(201).json({
1352
+ success: true,
1353
+ data: workspace,
1354
+ message: "Workspace created successfully"
1355
+ });
1356
+ } catch (error) {
1357
+ next(error);
1358
+ }
1359
+ });
1360
+ router2.put("/:id", async (req, res, next) => {
1361
+ try {
1362
+ const { name, path, type, scope } = req.body;
1363
+ if (type) {
1364
+ const validTypes = ["vscode", "cursor", "claude-desktop", "codex", "antigravity", "custom"];
1365
+ if (!validTypes.includes(type)) {
1366
+ return res.status(400).json({
1367
+ success: false,
1368
+ error: `type must be one of: ${validTypes.join(", ")}`
1369
+ });
1370
+ }
1371
+ }
1372
+ if (scope) {
1373
+ const validScopes = ["project", "global"];
1374
+ if (!validScopes.includes(scope)) {
1375
+ return res.status(400).json({
1376
+ success: false,
1377
+ error: `scope must be one of: ${validScopes.join(", ")}`
1378
+ });
1379
+ }
1380
+ }
1381
+ const workspace = await workspaceService.updateWorkspace(req.params.id, {
1382
+ name,
1383
+ path,
1384
+ type,
1385
+ scope
1386
+ });
1387
+ res.json({
1388
+ success: true,
1389
+ data: workspace,
1390
+ message: "Workspace updated successfully"
1391
+ });
1392
+ } catch (error) {
1393
+ next(error);
1394
+ }
1395
+ });
1396
+ router2.delete("/:id", async (req, res, next) => {
1397
+ try {
1398
+ const result = await workspaceService.deleteWorkspace(req.params.id);
1399
+ res.json(result);
1400
+ } catch (error) {
1401
+ next(error);
1402
+ }
1403
+ });
1404
+ router2.post("/:id/detect-skills", async (req, res, next) => {
1405
+ try {
1406
+ const workspace = await workspaceService.getWorkspaceById(req.params.id);
1407
+ const existingSkills = await workspaceService.detectExistingSkills(workspace.path);
1408
+ res.json({
1409
+ success: true,
1410
+ data: existingSkills
1411
+ });
1412
+ } catch (error) {
1413
+ next(error);
1414
+ }
1415
+ });
1416
+ router2.post("/:id/migrate-skills", async (req, res, next) => {
1417
+ try {
1418
+ const { skillNames } = req.body;
1419
+ if (!skillNames || !Array.isArray(skillNames) || skillNames.length === 0) {
1420
+ return res.status(400).json({
1421
+ success: false,
1422
+ error: "skillNames array is required"
1423
+ });
1424
+ }
1425
+ const result = await workspaceService.migrateExistingSkills(req.params.id, skillNames);
1426
+ res.json({
1427
+ success: true,
1428
+ data: result
1429
+ });
1430
+ } catch (error) {
1431
+ next(error);
1432
+ }
1433
+ });
1434
+ var workspaces_default = router2;
1435
+
1436
+ // src/routes/marketplace.ts
1437
+ import { Router as Router3 } from "express";
1438
+
1439
+ // src/services/bundleService.ts
1440
+ import { createWriteStream, existsSync as existsSync5, createReadStream } from "fs";
1441
+ import { mkdir as mkdir4, rm as rm4, readdir, stat } from "fs/promises";
1442
+ import { join as join5 } from "path";
1443
+ import { pipeline } from "stream/promises";
1444
+ import archiver from "archiver";
1445
+ import { createGunzip } from "zlib";
1446
+ import { extract } from "tar";
1447
+ var BUNDLES_DIR = join5(
1448
+ process.env.SKILLVERSE_HOME || join5(process.env.HOME || "", ".skillverse"),
1449
+ "bundles"
1450
+ );
1451
+ async function ensureBundlesDir() {
1452
+ if (!existsSync5(BUNDLES_DIR)) {
1453
+ await mkdir4(BUNDLES_DIR, { recursive: true });
1454
+ }
1455
+ }
1456
+ async function createBundle(skillPath, skillName) {
1457
+ await ensureBundlesDir();
1458
+ const bundleName = `${skillName}-${Date.now()}.tar.gz`;
1459
+ const bundlePath = join5(BUNDLES_DIR, bundleName);
1460
+ return new Promise((resolve, reject) => {
1461
+ const output = createWriteStream(bundlePath);
1462
+ const archive = archiver("tar", {
1463
+ gzip: true,
1464
+ gzipOptions: { level: 9 }
1465
+ });
1466
+ output.on("close", () => {
1467
+ console.log(`\u{1F4E6} Bundle created: ${bundlePath} (${archive.pointer()} bytes)`);
1468
+ resolve(bundlePath);
1469
+ });
1470
+ archive.on("error", (err) => {
1471
+ reject(err);
1472
+ });
1473
+ archive.pipe(output);
1474
+ archive.directory(skillPath, false);
1475
+ archive.finalize();
1476
+ });
1477
+ }
1478
+ async function extractBundle(bundlePath, targetDir) {
1479
+ if (!existsSync5(bundlePath)) {
1480
+ throw new Error(`Bundle not found: ${bundlePath}`);
1481
+ }
1482
+ if (!existsSync5(targetDir)) {
1483
+ await mkdir4(targetDir, { recursive: true });
1484
+ }
1485
+ await pipeline(
1486
+ createReadStream(bundlePath),
1487
+ createGunzip(),
1488
+ extract({ cwd: targetDir })
1489
+ );
1490
+ console.log(`\u{1F4C2} Bundle extracted to: ${targetDir}`);
1491
+ }
1492
+ async function deleteBundle(bundlePath) {
1493
+ if (existsSync5(bundlePath)) {
1494
+ await rm4(bundlePath);
1495
+ console.log(`\u{1F5D1}\uFE0F Bundle deleted: ${bundlePath}`);
1496
+ }
1497
+ }
1498
+ async function getBundleSize(bundlePath) {
1499
+ if (!existsSync5(bundlePath)) {
1500
+ return 0;
1501
+ }
1502
+ const stats = await stat(bundlePath);
1503
+ return stats.size;
1504
+ }
1505
+ async function listBundles() {
1506
+ await ensureBundlesDir();
1507
+ const files = await readdir(BUNDLES_DIR);
1508
+ return files.filter((f) => f.endsWith(".tar.gz")).map((f) => join5(BUNDLES_DIR, f));
1509
+ }
1510
+ var bundleService = {
1511
+ createBundle,
1512
+ extractBundle,
1513
+ deleteBundle,
1514
+ getBundleSize,
1515
+ listBundles,
1516
+ BUNDLES_DIR
1517
+ };
1518
+
1519
+ // src/routes/marketplace.ts
1520
+ import { existsSync as existsSync6 } from "fs";
1521
+ var router3 = Router3();
1522
+ router3.get("/skills", async (req, res, next) => {
1523
+ try {
1524
+ const { search, page = "1", pageSize = "20" } = req.query;
1525
+ const where = {};
1526
+ if (search) {
1527
+ where.skill = {
1528
+ OR: [
1529
+ { name: { contains: search } },
1530
+ { description: { contains: search } }
1531
+ ]
1532
+ };
1533
+ }
1534
+ const [items, total] = await Promise.all([
1535
+ prisma.marketplaceSkill.findMany({
1536
+ where,
1537
+ include: {
1538
+ skill: true
1539
+ },
1540
+ orderBy: {
1541
+ downloads: "desc"
1542
+ },
1543
+ skip: (parseInt(page) - 1) * parseInt(pageSize),
1544
+ take: parseInt(pageSize)
1545
+ }),
1546
+ prisma.marketplaceSkill.count({ where })
1547
+ ]);
1548
+ res.json({
1549
+ success: true,
1550
+ data: {
1551
+ items,
1552
+ total,
1553
+ page: parseInt(page),
1554
+ pageSize: parseInt(pageSize)
1555
+ }
1556
+ });
1557
+ } catch (error) {
1558
+ next(error);
1559
+ }
1560
+ });
1561
+ router3.get("/skills/:id", async (req, res, next) => {
1562
+ try {
1563
+ const marketplaceSkill = await prisma.marketplaceSkill.findUnique({
1564
+ where: { id: req.params.id },
1565
+ include: {
1566
+ skill: true
1567
+ }
1568
+ });
1569
+ if (!marketplaceSkill) {
1570
+ throw new AppError(ErrorCode.NOT_FOUND, "Marketplace skill not found", 404);
1571
+ }
1572
+ res.json({
1573
+ success: true,
1574
+ data: marketplaceSkill
1575
+ });
1576
+ } catch (error) {
1577
+ next(error);
1578
+ }
1579
+ });
1580
+ router3.get("/download/:id", async (req, res, next) => {
1581
+ try {
1582
+ const marketplaceSkill = await prisma.marketplaceSkill.findUnique({
1583
+ where: { id: req.params.id },
1584
+ include: {
1585
+ skill: true
1586
+ }
1587
+ });
1588
+ if (!marketplaceSkill) {
1589
+ throw new AppError(ErrorCode.NOT_FOUND, "Marketplace skill not found", 404);
1590
+ }
1591
+ if (marketplaceSkill.skill.source === "git" && marketplaceSkill.skill.sourceUrl) {
1592
+ return res.json({
1593
+ success: true,
1594
+ data: {
1595
+ type: "git",
1596
+ sourceUrl: marketplaceSkill.skill.sourceUrl
1597
+ }
1598
+ });
1599
+ }
1600
+ if (marketplaceSkill.bundlePath && existsSync6(marketplaceSkill.bundlePath)) {
1601
+ res.setHeader("Content-Type", "application/gzip");
1602
+ res.setHeader(
1603
+ "Content-Disposition",
1604
+ `attachment; filename="${marketplaceSkill.skill.name}.tar.gz"`
1605
+ );
1606
+ return res.sendFile(marketplaceSkill.bundlePath);
1607
+ }
1608
+ throw new AppError(ErrorCode.NOT_FOUND, "Bundle not available for this skill", 404);
1609
+ } catch (error) {
1610
+ next(error);
1611
+ }
1612
+ });
1613
+ router3.post("/publish", async (req, res, next) => {
1614
+ try {
1615
+ const { skillId, publisherName } = req.body;
1616
+ if (!skillId) {
1617
+ return res.status(400).json({
1618
+ success: false,
1619
+ error: "skillId is required"
1620
+ });
1621
+ }
1622
+ const skill = await prisma.skill.findUnique({
1623
+ where: { id: skillId }
1624
+ });
1625
+ if (!skill) {
1626
+ throw new AppError(ErrorCode.NOT_FOUND, "Skill not found", 404);
1627
+ }
1628
+ const existingEntry = await prisma.marketplaceSkill.findUnique({
1629
+ where: { skillId }
1630
+ });
1631
+ if (existingEntry) {
1632
+ throw new AppError(ErrorCode.ALREADY_EXISTS, "Skill is already published to marketplace", 409);
1633
+ }
1634
+ let bundlePath = null;
1635
+ let bundleSize = null;
1636
+ if (skill.source === "local" && existsSync6(skill.storagePath)) {
1637
+ bundlePath = await bundleService.createBundle(skill.storagePath, skill.name);
1638
+ bundleSize = await bundleService.getBundleSize(bundlePath);
1639
+ }
1640
+ const marketplaceSkill = await prisma.marketplaceSkill.create({
1641
+ data: {
1642
+ skillId,
1643
+ publisherName: publisherName || "Anonymous",
1644
+ bundlePath,
1645
+ bundleSize
1646
+ },
1647
+ include: {
1648
+ skill: true
1649
+ }
1650
+ });
1651
+ res.status(201).json({
1652
+ success: true,
1653
+ data: marketplaceSkill,
1654
+ message: "Skill published to marketplace successfully"
1655
+ });
1656
+ } catch (error) {
1657
+ next(error);
1658
+ }
1659
+ });
1660
+ router3.post("/install/:id", async (req, res, next) => {
1661
+ try {
1662
+ const marketplaceSkill = await prisma.marketplaceSkill.findUnique({
1663
+ where: { id: req.params.id },
1664
+ include: {
1665
+ skill: true
1666
+ }
1667
+ });
1668
+ if (!marketplaceSkill) {
1669
+ throw new AppError(ErrorCode.NOT_FOUND, "Marketplace skill not found", 404);
1670
+ }
1671
+ const sourceSkill = marketplaceSkill.skill;
1672
+ if (sourceSkill.source === "git" && sourceSkill.sourceUrl) {
1673
+ const newSkill = await skillService.createSkillFromGit(
1674
+ sourceSkill.sourceUrl,
1675
+ sourceSkill.description || void 0
1676
+ );
1677
+ await prisma.marketplaceSkill.update({
1678
+ where: { id: req.params.id },
1679
+ data: { downloads: { increment: 1 } }
1680
+ });
1681
+ return res.status(201).json({
1682
+ success: true,
1683
+ data: newSkill,
1684
+ message: "Skill installed from marketplace successfully"
1685
+ });
1686
+ }
1687
+ if (sourceSkill.source === "local" && marketplaceSkill.bundlePath && existsSync6(marketplaceSkill.bundlePath)) {
1688
+ const newSkill = await skillService.createSkillFromBundle(
1689
+ marketplaceSkill.bundlePath,
1690
+ sourceSkill.name,
1691
+ sourceSkill.description || void 0
1692
+ );
1693
+ await prisma.marketplaceSkill.update({
1694
+ where: { id: req.params.id },
1695
+ data: { downloads: { increment: 1 } }
1696
+ });
1697
+ return res.status(201).json({
1698
+ success: true,
1699
+ data: newSkill,
1700
+ message: "Skill installed from marketplace successfully"
1701
+ });
1702
+ }
1703
+ return res.status(400).json({
1704
+ success: false,
1705
+ error: "Cannot install this skill. Bundle not available."
1706
+ });
1707
+ } catch (error) {
1708
+ next(error);
1709
+ }
1710
+ });
1711
+ router3.delete("/unpublish/:skillId", async (req, res, next) => {
1712
+ try {
1713
+ const marketplaceSkill = await prisma.marketplaceSkill.findUnique({
1714
+ where: { skillId: req.params.skillId }
1715
+ });
1716
+ if (!marketplaceSkill) {
1717
+ throw new AppError(ErrorCode.NOT_FOUND, "Skill is not published to marketplace", 404);
1718
+ }
1719
+ await prisma.marketplaceSkill.delete({
1720
+ where: { id: marketplaceSkill.id }
1721
+ });
1722
+ res.json({
1723
+ success: true,
1724
+ message: "Skill unpublished from marketplace successfully"
1725
+ });
1726
+ } catch (error) {
1727
+ next(error);
1728
+ }
1729
+ });
1730
+ var marketplace_default = router3;
1731
+
1732
+ // src/routes/dashboard.ts
1733
+ import { Router as Router4 } from "express";
1734
+ var router4 = Router4();
1735
+ router4.get("/stats", async (req, res, next) => {
1736
+ try {
1737
+ const [totalSkills, totalWorkspaces, totalLinks, marketplaceSkills, recentSkills] = await Promise.all([
1738
+ prisma.skill.count(),
1739
+ prisma.workspace.count(),
1740
+ prisma.skillWorkspace.count(),
1741
+ prisma.marketplaceSkill.count(),
1742
+ prisma.skill.findMany({
1743
+ orderBy: { installDate: "desc" },
1744
+ take: 5,
1745
+ include: {
1746
+ linkedWorkspaces: {
1747
+ include: {
1748
+ workspace: true
1749
+ }
1750
+ }
1751
+ }
1752
+ })
1753
+ ]);
1754
+ res.json({
1755
+ success: true,
1756
+ data: {
1757
+ totalSkills,
1758
+ totalWorkspaces,
1759
+ totalLinks,
1760
+ marketplaceSkills,
1761
+ recentSkills
1762
+ }
1763
+ });
1764
+ } catch (error) {
1765
+ next(error);
1766
+ }
1767
+ });
1768
+ router4.get("/activity", async (req, res, next) => {
1769
+ try {
1770
+ const [recentSkills, recentLinks, recentPublished] = await Promise.all([
1771
+ prisma.skill.findMany({
1772
+ orderBy: { createdAt: "desc" },
1773
+ take: 10,
1774
+ select: {
1775
+ id: true,
1776
+ name: true,
1777
+ source: true,
1778
+ createdAt: true
1779
+ }
1780
+ }),
1781
+ prisma.skillWorkspace.findMany({
1782
+ orderBy: { linkedAt: "desc" },
1783
+ take: 10,
1784
+ include: {
1785
+ skill: { select: { name: true } },
1786
+ workspace: { select: { name: true } }
1787
+ }
1788
+ }),
1789
+ prisma.marketplaceSkill.findMany({
1790
+ orderBy: { publishDate: "desc" },
1791
+ take: 10,
1792
+ include: {
1793
+ skill: { select: { name: true } }
1794
+ }
1795
+ })
1796
+ ]);
1797
+ const activities = [
1798
+ ...recentSkills.map((s) => ({
1799
+ type: "skill_added",
1800
+ date: s.createdAt,
1801
+ data: { skillName: s.name, source: s.source }
1802
+ })),
1803
+ ...recentLinks.map((l) => ({
1804
+ type: "skill_linked",
1805
+ date: l.linkedAt,
1806
+ data: { skillName: l.skill.name, workspaceName: l.workspace.name }
1807
+ })),
1808
+ ...recentPublished.map((p) => ({
1809
+ type: "skill_published",
1810
+ date: p.publishDate,
1811
+ data: { skillName: p.skill.name }
1812
+ }))
1813
+ ].sort((a, b) => b.date.getTime() - a.date.getTime());
1814
+ res.json({
1815
+ success: true,
1816
+ data: activities.slice(0, 20)
1817
+ });
1818
+ } catch (error) {
1819
+ next(error);
1820
+ }
1821
+ });
1822
+ var dashboard_default = router4;
1823
+
1824
+ // src/middleware/logger.ts
1825
+ function requestLogger(req, res, next) {
1826
+ const start = Date.now();
1827
+ res.on("finish", () => {
1828
+ const duration = Date.now() - start;
1829
+ console.log(`${req.method} ${req.path} - ${res.statusCode} - ${duration}ms`);
1830
+ });
1831
+ next();
1832
+ }
1833
+
1834
+ // src/index.ts
1835
+ dotenv2.config();
1836
+ var __filename2 = fileURLToPath2(import.meta.url);
1837
+ var __dirname2 = dirname2(__filename2);
1838
+ var app = express();
1839
+ var PORT = process.env.PORT || 3001;
1840
+ app.use(cors());
1841
+ app.use(express.json());
1842
+ app.use(express.urlencoded({ extended: true }));
1843
+ app.use(requestLogger);
1844
+ var possiblePublicDirs = [
1845
+ join6(__dirname2, "../public"),
1846
+ // Production: dist/index.js -> public
1847
+ join6(__dirname2, "../../public"),
1848
+ // Dev tsx might resolve here
1849
+ join6(process.cwd(), "public"),
1850
+ // Fallback: relative to cwd
1851
+ join6(process.cwd(), "server/public")
1852
+ // Fallback: from root
1853
+ ];
1854
+ var publicDir = possiblePublicDirs.find((dir) => existsSync7(dir));
1855
+ if (publicDir) {
1856
+ app.use(express.static(publicDir));
1857
+ console.log(`\u{1F4C2} Serving static files from: ${publicDir}`);
1858
+ } else {
1859
+ console.warn('\u26A0\uFE0F No public directory found. Run "npm run build" in client first.');
1860
+ }
1861
+ app.use("/api/skills", skills_default);
1862
+ app.use("/api/workspaces", workspaces_default);
1863
+ app.use("/api/marketplace", marketplace_default);
1864
+ app.use("/api/dashboard", dashboard_default);
1865
+ app.get("/health", (req, res) => {
1866
+ res.json({ status: "ok", timestamp: (/* @__PURE__ */ new Date()).toISOString() });
1867
+ });
1868
+ if (publicDir && existsSync7(publicDir)) {
1869
+ app.get("*", (req, res) => {
1870
+ res.sendFile(join6(publicDir, "index.html"));
1871
+ });
1872
+ }
1873
+ app.use(errorHandler);
1874
+ async function initializeStorage() {
1875
+ const skillverseHome = process.env.SKILLVERSE_HOME || join6(process.env.HOME || "", ".skillverse");
1876
+ const skillsDir = process.env.SKILLS_DIR || join6(skillverseHome, "skills");
1877
+ const marketplaceDir = process.env.MARKETPLACE_DIR || join6(skillverseHome, "marketplace");
1878
+ const dirs = [skillverseHome, skillsDir, marketplaceDir];
1879
+ for (const dir of dirs) {
1880
+ if (!existsSync7(dir)) {
1881
+ await mkdir5(dir, { recursive: true });
1882
+ console.log(`Created directory: ${dir}`);
1883
+ }
1884
+ }
1885
+ }
1886
+ async function startServer(port = parseInt(process.env.PORT || "3001")) {
1887
+ try {
1888
+ await initializeStorage();
1889
+ return new Promise((resolve) => {
1890
+ app.listen(port, () => {
1891
+ console.log(`\u{1F680} SkillVerse server running on http://localhost:${port}`);
1892
+ console.log(`\u{1F4C1} Storage: ${process.env.SKILLVERSE_HOME || join6(process.env.HOME || "", ".skillverse")}`);
1893
+ resolve();
1894
+ });
1895
+ });
1896
+ } catch (error) {
1897
+ console.error("Failed to start server:", error);
1898
+ process.exit(1);
1899
+ }
1900
+ }
1901
+ if (process.argv[1] === fileURLToPath2(import.meta.url)) {
1902
+ startServer();
1903
+ }
1904
+ export {
1905
+ startServer
1906
+ };
1907
+ //# sourceMappingURL=index.js.map