Repository navigation
Expand file tree
/
Copy pathshared.js
More file actions
1600 lines (1485 loc) · 66.3 KB
/
Copy pathshared.js
File metadata and controls
1600 lines (1485 loc) · 66.3 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
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* PeaBox shared helpers. Loaded as a classic script in the renderer and
required by the main process and tests (UMD, no dependencies).
This module provides utility functions for:
- Path normalization and validation
- File extension / language detection
- Git status parsing (porcelain v1 -z and -b)
- State and session sanitization
- Formatting utilities (bytes, duration, time)
- Branch name validation
- Search and matching algorithms (fuzzy files/commands)
- Document symbol extraction
- Dependency-free text transforms and literal replacement
All functions are pure where possible and have no external dependencies.
*/
(function (root, factory) {
if (typeof module === 'object' && module.exports) module.exports = factory();
else root.PeaBoxShared = factory();
})(typeof globalThis !== 'undefined' ? globalThis : this, function () {
'use strict';
var DEFAULT_EXCLUDES = [
'node_modules', '.git', 'dist', 'build', 'out', '.next', '.nuxt', 'coverage',
'.venv', 'venv', '__pycache__', '.cache', '.idea', '.vs', 'target', '.turbo'
];
var LANGUAGES = {
py: 'python', pyw: 'python', js: 'javascript', mjs: 'javascript', cjs: 'javascript',
jsx: 'javascript', ts: 'typescript', tsx: 'typescript', json: 'json', jsonc: 'json',
html: 'html', htm: 'html', css: 'css', scss: 'scss', less: 'less', md: 'markdown',
markdown: 'markdown', go: 'go', rs: 'rust', c: 'c', h: 'cpp', cc: 'cpp', cpp: 'cpp',
cxx: 'cpp', hpp: 'cpp', cs: 'csharp', java: 'java', kt: 'kotlin', php: 'php',
rb: 'ruby', sql: 'sql', ps1: 'powershell', psm1: 'powershell', sh: 'shell',
bash: 'shell', zsh: 'shell', yml: 'yaml', yaml: 'yaml', xml: 'xml', svg: 'xml',
toml: 'ini', ini: 'ini', conf: 'ini', vue: 'html', svelte: 'html', lua: 'lua',
swift: 'swift', dart: 'dart', r: 'r', pl: 'perl', bat: 'bat', cmd: 'bat',
dockerfile: 'dockerfile', makefile: 'makefile', gradle: 'groovy', groovy: 'groovy'
};
var BADGES = {
js: ['JS', 'ext-js'], mjs: ['JS', 'ext-js'], cjs: ['JS', 'ext-js'], jsx: ['JSX', 'ext-js'],
ts: ['TS', 'ext-ts'], tsx: ['TSX', 'ext-ts'], py: ['PY', 'ext-py'], pyw: ['PY', 'ext-py'],
go: ['GO', 'ext-go'], rs: ['RS', 'ext-rs'], json: ['{}', 'ext-json'], jsonc: ['{}', 'ext-json'],
html: ['<>', 'ext-html'], htm: ['<>', 'ext-html'], css: ['CSS', 'ext-css'], scss: ['SCSS', 'ext-css'],
less: ['LESS', 'ext-css'], md: ['MD', 'ext-md'], markdown: ['MD', 'ext-md'],
c: ['C', 'ext-c'], h: ['H', 'ext-c'], cpp: ['C++', 'ext-c'], hpp: ['H++', 'ext-c'],
cs: ['C#', 'ext-cs'], java: ['JAVA', 'ext-java'], kt: ['KT', 'ext-java'], php: ['PHP', 'ext-php'],
rb: ['RB', 'ext-rb'], sql: ['SQL', 'ext-sql'], ps1: ['PS', 'ext-ps'], sh: ['SH', 'ext-sh'],
bash: ['SH', 'ext-sh'], yml: ['YML', 'ext-yml'], yaml: ['YML', 'ext-yml'], xml: ['XML', 'ext-xml'],
svg: ['SVG', 'ext-xml'], toml: ['TML', 'ext-ini'], ini: ['INI', 'ext-ini'], lua: ['LUA', 'ext-lua'],
swift: ['SW', 'ext-swift'], dart: ['DART', 'ext-dart'], vue: ['VUE', 'ext-vue'], svelte: ['SVELTE', 'ext-vue']
};
function str(v) { return v === null || v === undefined ? '' : String(v); }
function basename(p) {
var s = str(p).replace(/[\\/]+$/, '');
var i = Math.max(s.lastIndexOf('/'), s.lastIndexOf('\\'));
return i >= 0 ? s.slice(i + 1) : s;
}
function dirname(p) {
var s = str(p).replace(/[\\/]+$/, '');
var i = Math.max(s.lastIndexOf('/'), s.lastIndexOf('\\'));
if (i <= 0) return i === 0 ? s.slice(0, 1) : '';
return s.slice(0, i);
}
function extname(p) {
var b = basename(p);
var i = b.lastIndexOf('.');
return i > 0 ? b.slice(i + 1).toLowerCase() : b.toLowerCase();
}
function normalizeLanguage(file) {
var b = basename(file).toLowerCase();
if (b === 'dockerfile') return 'dockerfile';
if (b === 'makefile') return 'makefile';
return LANGUAGES[extname(file)] || 'plaintext';
}
function fileBadge(file) {
var b = basename(file).toLowerCase();
if (b === 'dockerfile') return { label: 'DOCKER', cls: 'ext-docker' };
if (b === 'makefile') return { label: 'MAKE', cls: 'ext-make' };
if (b.charAt(0) === '.' && b.indexOf('.', 1) < 0) return { label: 'DOT', cls: 'ext-file' };
var e = extname(file);
var hit = BADGES[e];
if (hit) return { label: hit[0], cls: hit[1] };
return { label: e ? e.slice(0, 3).toUpperCase() : 'FILE', cls: 'ext-file' };
}
function escapeHtml(value) {
return str(value).replace(/[&<>"']/g, function (c) {
return { '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[c];
});
}
function clamp(n, min, max) {
n = Number(n);
if (!isFinite(n)) n = min;
return Math.min(max, Math.max(min, Math.round(n)));
}
function normalizePath(p) {
return str(p).replace(/[\\/]+/g, '/').replace(/\/+$/, '');
}
function isSubPath(rootPath, target) {
var r = normalizePath(rootPath).toLowerCase();
var t = normalizePath(target).toLowerCase();
return !!r && (t === r || t.indexOf(r + '/') === 0);
}
function splitExcludes(value) {
var parts = Array.isArray(value) ? value : str(value).split(/[,;\n]/);
var out = [];
parts.forEach(function (x) {
x = str(x).trim();
if (x && out.indexOf(x) < 0) out.push(x);
});
return out.length ? out : DEFAULT_EXCLUDES.slice();
}
function quoteCmdArg(value) {
var s = str(value);
if (!/[ \t"&|<>^]/.test(s)) return s;
return '"' + s.replace(/"/g, '""') + '"';
}
function fuzzyMatch(query, text) {
var q = str(query).toLowerCase();
var t = str(text).toLowerCase();
if (!q) return { score: 0, positions: [] };
var qi = 0, score = 0, positions = [], last = -2;
for (var i = 0; i < t.length && qi < q.length; i++) {
if (t.charAt(i) !== q.charAt(qi)) continue;
positions.push(i);
score += (i === last + 1 ? 8 : 1);
if (i === 0 || /[\\/_.\- ]/.test(t.charAt(i - 1))) score += 5;
last = i;
qi++;
}
if (qi < q.length) return null;
score -= t.length * 0.01;
return { score: score, positions: positions };
}
function escapeRegExp(value) {
return str(value).replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
}
function scorePathMatch(query, rel, name) {
var match = fuzzyMatch(query, rel);
if (!match) return null;
var q = str(query).toLowerCase();
var base = str(name || basename(rel)).toLowerCase();
var stem = base.replace(/\.[^.]+$/, '');
var score = match.score;
if (stem === q) score += 160;
else if (base === q) score += 120;
else if (stem.indexOf(q) === 0) score += 80;
else if (base.indexOf(q) === 0) score += 60;
else if (base.indexOf(q) >= 0) score += 25;
if (rel.toLowerCase().indexOf('/' + q) >= 0) score += 12;
return { score: score, positions: match.positions };
}
/**
* Fuzzy-filters workspace files. Returns scored entries ordered best-first.
* Accepts strings or objects shaped like { path, rel, name }.
* @param {string} query - User query.
* @param {Array<string|object>} fileList - Candidate files.
* @param {number} [limit=200] - Maximum results.
* @returns {Array<object>} { path, rel, name, score, positions, item }
*/
function fuzzyMatchFiles(query, fileList, limit) {
var q = str(query).trim();
var list = Array.isArray(fileList) ? fileList : [];
var out = [];
for (var i = 0; i < list.length; i++) {
var raw = list[i];
var rel, full, name, item = null;
if (typeof raw === 'string') {
rel = normalizePath(raw);
full = raw;
name = basename(rel);
} else if (raw && typeof raw === 'object') {
rel = normalizePath(raw.rel || raw.path || raw.name || '');
full = raw.path || raw.rel || rel;
name = str(raw.name || basename(rel));
item = raw;
} else {
continue;
}
if (!rel) continue;
var match = q ? scorePathMatch(q, rel, name) : { score: 0, positions: [] };
if (!match) continue;
out.push({ path: full, rel: rel, name: name, score: match.score, positions: match.positions, item: item });
}
out.sort(function (a, b) {
return (b.score - a.score) || (a.rel.length - b.rel.length) ||
a.rel.localeCompare(b.rel, undefined, { sensitivity: 'base' });
});
var max = limit === undefined ? 200 : clamp(limit, 1, 5000);
return out.slice(0, max);
}
/**
* Fuzzy-filters commands by their label. Original properties are preserved.
* @param {string} query - User query.
* @param {Array<string|object>} commandList - Commands with a label/title.
* @param {number} [limit=200] - Maximum results.
* @returns {Array<object>} Commands extended with score and positions.
*/
function fuzzyMatchCommands(query, commandList, limit) {
var q = str(query).trim();
var list = Array.isArray(commandList) ? commandList : [];
var out = [];
for (var i = 0; i < list.length; i++) {
var raw = list[i];
var label = typeof raw === 'string' ? raw : str(raw && (raw.label || raw.title || raw.id));
if (!label) continue;
var match = q ? fuzzyMatch(q, label) : { score: 0, positions: [] };
if (!match) continue;
var copy = typeof raw === 'string' ? { label: raw } : {};
if (raw && typeof raw === 'object') {
for (var key in raw) if (Object.prototype.hasOwnProperty.call(raw, key)) copy[key] = raw[key];
}
copy.score = match.score;
copy.positions = match.positions;
out.push(copy);
}
out.sort(function (a, b) {
return (b.score - a.score) || a.label.localeCompare(b.label, undefined, { sensitivity: 'base' });
});
var max = limit === undefined ? 200 : clamp(limit, 1, 5000);
return out.slice(0, max);
}
function parseGitStatus(text) {
var parts = str(text).split('\0');
var changes = [];
for (var i = 0; i < parts.length; i++) {
var entry = parts[i];
if (!entry || entry.slice(0, 3) === '## ') continue;
if (entry.length < 4) continue;
var x = entry.charAt(0), y = entry.charAt(1);
var file = entry.slice(3);
var origPath = null;
if (x === 'R' || x === 'C' || y === 'R' || y === 'C') origPath = parts[++i] || null;
if (!file) continue;
var untracked = x === '?' && y === '?';
changes.push({
x: x, y: y, path: file, origPath: origPath, untracked: untracked,
staged: !untracked && x !== ' ' && x !== '?',
unstaged: !untracked && y !== ' ' && y !== '?'
});
}
return changes;
}
function parseGitBranchHeader(raw) {
var s = str(raw).trim();
if (!s) return '';
if (s.indexOf('No commits yet on ') === 0) return s.slice('No commits yet on '.length).trim();
if (s.indexOf('Initial commit on ') === 0) return s.slice('Initial commit on '.length).trim();
var dots = s.indexOf('...');
if (dots >= 0) s = s.slice(0, dots);
var bracket = s.indexOf(' [');
if (bracket >= 0) s = s.slice(0, bracket);
s = s.trim();
if (s === 'HEAD (no branch)' || s === 'HEAD (detached)') return 'HEAD';
return s;
}
function unquoteGitPath(raw) {
var p = str(raw).trim();
if (p.length >= 2 && p.charAt(0) === '"' && p.charAt(p.length - 1) === '"') {
p = p.slice(1, -1);
p = p.replace(/\\"/g, '"').replace(/\\\\/g, '\\').replace(/\\t/g, '\t').replace(/\\n/g, '\n');
}
return normalizePath(p);
}
/**
* Parses `git status --porcelain=v1 -b` output.
* @param {string} stdout - Raw porcelain output.
* @returns {{branch: string, files: Record<string, 'M'|'A'|'D'|'U'|'R'>}}
*/
function parseGitStatusPorcelain(stdout) {
var out = { branch: '', files: {} };
var lines = str(stdout).split(/\r?\n/);
for (var i = 0; i < lines.length; i++) {
var line = lines[i];
if (!line) continue;
if (line.slice(0, 3) === '## ') {
out.branch = parseGitBranchHeader(line.slice(3));
continue;
}
if (line.charAt(0) === '#' || line.length < 4) continue;
var x = line.charAt(0), y = line.charAt(1);
var rest = line.slice(3);
var code = 'M';
if (x === '?' && y === '?') code = 'U';
else if (x === 'R' || y === 'R' || x === 'C' || y === 'C') code = 'R';
else if (x === 'D' || y === 'D') code = 'D';
else if (x === 'A' || y === 'A') code = 'A';
else if (x === 'U' || y === 'U') code = 'U';
else if (x === 'M' || y === 'M') code = 'M';
else continue;
var arrow = rest.indexOf(' -> ');
var path = unquoteGitPath(arrow >= 0 ? rest.slice(arrow + 4) : rest);
if (!path) continue;
out.files[path] = code;
}
return out;
}
/**
* Parses `git log -n N --pretty=format:%H%x00%an%x00%ae%x00%aI%x00%s` output.
* Fields are tab-separated: hash, author, email, iso-date, subject.
* @param {string} stdout - Raw log output.
* @returns {Array<{hash:string, shortHash:string, author:string, email:string, date:string, subject:string}>}
*/
function parseGitLog(stdout) {
var lines = str(stdout).split(/\r?\n/);
var commits = [];
for (var i = 0; i < lines.length; i++) {
var line = lines[i];
if (!line) continue;
var f = line.split('\t');
if (f.length < 5) continue;
var hash = f[0], author = f[1], email = f[2], date = f[3];
var subject = f.slice(4).join('\t'); // subject may contain tabs escaped or remaining
commits.push({ hash: hash, shortHash: hash.slice(0, 7), author: author, email: email, date: date, subject: subject });
}
return commits;
}
/**
* Parses `git blame -p -z` output into per-line blame records.
* Each record: { hash, author, authorMail, time, line, origLine, text }.
* Header line format: `<sha> <orig-line> <final-line> [<num-lines>]`.
* @param {string} stdout - Raw porcelain blame output.
* @returns {Array<{hash:string, author:string, authorMail:string, time:number, line:number, origLine:number, text:string}>}
*/
function parseGitBlame(stdout) {
var lines = str(stdout).split(/\r?\n/);
var records = [];
var cur = null;
var lastHash = null;
for (var i = 0; i < lines.length; i++) {
var ln = lines[i];
if (ln === '' || ln === '\0') { cur = null; continue; }
var hdr = ln.match(/^([0-9a-f]{40}) (\d+) (\d+)(?: (\d+))?$/);
if (hdr) {
cur = {
hash: hdr[1],
author: '',
authorMail: '',
time: 0,
line: Number(hdr[3]) || 0,
origLine: Number(hdr[2]) || 0,
text: ''
};
lastHash = hdr[1];
continue;
}
if (!cur) continue;
if (ln.indexOf('author ') === 0) cur.author = ln.slice(7);
else if (ln.indexOf('author-mail ') === 0) cur.authorMail = ln.slice(12);
else if (ln.indexOf('author-time ') === 0) cur.time = Number(ln.slice(12)) || 0;
else if (ln.charAt(0) === '\t') {
cur.text = ln.slice(1);
records.push(cur);
cur = null;
}
}
return records;
}
/**
* Parses `git diff -U0 --no-color HEAD -- <file>` output into per-line gutter marks.
* Within a hunk, paired delete/add runs become 'mod'; unpaired adds 'add';
* leftover deletions collapse into a single 'del' marker with a count.
* @param {string} patch - Raw unified diff text.
* @returns {Array<{line:number, type:'add'|'mod'|'del', count?:number}>}
*/
function parseDiffHunks(patch) {
var marks = [];
var lines = str(patch).split(/\r?\n/);
var newLine = 0;
var pendingDels = 0;
var inHunk = false;
for (var i = 0; i < lines.length; i++) {
var raw = lines[i];
if (raw.charAt(0) === '@') {
var m = raw.match(/^@@ -\d+(?:,\d+)? \+(\d+)(?:,(\d+))? @@/);
if (m) {
if (pendingDels > 0 && newLine > 0) marks.push({ line: newLine, type: 'del', count: pendingDels });
pendingDels = 0;
newLine = Number(m[1]) || 0;
inHunk = true;
}
continue;
}
if (!inHunk) continue;
var c = raw.charAt(0);
if (c === '+') {
var type = pendingDels > 0 ? 'mod' : 'add';
if (pendingDels > 0) pendingDels--;
marks.push({ line: newLine, type: type });
newLine++;
} else if (c === '-') {
pendingDels++;
} else if (c === ' ' || raw === '') {
if (pendingDels > 0) { marks.push({ line: newLine, type: 'del', count: pendingDels }); pendingDels = 0; }
newLine++;
}
}
if (pendingDels > 0 && newLine > 0) marks.push({ line: newLine, type: 'del', count: pendingDels });
return marks;
}
function isWordChar(ch) { return !!ch && /[A-Za-z0-9_]/.test(ch); }
function boundaryMatch(line, index, length) {
var before = index > 0 ? line.charAt(index - 1) : '';
var after = index + length < line.length ? line.charAt(index + length) : '';
return !isWordChar(before) && !isWordChar(after);
}
function validateEntryName(name) {
var n = str(name).trim();
if (!n) return { ok: false, error: 'Name cannot be empty.' };
if (n === '.' || n === '..') return { ok: false, error: 'That name is not allowed.' };
if (/[\\/:*?"<>|\u0000]/.test(n)) return { ok: false, error: 'A name cannot contain \\ / : * ? " < > |' };
if (/[. ]$/.test(n)) return { ok: false, error: 'A name cannot end with a dot or space.' };
if (n.length > 255) return { ok: false, error: 'That name is too long.' };
return { ok: true, value: n };
}
function validateBranchName(name) {
var n = str(name).trim();
if (!n) return { ok: false, error: 'Branch name is required.' };
if (n === '@' || /\s/.test(n)) return { ok: false, error: 'Branch names cannot contain spaces.' };
if (/[~^:?*\[\\]/.test(n)) return { ok: false, error: 'A branch name cannot contain ~ ^ : ? * [ \\' };
if (n.indexOf('..') >= 0 || n.indexOf('@{') >= 0 || n.indexOf('//') >= 0) {
return { ok: false, error: 'That branch name is not valid.' };
}
if (n.charAt(0) === '-' || n.charAt(0) === '/' || n.charAt(n.length - 1) === '/') {
return { ok: false, error: 'A branch name cannot start with - or / and cannot end with /.' };
}
if (/[.]$/.test(n) || /[.]lock$/.test(n)) return { ok: false, error: 'A branch name cannot end with . or .lock.' };
if (n.length > 200) return { ok: false, error: 'That branch name is too long.' };
return { ok: true, value: n };
}
/**
* Detects file encoding from a raw byte array or string.
* Works in both browser and Node contexts.
* @param {Array<number>|string} bytes - Raw bytes as an array of numbers, or a raw string sample.
* @param {number} [sampleSize=4096] - Number of bytes to sample for detection.
* @returns {object} { encoding, bomDetected, hasNul, isBinary }
*/
function detectFileEncoding(bytes, sampleSize) {
var sample = [];
if (typeof bytes === 'string') {
for (var i = 0; i < bytes.length && i < sampleSize; i++) sample.push(bytes.charCodeAt(i) & 0xFF);
} else if (Array.isArray(bytes)) {
sample = bytes.slice(0, sampleSize || 4096);
} else if (bytes && typeof bytes.length === 'number') {
for (var j = 0; j < bytes.length && j < (sampleSize || 4096); j++) sample.push(bytes[j]);
}
var encoding = 'utf-8';
var bomDetected = false;
var hasNul = false;
if (sample.length >= 3 && sample[0] === 0xEF && sample[1] === 0xBB && sample[2] === 0xBF) { encoding = 'utf-8'; bomDetected = true; }
else if (sample.length >= 2 && sample[0] === 0xFF && sample[1] === 0xFE) { encoding = 'utf-16-le'; bomDetected = true; }
else if (sample.length >= 2 && sample[0] === 0xFE && sample[1] === 0xFF) { encoding = 'utf-16-be'; bomDetected = true; }
else if (sample.length >= 4 && sample[0] === 0xFF && sample[1] === 0xFE && sample[2] === 0x00 && sample[3] === 0x00) { encoding = 'utf-32-le'; bomDetected = true; }
else if (sample.length >= 4 && sample[0] === 0x00 && sample[1] === 0x00 && sample[2] === 0xFE && sample[3] === 0xFF) { encoding = 'utf-32-be'; bomDetected = true; }
for (var k = 0; k < sample.length; k++) { if (sample[k] === 0) { hasNul = true; break; } }
return { encoding: encoding, bomDetected: bomDetected, hasNul: hasNul, isBinary: hasNul && !bomDetected };
}
/**
* Parses compiler/linter diagnostics from text output.
* Handles gcc-style `path:line:col: message`, node-style `path:line` followed by
* a caret block and `Error: message`, and python `File "path", line N` blocks.
* @param {string} text - Raw stderr/stdout text.
* @returns {Array<{file:string,line:number,column:number,severity:string,message:string}>}
*/
function parseDiagnostics(text) {
var lines = str(text).split(/\r?\n/);
var out = [];
var pending = null;
function push(file, line, column, message) {
file = str(file).trim();
if (!file || !/[\\/.]/.test(file)) return;
out.push({
file: file, line: clamp(line, 1, 1000000), column: clamp(column, 1, 100000),
severity: /warning/i.test(message) ? 'warning' : 'error',
message: str(message).trim().slice(0, 600)
});
}
for (var i = 0; i < lines.length; i++) {
var line = lines[i];
if (!line.trim()) continue;
// python: File "C:\path\file.py", line 5
var py = line.match(/^File\s+"(.+)",\s+line\s+(\d+)/);
if (py) { pending = { file: py[1], line: parseInt(py[2], 10) }; continue; }
if (pending) {
if (/^[~^ ]+$/.test(line)) continue;
var pym = line.match(/^(\w*Error\S*|SyntaxError|IndentationError|TabError|.*?Error:\s.*)$/);
if (pym) { push(pending.file, pending.line, 1, pym[1]); pending = null; }
continue;
}
// gcc: path:line:col: message (absolute paths may contain drive colons)
var gcc = line.match(/^(.+?):(\d+):(\d+):\s*(.*)$/);
if (gcc) { push(gcc[1], gcc[2], gcc[3], gcc[4]); continue; }
// gcc without column: path:line: message
var gcc2 = line.match(/^(.+?):(\d+):\s*(.*)$/);
if (gcc2) { push(gcc2[1], gcc2[2], 1, gcc2[3]); continue; }
// node: path:line followed by a caret line and Error: message
var node = line.match(/^(.+?):(\d+)\s*$/);
if (node) {
var j = i + 1;
while (j < lines.length && /^[\^~\s]+$/.test(lines[j])) j++;
var msg = '';
if (j < lines.length) {
var errLine = lines[j].match(/^([\w$.]+Error(?:\s+.*)?)$/);
msg = errLine ? errLine[1] : lines[j];
}
push(node[1], node[2], 1, msg || 'Syntax error');
if (j < lines.length) i = j;
continue;
}
// fallback: bare Error: line (attach to nearest known file)
var bare = line.match(/^([\w$.]+Error):\s*(.*)$/);
if (bare && out.length) {
var last = out[out.length - 1];
if (last && last.message.indexOf(bare[1]) !== 0) last.message += '; ' + line.trim();
}
}
// Deduplicate and sort by file/line/column.
var seen = {};
var clean = [];
for (var k = 0; k < out.length; k++) {
var d = out[k];
var key = d.file + ':' + d.line + ':' + d.column + ':' + d.message;
if (seen[key]) continue;
seen[key] = 1;
clean.push(d);
}
clean.sort(function (a, b) {
var af = normalizePath(a.file).toLowerCase(), bf = normalizePath(b.file).toLowerCase();
if (af !== bf) return af < bf ? -1 : 1;
return (a.line - b.line) || (a.column - b.column);
});
return clean;
}
/**
* Normalizes line endings in file content.
* @param {string} content - File content to normalize.
* @param {string} [to='lf'] - Target line ending ('lf', 'crlf', 'native'). Defaults to 'lf'.
* @returns {string} Content with normalized line endings.
*/
function normalizeLineEndings(content, to) {
var s = str(content);
s = s.replace(/\r\n/g, '\n').replace(/\r/g, '\n');
var target = String(to || 'lf').toLowerCase();
if (target === 'crlf') return s.replace(/\n/g, '\r\n');
if (target === 'cr') return s.replace(/\n/g, '\r');
return s;
}
/* ---------------- document symbols ---------------- */
/**
* Extracts lightweight symbols from source text.
* Supports .js/.ts, .py, .md, .html and .css.
* @param {string} content - Document text.
* @param {string} fileExtension - Extension with or without a leading dot.
* @returns {Array<{name:string, kind:string, line:number, column:number, detail:string}>}
*/
function extractDocumentSymbols(content, fileExtension) {
var ext = str(fileExtension).toLowerCase().replace(/^\./, '');
var aliases = {
jsx: 'js', mjs: 'js', cjs: 'js', tsx: 'ts', pyw: 'py',
markdown: 'md', htm: 'html', scss: 'css', less: 'css'
};
ext = aliases[ext] || ext;
var lines = str(content).split(/\r?\n/);
var out = [];
var seen = {};
function add(name, kind, index, column, detail) {
name = str(name).replace(/\s+/g, ' ').trim();
if (!name || name.length > 240) return;
var line = index + 1;
var key = kind + ':' + line + ':' + name;
if (seen[key]) return;
seen[key] = 1;
out.push({ name: name, kind: kind, line: line, column: column || 1, detail: detail || kind });
}
if (ext === 'js' || ext === 'ts') {
var classRe = /^\s*(?:export\s+)?(?:default\s+)?(?:abstract\s+)?class\s+([A-Za-z_$][\w$]*)/;
var funcRe = /^\s*(?:export\s+)?(?:default\s+)?(?:async\s+)?function\s*\*?\s*([A-Za-z_$][\w$]*)/;
var varFnRe = /^\s*(?:export\s+)?(?:const|let|var)\s+([A-Za-z_$][\w$]*)\s*=\s*(?:async\s*)?(?:function\b|\([^)]*\)\s*=>|[A-Za-z_$][\w$]*\s*=>)/;
var methodRe = /^\s{2,}(?:static\s+|async\s+|get\s+|set\s+|\*\s*)*(#?[A-Za-z_$][\w$]*)\s*\([^;{}]*\)\s*\{/;
var reserved = { if: 1, for: 1, while: 1, switch: 1, catch: 1, with: 1, function: 1, return: 1, do: 1, try: 1, else: 1 };
for (var ji = 0; ji < lines.length; ji++) {
var jline = lines[ji], jm;
if ((jm = jline.match(classRe))) { add(jm[1], 'class', ji, jline.indexOf(jm[1]) + 1, 'class'); continue; }
if ((jm = jline.match(funcRe))) { add(jm[1], 'function', ji, jline.indexOf(jm[1]) + 1, 'function'); continue; }
if ((jm = jline.match(varFnRe))) { add(jm[1], 'function', ji, jline.indexOf(jm[1]) + 1, 'function'); continue; }
if ((jm = jline.match(methodRe)) && !Object.prototype.hasOwnProperty.call(reserved, jm[1])) {
add(jm[1], 'method', ji, jline.indexOf(jm[1]) + 1, 'method');
}
}
} else if (ext === 'py') {
for (var pi = 0; pi < lines.length; pi++) {
var pline = lines[pi], pm;
if ((pm = pline.match(/^(\s*)(?:async\s+)?class\s+([A-Za-z_]\w*)/))) {
add(pm[2], 'class', pi, pline.indexOf(pm[2]) + 1, 'class');
} else if ((pm = pline.match(/^(\s*)(?:async\s+)?def\s+([A-Za-z_]\w*)/))) {
add(pm[2], pm[1].length ? 'method' : 'function', pi, pline.indexOf(pm[2]) + 1, pm[1].length ? 'method' : 'function');
}
}
} else if (ext === 'md') {
for (var mi = 0; mi < lines.length; mi++) {
var mline = lines[mi];
var mm = mline.match(/^(#{1,6})\s+(.+?)\s*#*\s*$/);
if (!mm) continue;
var title = mm[2].replace(/[*_`~]/g, '').replace(/\[([^\]]+)\]\([^)]*\)/g, '$1').trim();
add(title, 'heading', mi, mline.indexOf(mm[2]) + 1, 'h' + mm[1].length);
}
} else if (ext === 'html') {
for (var hi = 0; hi < lines.length; hi++) {
var hline = lines[hi];
var heading = hline.match(/<h([1-6])\b[^>]*>(.*?)<\/h\1>/i);
if (heading) {
var htext = heading[2].replace(/<[^>]*>/g, '').replace(/&[a-z#0-9]+;/gi, ' ').trim();
add(htext, 'heading', hi, hline.indexOf(heading[2]) + 1, 'h' + heading[1]);
}
var idRe = /<([a-zA-Z][\w:-]*)\b[^>]*\bid=(?:"([^"]+)"|'([^']+)')/g;
var idMatch;
while ((idMatch = idRe.exec(hline))) add(idMatch[2] || idMatch[3], 'id', hi, hline.indexOf(idMatch[2] || idMatch[3]) + 1, idMatch[1]);
}
} else if (ext === 'css') {
for (var ci = 0; ci < lines.length; ci++) {
var cline = lines[ci];
var keyframes = cline.match(/^\s*@(?:-webkit-)?keyframes\s+([\w-]+)/);
if (keyframes) { add(keyframes[1], 'keyframes', ci, cline.indexOf(keyframes[1]) + 1, 'keyframes'); continue; }
var selector = cline.match(/^\s*([^{}@/][^{}]*?)\s*\{\s*$/);
if (selector) {
var sel = selector[1].replace(/\s+/g, ' ').trim();
if (sel && sel.length < 180) add(sel, 'selector', ci, cline.indexOf(selector[1]) + 1, 'selector');
}
}
}
out.sort(function (a, b) { return (a.line - b.line) || (a.column - b.column); });
return out.slice(0, 2000);
}
/* ---------------- text transforms ---------------- */
function splitLineList(content) {
var source = str(content);
var trailing = /(?:\r\n|\n|\r)$/.test(source);
var lines = source.split(/\r\n|\n|\r/);
if (trailing && lines.length) lines.pop();
return { lines: lines, trailing: trailing };
}
function joinLineList(lines, trailing) {
return lines.join('\n') + (trailing && lines.length ? '\n' : '');
}
/**
* Pretty-prints JSON without throwing.
* @returns {{ok: boolean, text?: string, error?: string}}
*/
function formatJsonText(content, indent) {
var source = str(content).replace(/^\uFEFF/, '');
try {
var value = JSON.parse(source);
var spaces = indent === undefined ? 2 : clamp(indent, 0, 8);
return { ok: true, text: JSON.stringify(value, null, spaces) };
} catch (err) {
return { ok: false, error: (err && err.message) || 'Invalid JSON.' };
}
}
function sortLines(content, options) {
options = options || {};
var parts = splitLineList(content);
var caseSensitive = !!options.caseSensitive;
parts.lines.sort(function (a, b) {
var x = caseSensitive ? a : a.toLowerCase();
var y = caseSensitive ? b : b.toLowerCase();
if (x < y) return -1;
if (x > y) return 1;
return a < b ? -1 : a > b ? 1 : 0;
});
if (options.descending) parts.lines.reverse();
return joinLineList(parts.lines, parts.trailing);
}
function dedupeLines(content, options) {
options = options || {};
var parts = splitLineList(content);
var caseSensitive = options.caseSensitive !== false;
var seen = {};
var out = [];
for (var i = 0; i < parts.lines.length; i++) {
var line = parts.lines[i];
var key = caseSensitive ? line : line.toLowerCase();
if (Object.prototype.hasOwnProperty.call(seen, key)) continue;
seen[key] = 1;
out.push(line);
}
return joinLineList(out, parts.trailing);
}
function trimTrailingWhitespace(content) {
return str(content).replace(/[ \t]+(?=\r\n|\n|\r|$)/g, '');
}
/**
* Appends terminal-style output, honouring carriage returns.
* A `\r` moves the cursor to the start of the current line so progress bars
* overwrite themselves instead of appending a new line for every update.
* @param {string} existing - Text already displayed.
* @param {string} chunk - Newly received text.
* @returns {string} The combined text.
*/
function applyCarriageReturns(existing, chunk) {
let out = str(existing);
const incoming = str(chunk);
if (!incoming) return out;
let cursor = out.length;
let i = 0;
while (i < incoming.length) {
const ch = incoming[i];
if (ch === '\r') {
if (incoming[i + 1] === '\n') {
out = out.slice(0, cursor) + '\n' + out.slice(cursor);
cursor += 1;
i += 2;
continue;
}
const nl = out.lastIndexOf('\n', cursor - 1);
cursor = nl + 1;
i += 1;
continue;
}
if (ch === '\n') {
out = out.slice(0, cursor) + '\n' + out.slice(cursor);
cursor += 1;
i += 1;
continue;
}
let j = i;
while (j < incoming.length && incoming[j] !== '\r' && incoming[j] !== '\n') j += 1;
const run = incoming.slice(i, j);
if (cursor === out.length) out += run;
else out = out.slice(0, cursor) + run + out.slice(cursor + run.length);
cursor += run.length;
i = j;
}
return out;
}
/**
* Parses Git diff output into per-hunk records (file header + unified diff hunk).
* Each hunk keeps its content lines and a ready-to-apply patch fragment.
* @param {string} diffText - Raw git diff output (stdout).
* @returns {Array<{context:string, added:string, removed:string, staged:boolean, header:string, raw:string, fileHeader:string[], path:string, oldStart:number, oldLines:number, newStart:number, newLines:number, addedCount:number, removedCount:number}>}
*/
function parseGitHunks(diffText) {
var lines = str(diffText).split(/\r?\n/);
var hunks = [];
var current = null;
var inHunk = false;
var fileHeader = [];
var filePath = '';
for (var i = 0; i < lines.length; i++) {
var ln = lines[i];
if (/^diff --git /.test(ln)) {
if (current) { hunks.push(current); current = null; }
inHunk = false;
fileHeader = [ln];
filePath = (ln.match(/^diff --git a\/(.+?) b\/(.+)$/) || [])[2] || '';
continue;
}
if (/^(?:index|---|\+\+\+|new file mode|deleted file mode|old mode|new mode|similarity index|dissimilarity index|rename from|rename to|Binary files|GIT binary patch) /.test(ln)) {
if (inHunk) { if (current) { hunks.push(current); current = null; } inHunk = false; }
fileHeader.push(ln);
continue;
}
if (/^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@/.test(ln)) {
if (current) hunks.push(current);
var m = ln.match(/^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@/);
current = {
context: '',
added: '',
removed: '',
staged: false,
header: ln,
raw: ln + '\n',
fileHeader: fileHeader.slice(),
path: filePath,
oldStart: m ? Number(m[1]) : 0,
oldLines: m && m[2] !== undefined ? Number(m[2]) : 1,
newStart: m ? Number(m[3]) : 0,
newLines: m && m[4] !== undefined ? Number(m[4]) : 1,
addedCount: 0,
removedCount: 0
};
inHunk = true;
continue;
}
if (!inHunk) continue;
if (ln === '\\ No newline at end of file') { current.raw += ln + '\n'; continue; }
if (ln.startsWith(' ')) { current.context += ln.slice(1) + '\n'; current.raw += ln + '\n'; continue; }
if (ln.startsWith('+')) { current.added += ln.slice(1) + '\n'; current.addedCount += 1; current.raw += ln + '\n'; continue; }
if (ln.startsWith('-')) { current.removed += ln.slice(1) + '\n'; current.removedCount += 1; current.raw += ln + '\n'; continue; }
}
if (current) hunks.push(current);
return hunks;
}
/**
* Builds a single-hunk git patch fragment (file header + hunk) from a parsed hunk.
* @param {object} hunk - Hunk record from parseGitHunks.
* @returns {string} Patch text suitable for `git apply`.
*/
function buildHunkPatch(hunk) {
var h = hunk || { fileHeader: [], raw: '' };
var header = Array.isArray(h.fileHeader) ? h.fileHeader.join('\n') : '';
var body = h.raw || '';
return header ? header + '\n' + body : body;
}
/**
* Applies a named text transform.
* @param {string} content - Document text.
* @param {string} id - Transform id (format-json, sort-lines, dedupe-lines, trim-trailing-whitespace).
* @param {object} [options] - Transform options.
* @returns {{ok: boolean, text?: string, changed?: boolean, error?: string}}
*/
function transformText(content, id, options) {
options = options || {};
var source = str(content);
var text;
if (id === 'format-json' || id === 'json') {
var parsed = formatJsonText(source, options.indent);
if (!parsed.ok) return parsed;
text = parsed.text;
} else if (id === 'sort-lines' || id === 'sort-lines-ascending') {
text = sortLines(source, options);
} else if (id === 'sort-lines-descending') {
text = sortLines(source, { caseSensitive: options.caseSensitive, descending: true });
} else if (id === 'dedupe-lines' || id === 'remove-duplicate-lines') {
text = dedupeLines(source, options);
} else if (id === 'trim-trailing-whitespace') {
text = trimTrailingWhitespace(source);
} else if (id === 'uppercase') {
text = source.toUpperCase();
} else if (id === 'lowercase') {
text = source.toLowerCase();
} else if (id === 'title-case') {
text = source.replace(/\\S+/g, function (w) { return w.charAt(0).toUpperCase() + w.slice(1).toLowerCase(); });
} else if (id === 'camel-case') {
text = source.trim().replace(/[^A-Za-z0-9]+(.)?/g, function (_, c) { return c ? c.toUpperCase() : ''; });
} else if (id === 'snake-case') {
text = source.trim().replace(/([a-z])([A-Z])/g, '$1_$2').replace(/[^A-Za-z0-9]+/g, '_').toLowerCase();
} else if (id === 'kebab-case') {
text = source.trim().replace(/([a-z])([A-Z])/g, '$1-$2').replace(/[^A-Za-z0-9]+/g, '-').toLowerCase();
} else {
return { ok: false, error: 'Unknown text transform.' };
}
return { ok: true, text: text, changed: text !== source };
}
/**
* Replaces literal text with optional case sensitivity and whole-word matching.
* @returns {{text: string, count: number}}
*/
function replaceInText(content, query, replacement, options) {
options = options || {};
var source = str(content);
var needle = str(query);
if (!needle) return { text: source, count: 0 };
var pattern;
if (options.useRegex) {
pattern = needle;
} else {
pattern = escapeRegExp(needle);
if (options.wholeWord) pattern = '(?<![A-Za-z0-9_])' + pattern + '(?![A-Za-z0-9_])';
}
var flags = options.caseSensitive ? 'g' : 'gi';
var re;
try { re = new RegExp(pattern, flags); }
catch (err) { return { text: source, count: 0, error: 'Invalid pattern: ' + err.message }; }
var count = 0;
var text = source.replace(re, function () { count++; return str(replacement); });
return { text: text, count: count };
}
/* ---------------- snippets ---------------- */
var SNIPPETS = {
javascript: [
{ name: 'function', body: 'function ${1:name}(${2:params}) {\n\t$0\n}' },
{ name: 'arrow function', body: 'const ${1:name} = (${2:params}) => {\n\t$0\n};' },
{ name: 'async function', body: 'async function ${1:name}(${2:params}) {\n\t$0\n}' },
{ name: 'for loop', body: 'for (let ${1:i} = 0; ${1:i} < ${2:array}.length; ${1:i}++) {\n\t$0\n}' },
{ name: 'for-of loop', body: 'for (const ${1:item} of ${2:iterable}) {\n\t$0\n}' },
{ name: 'if statement', body: 'if (${1:condition}) {\n\t$0\n}' },
{ name: 'try/catch', body: 'try {\n\t$0\n} catch (${1:err}) {\n\t${2:console.error(err);}\n}' },
{ name: 'class', body: 'class ${1:Name} {\n\tconstructor(${2:params}) {\n\t\t$0\n\t}\n}' },
{ name: 'console.log', body: 'console.log($0);' },
{ name: 'setTimeout', body: 'setTimeout(() => {\n\t$0\n}, ${1:delay});' }
],
html: [
{ name: 'html5 boilerplate', body: '<!DOCTYPE html>\n<html lang="en">\n<head>\n\t<meta charset="UTF-8">\n\t<meta name="viewport" content="width=device-width, initial-scale=1.0">\n\t<title>${1:Document}</title>\n</head>\n<body>\n\t$0\n</body>\n</html>' },
{ name: 'div', body: '<div${1: class="${2:name}"}>\n\t$0\n</div>' },
{ name: 'table', body: '<table>\n\t<thead>\n\t\t<tr><th>${1:Header}</th></tr>\n\t</thead>\n\t<tbody>\n\t\t<tr><td>$0</td></tr>\n\t</tbody>\n</table>' },
{ name: 'form', body: '<form${1: action="${2:/submit}" method="${3:post}"}>\n\t$0\n</form>' },
{ name: 'link stylesheet', body: '<link rel="stylesheet" href="${1:style.css}">' },
{ name: 'script tag', body: '<script src="${1:app.js}"></script>' }
],
css: [
{ name: 'rule', body: '${1:selector} {\n\t${2:property}: ${3:value};\n\t$0\n}' },
{ name: 'flexbox', body: 'display: flex;\nalign-items: ${1:center};\njustify-content: ${2:center};\ngap: ${3:8px};' },
{ name: 'media query', body: '@media (max-width: ${1:768px}) {\n\t$0\n}' }
],
json: [
{ name: 'object', body: '{\n\t"${1:key}": "${2:value}"$0\n}' },
{ name: 'array of objects', body: '[\n\t{\n\t\t"${1:key}": "${2:value}"\n\t}$0\n]' }
],
python: [
{ name: 'function', body: 'def ${1:name}(${2:params}):\n $0' },
{ name: 'class', body: 'class ${1:Name}:\n def __init__(self${2:, params}):\n $0' },
{ name: 'main guard', body: 'if __name__ == "__main__":\n $0' },
{ name: 'for loop', body: 'for ${1:item} in ${2:iterable}:\n $0' },
{ name: 'try/except', body: 'try:\n $0\nexcept ${1:Exception} as ${2:e}:\n ${3:print(e)}' }
],
markdown: [
{ name: 'section header', body: '## ${1:Title}\n\n$0' },
{ name: 'code block', body: '```${1:lang}\n$0\n```' },
{ name: 'table', body: '| ${1:Column} | ${2:Column} |\n| --- | --- |\n| $0 | |' },
{ name: 'task list', body: '- [ ] ${1:task}\n- [ ] $0' }
]
};
// Language aliases share a snippet set.
var SNIPPET_ALIASES = {
javascriptreact: 'javascript', jsx: 'javascript', mjs: 'javascript', cjs: 'javascript',
typescript: 'javascript', typescriptreact: 'javascript', tsx: 'javascript', ts: 'javascript',
html: 'html', xml: 'html', vue: 'html', svelte: 'html',
css: 'css', scss: 'css', less: 'css',
json: 'json', jsonc: 'json',
python: 'python', py: 'python',
markdown: 'markdown', md: 'markdown'
};
/**
* Built-in snippets available for a Monaco language id or file extension.
* @param {string} languageIdOrExt
* @returns {Array<{name:string, body:string}>}
*/
function snippetsFor(languageIdOrExt) {
var key = str(languageIdOrExt).toLowerCase();
if (!key) return [];
key = SNIPPET_ALIASES[key] || key;
return SNIPPETS[key] || [];
}
/* ---------------- session persistence ---------------- */
function defaultSession() {
return { version: 1, workspace: null, activeTab: null, tabs: [] };
}