0
# Store Management
1
2
The store system provides reactive state management for files, compilation state, and REPL configuration. It handles file operations, Vue compilation, import map management, and state serialization for URL persistence.
3
4
## Capabilities
5
6
### Store Factory
7
8
Creates a new REPL store instance with reactive state management and file compilation.
9
10
```typescript { .api }
11
/**
12
* Creates and configures a REPL store instance with reactive state management
13
* @param state - Partial state configuration to override defaults
14
* @param serializedState - Optional serialized state string to restore from URL hash
15
* @returns Configured ReplStore instance with reactive file management
16
*/
17
function useStore(
18
state?: Partial<StoreState>,
19
serializedState?: string
20
): ReplStore;
21
22
interface StoreState {
23
/** Files in the REPL mapped by filename */
24
files: Record<string, File>;
25
/** Currently active filename being edited */
26
activeFilename: string;
27
/** Main entry file (typically src/App.vue) */
28
mainFile: string;
29
/** Template code for new files */
30
template: {
31
welcomeSFC?: string;
32
newSFC?: string;
33
};
34
/** Built-in import map for Vue and dependencies */
35
builtinImportMap: ImportMap;
36
/** Compilation errors and warnings */
37
errors: (string | Error)[];
38
/** Whether output panel is visible (mobile) */
39
showOutput: boolean;
40
/** Current output mode tab */
41
outputMode: OutputModes;
42
/** Vue SFC compilation options */
43
sfcOptions: SFCOptions;
44
/** SSR compilation results */
45
ssrOutput: {
46
html: string;
47
context: unknown;
48
};
49
/** Vue compiler instance */
50
compiler: typeof defaultCompiler;
51
/** Vue version for CDN imports */
52
vueVersion: string | null;
53
/** Locale for language tools */
54
locale: string | undefined;
55
/** TypeScript version */
56
typescriptVersion: string;
57
/** Dependency versions map */
58
dependencyVersion: Record<string, string>;
59
/** Function to reload language tools */
60
reloadLanguageTools?: (() => void) | undefined;
61
}
62
```
63
64
**Usage Examples:**
65
66
```typescript
67
import { useStore, useVueImportMap } from "@vue/repl/core";
68
69
// Basic store creation
70
const store = useStore();
71
72
// Store with custom configuration
73
const store = useStore({
74
showOutput: ref(true),
75
outputMode: ref('preview'),
76
vueVersion: ref('3.4.0')
77
});
78
79
// Store with URL state restoration
80
const store = useStore({}, location.hash);
81
82
// Store with custom import map
83
const { importMap, vueVersion } = useVueImportMap({
84
vueVersion: '3.4.0'
85
});
86
const store = useStore({
87
builtinImportMap: importMap,
88
vueVersion
89
});
90
```
91
92
### File Management
93
94
Methods for managing files in the REPL store.
95
96
```typescript { .api }
97
/**
98
* Set the active file being edited
99
* @param filename - Filename to make active
100
*/
101
function setActive(filename: string): void;
102
103
/**
104
* Add a new file to the store
105
* @param fileOrFilename - File instance or filename string
106
*/
107
function addFile(fileOrFilename: string | File): void;
108
109
/**
110
* Delete a file from the store with confirmation
111
* @param filename - Filename to delete
112
*/
113
function deleteFile(filename: string): void;
114
115
/**
116
* Rename an existing file with validation
117
* @param oldFilename - Current filename
118
* @param newFilename - New filename
119
*/
120
function renameFile(oldFilename: string, newFilename: string): void;
121
122
/**
123
* Export all files as plain object (strips src/ prefix)
124
* @returns Object mapping filenames to code content
125
*/
126
function getFiles(): Record<string, string>;
127
128
/**
129
* Import files from plain object, replacing current files
130
* @param newFiles - Object mapping filenames to code content
131
* @param mainFile - Optional main file override
132
*/
133
function setFiles(newFiles: Record<string, string>, mainFile?: string): Promise<void>;
134
```
135
136
**Usage Examples:**
137
138
```typescript
139
// Add new files
140
store.addFile('src/components/Button.vue');
141
store.addFile(new File('src/utils/helpers.ts', 'export const helper = () => {}'));
142
143
// Set active file
144
store.setActive('src/components/Button.vue');
145
146
// Rename file
147
store.renameFile('src/Button.vue', 'src/components/Button.vue');
148
149
// Export/import files
150
const files = store.getFiles();
151
await store.setFiles({
152
'App.vue': '<template><div>Hello</div></template>',
153
'utils.ts': 'export const util = () => {}'
154
});
155
156
// Delete file (shows confirmation dialog)
157
store.deleteFile('src/old-component.vue');
158
```
159
160
### Configuration Management
161
162
Methods for managing import maps and TypeScript configuration.
163
164
```typescript { .api }
165
/**
166
* Get current import map configuration
167
* @returns Parsed import map object
168
*/
169
function getImportMap(): ImportMap;
170
171
/**
172
* Update import map configuration
173
* @param map - New import map configuration
174
* @param merge - Whether to merge with existing map
175
*/
176
function setImportMap(map: ImportMap, merge?: boolean): void;
177
178
/**
179
* Get current TypeScript configuration
180
* @returns Parsed tsconfig object
181
*/
182
function getTsConfig(): Record<string, any>;
183
```
184
185
**Usage Examples:**
186
187
```typescript
188
// Get current import map
189
const currentMap = store.getImportMap();
190
191
// Set new import map
192
store.setImportMap({
193
imports: {
194
'lodash': 'https://cdn.skypack.dev/lodash',
195
'axios': 'https://cdn.skypack.dev/axios'
196
}
197
});
198
199
// Merge with existing import map
200
store.setImportMap({
201
imports: {
202
'dayjs': 'https://cdn.skypack.dev/dayjs'
203
}
204
}, true);
205
206
// Get TypeScript config
207
const tsConfig = store.getTsConfig();
208
```
209
210
### State Serialization
211
212
Methods for persisting and restoring store state via URL hash.
213
214
```typescript { .api }
215
/**
216
* Serialize store state to URL hash string
217
* @returns Base64 encoded state string with # prefix
218
*/
219
function serialize(): string;
220
221
/**
222
* Restore store state from serialized string
223
* @param serializedState - Base64 encoded state string
224
* @param checkBuiltinImportMap - Whether to apply built-in import map
225
*/
226
function deserialize(serializedState: string, checkBuiltinImportMap?: boolean): void;
227
```
228
229
**Usage Examples:**
230
231
```typescript
232
// Serialize current state
233
const stateString = store.serialize();
234
console.log(stateString); // "#eyJBcHAudnVlIjoiPHRlbXBsYXRlPi4uLiJ9"
235
236
// Persist to URL
237
history.replaceState({}, '', store.serialize());
238
239
// Restore from URL
240
store.deserialize(location.hash);
241
242
// Watch for changes and auto-persist
243
watchEffect(() => {
244
history.replaceState({}, '', store.serialize());
245
});
246
```
247
248
### Store Initialization
249
250
Initialize store watchers and compilation system.
251
252
```typescript { .api }
253
/**
254
* Initialize store watchers, compilation system, and default files
255
* Must be called before using the store
256
*/
257
function init(): void;
258
```
259
260
**Usage Example:**
261
262
```typescript
263
const store = useStore();
264
store.init(); // Start compilation watchers and initialize default files
265
```
266
267
## Store State Properties
268
269
The ReplStore interface provides access to reactive state properties:
270
271
```typescript { .api }
272
interface ReplStore extends UnwrapRef<StoreState> {
273
/** Currently active file object */
274
activeFile: File;
275
/** Whether compiler is loading */
276
loading: boolean;
277
278
// All methods listed above
279
init(): void;
280
setActive(filename: string): void;
281
// ... (other methods)
282
}
283
```
284
285
## Constants
286
287
```typescript { .api }
288
/** Standard filename for import map configuration */
289
const importMapFile: string = 'import-map.json';
290
291
/** Standard filename for TypeScript configuration */
292
const tsconfigFile: string = 'tsconfig.json';
293
```
294
295
## Error Handling
296
297
The store system handles various error conditions:
298
299
- **File not found**: `renameFile` and `deleteFile` validate file existence
300
- **Invalid JSON**: Import map and tsconfig parsing errors are captured in `errors` array
301
- **Compilation errors**: Vue SFC compilation errors are stored in `errors` array
302
- **Serialization errors**: Failed deserialization shows alert and falls back to default file