workspace.ts
6.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
import path from 'node:path';
import fs from 'node:fs';
import { WorkspaceStructure } from '../types/workspace-types';
import { logger } from './logger';
/**
* Defines the logical structure of the output workspace.
* output directory structure
coderio/
└── figmaName/ # Project root directory generated from a Figma URL
├── my-app/ # Generated project source code
├── process/ # Intermediate data and cache during generation
│ ├── validation/ # Validation reports, screenshots, and processed.json
│ └── ... # Other process artifacts
├── reports.html # Validation reports summary
└── checkpoint/ # Cache
├── coderio-cli.db
└── checkpoint.json
*/
class Workspace {
path: WorkspaceStructure | null = null;
initWorkspace(subPath: string, rootPath?: string, appName?: string): WorkspaceStructure {
if (this.path) {
return this.path;
}
const root = rootPath || (process.env.CODERIO_CLI_USER_CWD ?? process.cwd());
const coderioRoot = path.join(root, 'coderio');
const finalRoot = path.resolve(coderioRoot, subPath);
const app = appName || 'my-app';
const absoluteRoot = path.resolve(finalRoot);
const processDir = path.join(absoluteRoot, 'process');
const checkpointDir = path.join(absoluteRoot, 'checkpoint');
const debugDir = path.join(absoluteRoot, 'debug');
this.path = {
root: absoluteRoot,
app: path.join(absoluteRoot, app),
process: processDir,
debug: debugDir,
reports: path.join(absoluteRoot, 'reports.html'),
db: path.join(checkpointDir, 'coderio-cli.db'),
checkpoint: path.join(checkpointDir, 'checkpoint.json'),
};
return this.path;
}
/**
* Reset the cached workspace so the next `initWorkspace` call rebuilds it.
*
* The CLI runs once per process, but the service mode may run multiple
* jobs (potentially with different root paths / app names) within the same
* process, so it must clear the cached path between jobs.
*/
reset(): void {
this.path = null;
}
/**
* Delete all files and directories inside the workspace
* @param workspace - The workspace structure
* @param preserve - Optional list of relative paths (from workspace root) to preserve from deletion
*/
deleteWorkspace(workspace: WorkspaceStructure, preserve: string[] = []): void {
try {
if (!fs.existsSync(workspace.root)) return;
// Build set of normalized relative paths to preserve
const preserveFiles = new Set(preserve.map(p => path.normalize(p)));
// Collect ancestor directories of preserved files
const preserveDirs = new Set<string>();
for (const p of preserveFiles) {
let dir = path.dirname(p);
while (dir !== '.') {
preserveDirs.add(dir);
dir = path.dirname(dir);
}
}
const deleteRecursive = (dirPath: string, relativeTo: string = '') => {
const entries = fs.readdirSync(dirPath);
for (const entry of entries) {
const fullPath = path.join(dirPath, entry);
const relPath = relativeTo ? path.join(relativeTo, entry) : entry;
if (preserveFiles.has(relPath)) {
continue; // This file is preserved
}
if (preserveDirs.has(relPath)) {
// Directory contains preserved files, recurse into it
deleteRecursive(fullPath, relPath);
} else {
fs.rmSync(fullPath, { recursive: true, force: true });
}
}
};
deleteRecursive(workspace.root);
} catch (error) {
const errorMessage = error instanceof Error ? error.message : String(error);
// The `safe-delete` hook in this environment intercepts every
// filesystem delete and complains about its (failed) trash step, but
// the underlying delete still succeeds at the OS level. Treat that
// specific error as harmless noise rather than a scary warning.
if (errorMessage.includes('[safe-delete]')) {
logger.printInfoLog(`Workspace reset (safe-delete hook noted): ${errorMessage}`);
} else {
logger.printWarnLog(`Failed to delete workspace: ${errorMessage}`);
}
}
}
/**
* Resolve the absolute path to the source code directory
* @param paths - The workspace structure
* @param srcSubPath - The subpath to the source code directory
* @returns The absolute path to the source code directory
*/
resolveAppSrc(paths: WorkspaceStructure, srcSubPath: string): string {
return path.join(paths.app, 'src', srcSubPath);
}
/**
* Resolve component alias path to absolute filesystem path.
*
* Handles various path formats:
* - @/components/Button → /workspace/my-app/src/components/Button/index.tsx
* - @/src/components/Button → /workspace/my-app/src/components/Button/index.tsx
* - components/Button → /workspace/my-app/src/components/Button/index.tsx
*
*/
resolveComponentPath(aliasPath: string): string {
// Normalize path separators for robustness across platforms.
const normalizedAlias = aliasPath.replace(/\\/g, '/');
// Step 1: Strip @/ prefix if present
let relativePath = normalizedAlias.startsWith('@/')
? normalizedAlias.substring(2) // '@/components/Button' → 'components/Button'
: normalizedAlias;
// Step 2: Strip 'src/' prefix if present (resolveAppSrc adds it)
// '@/src/components/Button' → 'components/Button'
if (relativePath.startsWith('src/')) {
relativePath = relativePath.substring(4);
}
// Step 3: Ensure path ends with /index.tsx (all components follow this convention)
if (!relativePath.endsWith('.tsx') && !relativePath.endsWith('.ts')) {
relativePath = `${relativePath}/index.tsx`;
}
return relativePath;
}
}
export const workspaceManager = new Workspace();