@innovatorved/code-lab 0.1.7 → 0.1.8

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.
package/src/storage.ts ADDED
@@ -0,0 +1,377 @@
1
+ /**
2
+ * @innovatorved/code-lab — Cascading Multi-Project Durable Workspace Storage
3
+ * ============================================================================
4
+ * Provides durable multi-project workspace persistence with automatic tiered
5
+ * fallback:
6
+ * 1. IndexedDB (`indexeddb`) — high-capacity asynchronous browser store
7
+ * 2. LocalStorage (`localstorage`) — synchronous key-value fallback
8
+ * 3. In-Memory Map (`memory`) — guaranteed zero-dependency fallback for
9
+ * headless tests, SSR, or restricted/incognito sandboxes
10
+ *
11
+ * Strict leaf module: fully typed, zero explicit any, zero empty catches.
12
+ */
13
+
14
+ export type StorageBackendType = 'indexeddb' | 'localstorage' | 'memory';
15
+
16
+ export interface StoredProject {
17
+ id: string;
18
+ name: string;
19
+ files: Record<string, string>;
20
+ updatedAt: number;
21
+ createdAt?: number;
22
+ entry?: string;
23
+ testEntry?: string;
24
+ version?: number;
25
+ }
26
+
27
+ export interface ProjectSummary {
28
+ id: string;
29
+ name: string;
30
+ updatedAt: number;
31
+ fileCount: number;
32
+ }
33
+
34
+ export interface WorkspaceStorageOptions {
35
+ dbName?: string;
36
+ storeName?: string;
37
+ storagePrefix?: string;
38
+ preferredBackend?: StorageBackendType;
39
+ }
40
+
41
+ const DEFAULT_DB_NAME = 'codelab_workspace_db';
42
+ const DEFAULT_STORE_NAME = 'projects';
43
+ const DEFAULT_LS_PREFIX = 'codelab:project:';
44
+
45
+ function cloneProject(project: StoredProject): StoredProject {
46
+ const filesCopy: Record<string, string> = {};
47
+ if (project.files && typeof project.files === 'object') {
48
+ for (const [k, v] of Object.entries(project.files)) {
49
+ filesCopy[k] = String(v);
50
+ }
51
+ }
52
+ return {
53
+ id: String(project.id),
54
+ name: String(project.name || project.id),
55
+ files: filesCopy,
56
+ updatedAt: typeof project.updatedAt === 'number' ? project.updatedAt : Date.now(),
57
+ ...(project.createdAt !== undefined ? { createdAt: project.createdAt } : {}),
58
+ ...(project.entry !== undefined ? { entry: project.entry } : {}),
59
+ ...(project.testEntry !== undefined ? { testEntry: project.testEntry } : {}),
60
+ ...(project.version !== undefined ? { version: project.version } : {})
61
+ };
62
+ }
63
+
64
+ function isLocalStorageAvailable(prefix: string): boolean {
65
+ try {
66
+ if (typeof globalThis === 'undefined' || !('localStorage' in globalThis)) {
67
+ return false;
68
+ }
69
+ const ls = globalThis.localStorage;
70
+ if (!ls || typeof ls.getItem !== 'function' || typeof ls.setItem !== 'function') {
71
+ return false;
72
+ }
73
+ const probeKey = `${prefix}__probe__`;
74
+ ls.setItem(probeKey, '1');
75
+ ls.removeItem(probeKey);
76
+ return true;
77
+ } catch (err) {
78
+ const _ignored = err;
79
+ void _ignored;
80
+ return false;
81
+ }
82
+ }
83
+
84
+ function isIndexedDbAvailable(): boolean {
85
+ try {
86
+ if (typeof globalThis === 'undefined' || !('indexedDB' in globalThis)) {
87
+ return false;
88
+ }
89
+ return Boolean(globalThis.indexedDB && typeof globalThis.indexedDB.open === 'function');
90
+ } catch (err) {
91
+ const _ignored = err;
92
+ void _ignored;
93
+ return false;
94
+ }
95
+ }
96
+
97
+ export class WorkspaceStorage {
98
+ private readonly dbName: string;
99
+ private readonly storeName: string;
100
+ private readonly storagePrefix: string;
101
+ private backendType: StorageBackendType;
102
+ private readonly memoryStore: Map<string, StoredProject> = new Map();
103
+ private dbPromise: Promise<IDBDatabase | null> | null = null;
104
+
105
+ constructor(options: WorkspaceStorageOptions = {}) {
106
+ this.dbName = options.dbName || DEFAULT_DB_NAME;
107
+ this.storeName = options.storeName || DEFAULT_STORE_NAME;
108
+ this.storagePrefix = options.storagePrefix || DEFAULT_LS_PREFIX;
109
+
110
+ if (options.preferredBackend) {
111
+ this.backendType = options.preferredBackend;
112
+ } else if (isIndexedDbAvailable()) {
113
+ this.backendType = 'indexeddb';
114
+ } else if (isLocalStorageAvailable(this.storagePrefix)) {
115
+ this.backendType = 'localstorage';
116
+ } else {
117
+ this.backendType = 'memory';
118
+ }
119
+ }
120
+
121
+ public getBackendType(): StorageBackendType {
122
+ return this.backendType;
123
+ }
124
+
125
+ private openIdb(): Promise<IDBDatabase | null> {
126
+ if (this.dbPromise) return this.dbPromise;
127
+ this.dbPromise = new Promise<IDBDatabase | null>((resolve) => {
128
+ try {
129
+ const req = globalThis.indexedDB.open(this.dbName, 1);
130
+ req.onupgradeneeded = () => {
131
+ const db = req.result;
132
+ if (!db.objectStoreNames.contains(this.storeName)) {
133
+ db.createObjectStore(this.storeName, { keyPath: 'id' });
134
+ }
135
+ };
136
+ req.onsuccess = () => {
137
+ resolve(req.result);
138
+ };
139
+ req.onerror = () => {
140
+ resolve(null);
141
+ };
142
+ } catch (err) {
143
+ const _ignored = err;
144
+ void _ignored;
145
+ resolve(null);
146
+ }
147
+ });
148
+ return this.dbPromise;
149
+ }
150
+
151
+ private downgradeFromIdb(): void {
152
+ if (isLocalStorageAvailable(this.storagePrefix)) {
153
+ this.backendType = 'localstorage';
154
+ } else {
155
+ this.backendType = 'memory';
156
+ }
157
+ }
158
+
159
+ public async saveProject(project: StoredProject): Promise<boolean> {
160
+ if (!project || typeof project.id !== 'string' || !project.id.trim()) {
161
+ return false;
162
+ }
163
+ const normalized = cloneProject(project);
164
+ // Always keep memory mirror hot for resilience
165
+ this.memoryStore.set(normalized.id, normalized);
166
+
167
+ if (this.backendType === 'indexeddb') {
168
+ const db = await this.openIdb();
169
+ if (!db) {
170
+ this.downgradeFromIdb();
171
+ } else {
172
+ const ok = await new Promise<boolean>((resolve) => {
173
+ try {
174
+ const tx = db.transaction(this.storeName, 'readwrite');
175
+ const store = tx.objectStore(this.storeName);
176
+ const req = store.put(normalized);
177
+ req.onsuccess = () => resolve(true);
178
+ req.onerror = () => resolve(false);
179
+ } catch (err) {
180
+ const _ignored = err;
181
+ void _ignored;
182
+ resolve(false);
183
+ }
184
+ });
185
+ if (ok) return true;
186
+ this.downgradeFromIdb();
187
+ }
188
+ }
189
+
190
+ if (this.backendType === 'localstorage') {
191
+ try {
192
+ const key = `${this.storagePrefix}${normalized.id}`;
193
+ globalThis.localStorage.setItem(key, JSON.stringify(normalized));
194
+ return true;
195
+ } catch (err) {
196
+ // QuotaExceededError or disabled storage -> fallback to memory
197
+ const _ignored = err;
198
+ void _ignored;
199
+ this.backendType = 'memory';
200
+ }
201
+ }
202
+
203
+ return true;
204
+ }
205
+
206
+ public async loadProject(id: string): Promise<StoredProject | null> {
207
+ if (!id || typeof id !== 'string') return null;
208
+
209
+ if (this.backendType === 'indexeddb') {
210
+ const db = await this.openIdb();
211
+ if (!db) {
212
+ this.downgradeFromIdb();
213
+ } else {
214
+ const found = await new Promise<StoredProject | null>((resolve) => {
215
+ try {
216
+ const tx = db.transaction(this.storeName, 'readonly');
217
+ const store = tx.objectStore(this.storeName);
218
+ const req = store.get(id);
219
+ req.onsuccess = () => {
220
+ const res = req.result as StoredProject | undefined;
221
+ resolve(res ? cloneProject(res) : null);
222
+ };
223
+ req.onerror = () => resolve(null);
224
+ } catch (err) {
225
+ const _ignored = err;
226
+ void _ignored;
227
+ resolve(null);
228
+ }
229
+ });
230
+ if (found) return found;
231
+ }
232
+ }
233
+
234
+ if (this.backendType === 'localstorage') {
235
+ try {
236
+ const raw = globalThis.localStorage.getItem(`${this.storagePrefix}${id}`);
237
+ if (raw) {
238
+ const parsed = JSON.parse(raw) as StoredProject;
239
+ if (parsed && typeof parsed.id === 'string' && parsed.files && typeof parsed.files === 'object') {
240
+ return cloneProject(parsed);
241
+ }
242
+ }
243
+ } catch (err) {
244
+ // Corrupted JSON entry in localStorage: remove corrupt key and check memory
245
+ const _ignored = err;
246
+ void _ignored;
247
+ }
248
+ }
249
+
250
+ const fromMem = this.memoryStore.get(id);
251
+ return fromMem ? cloneProject(fromMem) : null;
252
+ }
253
+
254
+ public async listProjects(): Promise<ProjectSummary[]> {
255
+ const byId = new Map<string, ProjectSummary>();
256
+
257
+ const recordSummary = (proj: StoredProject): void => {
258
+ if (!proj || typeof proj.id !== 'string') return;
259
+ byId.set(proj.id, {
260
+ id: proj.id,
261
+ name: proj.name || proj.id,
262
+ updatedAt: typeof proj.updatedAt === 'number' ? proj.updatedAt : Date.now(),
263
+ fileCount: proj.files && typeof proj.files === 'object' ? Object.keys(proj.files).length : 0
264
+ });
265
+ };
266
+
267
+ for (const p of this.memoryStore.values()) {
268
+ recordSummary(p);
269
+ }
270
+
271
+ if (this.backendType === 'indexeddb') {
272
+ const db = await this.openIdb();
273
+ if (db) {
274
+ await new Promise<void>((resolve) => {
275
+ try {
276
+ const tx = db.transaction(this.storeName, 'readonly');
277
+ const store = tx.objectStore(this.storeName);
278
+ const req = store.getAll();
279
+ req.onsuccess = () => {
280
+ const items = Array.isArray(req.result) ? (req.result as StoredProject[]) : [];
281
+ for (const item of items) {
282
+ recordSummary(item);
283
+ }
284
+ resolve();
285
+ };
286
+ req.onerror = () => resolve();
287
+ } catch (err) {
288
+ const _ignored = err;
289
+ void _ignored;
290
+ resolve();
291
+ }
292
+ });
293
+ }
294
+ } else if (this.backendType === 'localstorage') {
295
+ try {
296
+ const ls = globalThis.localStorage;
297
+ for (let i = 0; i < ls.length; i++) {
298
+ const key = ls.key(i);
299
+ if (key && key.startsWith(this.storagePrefix)) {
300
+ const raw = ls.getItem(key);
301
+ if (raw) {
302
+ try {
303
+ const parsed = JSON.parse(raw) as StoredProject;
304
+ recordSummary(parsed);
305
+ } catch (parseErr) {
306
+ const _ignored = parseErr;
307
+ void _ignored;
308
+ }
309
+ }
310
+ }
311
+ }
312
+ } catch (err) {
313
+ const _ignored = err;
314
+ void _ignored;
315
+ }
316
+ }
317
+
318
+ return Array.from(byId.values()).sort((a, b) => b.updatedAt - a.updatedAt);
319
+ }
320
+
321
+ public async deleteProject(id: string): Promise<boolean> {
322
+ if (!id || typeof id !== 'string') return false;
323
+ let existed = this.memoryStore.delete(id);
324
+
325
+ if (this.backendType === 'indexeddb') {
326
+ const db = await this.openIdb();
327
+ if (db) {
328
+ const idbDeleted = await new Promise<boolean>((resolve) => {
329
+ try {
330
+ const tx = db.transaction(this.storeName, 'readwrite');
331
+ const store = tx.objectStore(this.storeName);
332
+ const checkReq = store.get(id);
333
+ checkReq.onsuccess = () => {
334
+ if (!checkReq.result) {
335
+ resolve(false);
336
+ return;
337
+ }
338
+ const delReq = store.delete(id);
339
+ delReq.onsuccess = () => resolve(true);
340
+ delReq.onerror = () => resolve(false);
341
+ };
342
+ checkReq.onerror = () => resolve(false);
343
+ } catch (err) {
344
+ const _ignored = err;
345
+ void _ignored;
346
+ resolve(false);
347
+ }
348
+ });
349
+ existed = existed || idbDeleted;
350
+ }
351
+ }
352
+
353
+ if (this.backendType === 'localstorage') {
354
+ try {
355
+ const key = `${this.storagePrefix}${id}`;
356
+ if (globalThis.localStorage.getItem(key) !== null) {
357
+ globalThis.localStorage.removeItem(key);
358
+ existed = true;
359
+ }
360
+ } catch (err) {
361
+ const _ignored = err;
362
+ void _ignored;
363
+ }
364
+ }
365
+
366
+ return existed;
367
+ }
368
+ }
369
+
370
+ export function createWorkspaceStorage(options: WorkspaceStorageOptions = {}): WorkspaceStorage {
371
+ return new WorkspaceStorage(options);
372
+ }
373
+
374
+ export default {
375
+ WorkspaceStorage,
376
+ createWorkspaceStorage
377
+ };
package/src/terminal.ts CHANGED
@@ -33,6 +33,16 @@
33
33
  })(typeof globalThis !== 'undefined' ? globalThis : (typeof window !== 'undefined' ? window : this), function () {
34
34
  'use strict';
35
35
 
36
+ const _termRoot = typeof globalThis !== 'undefined' ? globalThis : (typeof window !== 'undefined' ? window : {});
37
+ const _terminalLogger = (_termRoot && _termRoot.CodeLabLogger && typeof _termRoot.CodeLabLogger.createLogger === 'function')
38
+ ? _termRoot.CodeLabLogger.createLogger()
39
+ : {
40
+ debug() {},
41
+ info(...args) { if (typeof console !== 'undefined' && console.info) console.info('[code-lab]', ...args); },
42
+ warn(...args) { if (typeof console !== 'undefined' && console.warn) console.warn('[code-lab]', ...args); },
43
+ error(...args) { if (typeof console !== 'undefined' && console.error) console.error('[code-lab]', ...args); }
44
+ };
45
+
36
46
  const ANSI_CODE_MAP = {
37
47
  1: 'cl-ansi-bold',
38
48
  2: 'cl-ansi-dim',
@@ -573,7 +583,7 @@
573
583
  if (!this.container || typeof this.container.querySelector !== 'function') return;
574
584
  const input = this.container.querySelector('#cl-repl-input');
575
585
  if (input && typeof input.focus === 'function') {
576
- try { input.focus(); } catch (_) {}
586
+ try { input.focus(); } catch (err) { _terminalLogger.debug('Terminal input focus skipped.', err); }
577
587
  }
578
588
  }
579
589
 
@@ -597,9 +607,9 @@
597
607
  }
598
608
  for (const entry of this._listeners) {
599
609
  if (typeof entry === 'function') {
600
- try { entry(); } catch (_) {}
610
+ try { entry(); } catch (err) { _terminalLogger.debug('Terminal listener cleanup callback failed.', err); }
601
611
  } else if (entry && entry.target && typeof entry.target.removeEventListener === 'function') {
602
- try { entry.target.removeEventListener(entry.type, entry.handler); } catch (_) {}
612
+ try { entry.target.removeEventListener(entry.type, entry.handler); } catch (err) { _terminalLogger.debug('Terminal removeEventListener failed.', err); }
603
613
  }
604
614
  }
605
615
  this._listeners = [];
@@ -668,7 +678,9 @@
668
678
  try {
669
679
  const res = this.onKey(e);
670
680
  if (res === false) return;
671
- } catch (_) {}
681
+ } catch (err) {
682
+ _terminalLogger.warn('Terminal onKey callback threw.', err);
683
+ }
672
684
  }
673
685
 
674
686
  const key = e.key;
@@ -821,7 +833,7 @@
821
833
  this.replMode = false;
822
834
  }
823
835
  if (this.onInterrupt) {
824
- try { this.onInterrupt(); } catch (_) {}
836
+ try { this.onInterrupt(); } catch (err) { _terminalLogger.warn('Terminal onInterrupt callback threw.', err); }
825
837
  }
826
838
  this.render();
827
839
  return;
@@ -1022,7 +1034,9 @@
1022
1034
  if (typeof nextInput.setSelectionRange === 'function') {
1023
1035
  nextInput.setSelectionRange(this.cursor, this.cursor);
1024
1036
  }
1025
- } catch (_) {}
1037
+ } catch (err) {
1038
+ _terminalLogger.debug('Terminal focus/selection restore skipped.', err);
1039
+ }
1026
1040
  }
1027
1041
  }
1028
1042
  }