@celljs/ta-workspace 0.0.0-stage → 4.6.1

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.
@@ -0,0 +1,191 @@
1
+ import { describe, expect, it } from 'bun:test';
2
+ import type { TaDirEntry } from '@celljs/ta-protocol';
3
+ import { TerminalKeys } from './keys';
4
+ import { WorkspaceUtil } from './workspace';
5
+
6
+ const dir = (path: string): TaDirEntry => ({ name: WorkspaceUtil.basename(path), path, kind: 'directory' });
7
+ const file = (path: string): TaDirEntry => ({ name: WorkspaceUtil.basename(path), path, kind: 'file' });
8
+
9
+ describe('WorkspaceUtil', () => {
10
+ it('splits paths', () => {
11
+ expect(WorkspaceUtil.basename('src/a/b.ts')).toBe('b.ts');
12
+ expect(WorkspaceUtil.basename('/Users/me/project/')).toBe('project');
13
+ expect(WorkspaceUtil.dirname('src/a/b.ts')).toBe('src/a');
14
+ expect(WorkspaceUtil.dirname('b.ts')).toBe('');
15
+ });
16
+
17
+ it('shows the tree as far as it is open and read', () => {
18
+ const children = new Map([
19
+ ['', [dir('src'), file('README.md')]],
20
+ ['src', [dir('src/lib'), file('src/a.ts')]],
21
+ ]);
22
+ let expanded = new Set<string>();
23
+ expect(WorkspaceUtil.rows(children, expanded).map(row => row.entry.path)).toEqual(['src', 'README.md']);
24
+ expanded = WorkspaceUtil.toggle(expanded, 'src');
25
+ expanded = WorkspaceUtil.toggle(expanded, 'src/lib');
26
+ const rows = WorkspaceUtil.rows(children, expanded);
27
+ expect(rows.map(row => [row.entry.path, row.depth, row.expanded, row.loading])).toEqual([
28
+ ['src', 0, true, false],
29
+ ['src/lib', 1, true, true],
30
+ ['src/a.ts', 1, false, false],
31
+ ['README.md', 0, false, false],
32
+ ]);
33
+ expect([...WorkspaceUtil.toggle(expanded, 'src')]).toEqual([]);
34
+ expect([...WorkspaceUtil.reveal(new Set(), 'a/b/c.ts')]).toEqual(['a', 'a/b']);
35
+ });
36
+
37
+ it('groups git changes', () => {
38
+ const rows = WorkspaceUtil.gitRows({
39
+ repository: true,
40
+ files: [
41
+ { path: 'z.ts', unstaged: '?' },
42
+ { path: 'b.ts', staged: 'M', unstaged: 'M' },
43
+ { path: 'a.ts', staged: 'A' },
44
+ { path: 'c.ts', staged: 'U', unstaged: 'U' },
45
+ ],
46
+ });
47
+ expect(rows.map(row => `${row.group}:${row.letter}:${row.file.path}`)).toEqual([
48
+ 'merge:!:c.ts',
49
+ 'staged:A:a.ts',
50
+ 'staged:M:b.ts',
51
+ 'changes:M:b.ts',
52
+ 'changes:U:z.ts',
53
+ ]);
54
+ expect(WorkspaceUtil.gitColor('U')).toBe('var(--taw-git-added)');
55
+ expect(WorkspaceUtil.gitColor('D')).toBe('var(--taw-git-deleted)');
56
+ expect(WorkspaceUtil.gitColor(undefined)).toBeUndefined();
57
+ });
58
+
59
+ it('groups matches by file and marks the match', () => {
60
+ const groups = WorkspaceUtil.groupMatches([
61
+ { path: 'a', line: 1, column: 1, length: 1, preview: 'x', previewColumn: 0 },
62
+ { path: 'b', line: 2, column: 1, length: 1, preview: 'y', previewColumn: 0 },
63
+ { path: 'a', line: 3, column: 1, length: 1, preview: 'z', previewColumn: 0 },
64
+ ]);
65
+ expect(groups.map(group => [group.path, group.matches.length])).toEqual([
66
+ ['a', 2],
67
+ ['b', 1],
68
+ ]);
69
+ expect(WorkspaceUtil.highlight({ preview: 'const Needle = 1', previewColumn: 6, length: 6 })).toEqual(['const ', 'Needle', ' = 1']);
70
+ expect(WorkspaceUtil.highlight({ preview: 'a.b', previewColumn: 0, length: 3 })).toEqual(['', 'a.b', '']);
71
+ // A match far in a long line keeps a few words before it, from the start of a word.
72
+ const long = { preview: 'const first = "aaaa bbbb cccc dddd eeee ffff gggg"; needle();', previewColumn: 52, length: 6 };
73
+ const [before, found] = WorkspaceUtil.highlight(long);
74
+ expect(found).toBe('needle');
75
+ expect(before).toBe('… dddd eeee ffff gggg"; ');
76
+ expect(WorkspaceUtil.cutBefore('x'.repeat(40), 10)).toBe(`…${'x'.repeat(10)}`);
77
+ });
78
+
79
+ it('puts paths in a tree of folders, a folder holding only a folder shown with it', () => {
80
+ const tree = WorkspaceUtil.pathTree(
81
+ ['b.ts', 'packages/alipay/src/node/a.ts', 'packages/alipay/src/node/test/f.ts', 'src/z.ts', 'src/a.ts', 'packages/web/x.ts'],
82
+ path => path,
83
+ );
84
+ const show = (folder: typeof tree, depth = 0): string[] => [
85
+ ...folder.folders.flatMap(inner => [`${' '.repeat(depth)}${inner.name}/ ${inner.size}`, ...show(inner, depth + 1)]),
86
+ ...folder.items.map(item => `${' '.repeat(depth)}${WorkspaceUtil.basename(item)}`),
87
+ ];
88
+ expect(show(tree)).toEqual([
89
+ 'packages/ 3',
90
+ ' alipay/src/node/ 2',
91
+ ' test/ 1',
92
+ ' f.ts',
93
+ ' a.ts',
94
+ ' web/ 1',
95
+ ' x.ts',
96
+ 'src/ 2',
97
+ ' a.ts',
98
+ ' z.ts',
99
+ 'b.ts',
100
+ ]);
101
+ expect(tree.folders[0].folders[0].path).toBe('packages/alipay/src/node');
102
+ expect(
103
+ WorkspaceUtil.pathTree(
104
+ ['a/b.ts', 'a/c.ts'],
105
+ path => path,
106
+ () => 5,
107
+ ).size,
108
+ ).toBe(10);
109
+ });
110
+
111
+ it('checks the names typed in the explorer, as VS Code does', () => {
112
+ const siblings = ['src', 'README.md'];
113
+ expect(WorkspaceUtil.validateName('', siblings)).toMatchObject({ key: 'nameEmpty', severity: 'error' });
114
+ expect(WorkspaceUtil.validateName(' ', siblings)).toMatchObject({ key: 'nameEmpty' });
115
+ expect(WorkspaceUtil.validateName('/etc', siblings)).toMatchObject({ key: 'nameSlash' });
116
+ expect(WorkspaceUtil.validateName('a/../b', siblings)).toMatchObject({ key: 'nameInvalid' });
117
+ expect(WorkspaceUtil.validateName('readme.md', siblings)).toMatchObject({ key: 'nameExists' });
118
+ // A path makes the folders on its way, into one that is there.
119
+ expect(WorkspaceUtil.validateName('src/new.ts', siblings)).toBeUndefined();
120
+ expect(WorkspaceUtil.validateName(' a.ts', siblings)).toMatchObject({ key: 'nameWhitespace', severity: 'warning' });
121
+ expect(WorkspaceUtil.validateName('a.ts', siblings)).toBeUndefined();
122
+ expect(WorkspaceUtil.within('src/a.ts', 'src')).toBe(true);
123
+ expect(WorkspaceUtil.within('srcx/a.ts', 'src')).toBe(false);
124
+ expect(WorkspaceUtil.join('', 'a')).toBe('a');
125
+ expect(WorkspaceUtil.join('src', 'a')).toBe('src/a');
126
+ });
127
+
128
+ it('reads the address bar', () => {
129
+ expect(WorkspaceUtil.toUrl('localhost:3000/a')).toBe('http://localhost:3000/a');
130
+ expect(WorkspaceUtil.toUrl('127.0.0.1:8080')).toBe('http://127.0.0.1:8080');
131
+ expect(WorkspaceUtil.toUrl('example.com')).toBe('https://example.com');
132
+ expect(WorkspaceUtil.toUrl('https://x.dev')).toBe('https://x.dev');
133
+ expect(WorkspaceUtil.toUrl('react hooks')).toBe('https://www.bing.com/search?q=react%20hooks');
134
+ expect(WorkspaceUtil.toUrl(' ')).toBeUndefined();
135
+ });
136
+
137
+ it('writes sizes', () => {
138
+ expect(WorkspaceUtil.size(12)).toBe('12 B');
139
+ expect(WorkspaceUtil.size(1536)).toBe('1.5 KB');
140
+ expect(WorkspaceUtil.size(5 * 1024 * 1024)).toBe('5.0 MB');
141
+ });
142
+ });
143
+
144
+ describe('TerminalKeys', () => {
145
+ it('turns keys into what a terminal sends', () => {
146
+ expect(TerminalKeys.sequence({ key: 'Enter' })).toBe('\r');
147
+ expect(TerminalKeys.sequence({ key: 'ArrowUp' })).toBe('\x1b[A');
148
+ expect(TerminalKeys.sequence({ key: 'c', ctrlKey: true })).toBe('\x03');
149
+ expect(TerminalKeys.sequence({ key: 'Tab', shiftKey: true })).toBe('\x1b[Z');
150
+ expect(TerminalKeys.sequence({ key: 'a' })).toBeUndefined();
151
+ expect(TerminalKeys.sequence({ key: 'v', metaKey: true })).toBeUndefined();
152
+ expect(TerminalKeys.paste('a\nb\r\nc')).toBe('a\rb\rc');
153
+ });
154
+ });
155
+
156
+ describe('WorkspaceUtil links', () => {
157
+ it('makes the path of a link absolute', () => {
158
+ expect(WorkspaceUtil.absolute('/repo', 'src')).toBe('/repo/src');
159
+ expect(WorkspaceUtil.absolute('/repo/', '')).toBe('/repo/');
160
+ expect(WorkspaceUtil.absolute('/', 'etc')).toBe('/etc');
161
+ });
162
+
163
+ it('gives a page of the origin of Ta an origin of its own in the browser', () => {
164
+ expect(WorkspaceUtil.frameSandbox('https://x.dev/', 'http://localhost:4000')).toContain('allow-same-origin');
165
+ expect(WorkspaceUtil.frameSandbox('http://localhost:5173/', 'http://localhost:4000')).toContain('allow-same-origin');
166
+ expect(WorkspaceUtil.frameSandbox('http://localhost:4000/', 'http://localhost:4000')).not.toContain('allow-same-origin');
167
+ expect(WorkspaceUtil.frameSandbox('/api/x', 'http://localhost:4000')).not.toContain('allow-same-origin');
168
+ });
169
+ });
170
+
171
+ describe('WorkspaceUtil kept state', () => {
172
+ it('reads back the tabs kept, and leaves out what it cannot open', () => {
173
+ expect(
174
+ WorkspaceUtil.keptFiles([
175
+ { kind: 'file', cwd: '/w', path: 'a.ts', extra: 1 },
176
+ { kind: 'diff', cwd: '/w', path: 'b.ts', staged: true },
177
+ { kind: 'diff', cwd: '/w', path: 'c.ts' },
178
+ { kind: 'folder', cwd: '/w', path: 'd' },
179
+ { kind: 'file', path: 'e.ts' },
180
+ null,
181
+ ]),
182
+ ).toEqual([
183
+ { kind: 'file', cwd: '/w', path: 'a.ts' },
184
+ { kind: 'diff', cwd: '/w', path: 'b.ts', staged: true },
185
+ { kind: 'diff', cwd: '/w', path: 'c.ts', staged: false },
186
+ ]);
187
+ expect(WorkspaceUtil.keptFiles({ files: [] })).toEqual([]);
188
+ expect(WorkspaceUtil.paths(['src', 1, 'src/a'])).toEqual(['src', 'src/a']);
189
+ expect(WorkspaceUtil.paths('src')).toEqual([]);
190
+ });
191
+ });
@@ -0,0 +1,331 @@
1
+ import type { TaDirEntry } from '@celljs/ta-protocol';
2
+ import { type GitFile, type GitStatus, GitUtil } from './git';
3
+ import type { TextMatch } from './search';
4
+
5
+ /** A row of the explorer: an entry and how deep it sits. */
6
+ export interface TreeRow {
7
+ entry: TaDirEntry;
8
+ depth: number;
9
+ expanded: boolean;
10
+ /** A directory whose entries are being read. */
11
+ loading: boolean;
12
+ }
13
+
14
+ /** The groups of source control, as VS Code has them: conflicts to merge, staged, the rest. */
15
+ export type GitGroup = 'merge' | 'staged' | 'changes';
16
+
17
+ export interface GitRow {
18
+ file: GitFile;
19
+ group: GitGroup;
20
+ /** The letter shown: M, A, D, R, C (copied), U (untracked) or ! (conflict). */
21
+ letter: string;
22
+ }
23
+
24
+ /** A folder of WorkspaceUtil.pathTree: `name` may be some folders (`a/b`); `size` counts the items inside it, at any depth, by their weight. */
25
+ export interface PathFolder<T> {
26
+ path: string;
27
+ name: string;
28
+ folders: PathFolder<T>[];
29
+ items: T[];
30
+ size: number;
31
+ }
32
+
33
+ /** What is wrong with a name typed in the explorer, or odd about it (a warning); undefined when it is fine. */
34
+ export type NameProblem = { key: 'nameEmpty' | 'nameSlash' | 'nameInvalid' | 'nameExists'; severity: 'error' } | { key: 'nameWhitespace'; severity: 'warning' };
35
+
36
+ /** A tab of a file or a diff as kept for the user (pi.storage `open-files`), in the order they opened. */
37
+ export interface KeptFile {
38
+ kind: 'file' | 'diff';
39
+ cwd: string;
40
+ path: string;
41
+ /** For a diff: of the index, against HEAD. */
42
+ staged?: boolean;
43
+ }
44
+
45
+ export interface FileMatches {
46
+ path: string;
47
+ matches: TextMatch[];
48
+ }
49
+
50
+ /** The pure parts of the views: paths, the tree, the groups of git and of search results. */
51
+ export namespace WorkspaceUtil {
52
+ /** The tabs kept, those that can still be read: from an older version or by hand, the others are left out. */
53
+ export function keptFiles(value: unknown): KeptFile[] {
54
+ if (!Array.isArray(value)) {
55
+ return [];
56
+ }
57
+ return value.flatMap((file): KeptFile[] => {
58
+ if (!file || (file.kind !== 'file' && file.kind !== 'diff') || typeof file.cwd !== 'string' || typeof file.path !== 'string') {
59
+ return [];
60
+ }
61
+ return [
62
+ file.kind === 'diff'
63
+ ? { kind: 'diff', cwd: file.cwd, path: file.path, staged: file.staged === true }
64
+ : { kind: 'file', cwd: file.cwd, path: file.path },
65
+ ];
66
+ });
67
+ }
68
+
69
+ /** The paths kept, as the directories open in the explorer; nothing from what is not a list of them. */
70
+ export function paths(value: unknown): string[] {
71
+ return Array.isArray(value) ? value.filter((path): path is string => typeof path === 'string') : [];
72
+ }
73
+
74
+ export function basename(path: string): string {
75
+ const trimmed = path.replace(/\/+$/, '');
76
+ return trimmed.slice(trimmed.lastIndexOf('/') + 1) || trimmed;
77
+ }
78
+
79
+ /** The directory of a relative path; '' for one at the top. */
80
+ export function dirname(path: string): string {
81
+ const index = path.lastIndexOf('/');
82
+ return index < 0 ? '' : path.slice(0, index);
83
+ }
84
+
85
+ /**
86
+ * The rows shown: the entries of `root`, and below each expanded directory its own, as far as they
87
+ * are read. `children` holds what was read, by the path of the directory ('' for the top).
88
+ */
89
+ export function rows(children: ReadonlyMap<string, TaDirEntry[]>, expanded: ReadonlySet<string>, root = ''): TreeRow[] {
90
+ const out: TreeRow[] = [];
91
+ const walk = (dir: string, depth: number) => {
92
+ for (const entry of children.get(dir) ?? []) {
93
+ const open = entry.kind === 'directory' && expanded.has(entry.path);
94
+ out.push({ entry, depth, expanded: open, loading: open && !children.has(entry.path) });
95
+ if (open) {
96
+ walk(entry.path, depth + 1);
97
+ }
98
+ }
99
+ };
100
+ walk(root, 0);
101
+ return out;
102
+ }
103
+
104
+ /** Toggles a directory; collapsing it also collapses those inside it. */
105
+ export function toggle(expanded: ReadonlySet<string>, path: string): Set<string> {
106
+ const next = new Set(expanded);
107
+ if (next.has(path)) {
108
+ for (const open of expanded) {
109
+ if (open === path || open.startsWith(`${path}/`)) {
110
+ next.delete(open);
111
+ }
112
+ }
113
+ } else {
114
+ next.add(path);
115
+ }
116
+ return next;
117
+ }
118
+
119
+ /** The directories to expand so that `path` shows. */
120
+ export function reveal(expanded: ReadonlySet<string>, path: string): Set<string> {
121
+ const next = new Set(expanded);
122
+ const parts = path.split('/');
123
+ for (let i = 1; i < parts.length; i++) {
124
+ next.add(parts.slice(0, i).join('/'));
125
+ }
126
+ return next;
127
+ }
128
+
129
+ /** By group (conflicts, staged, changes), each by path; a file changed in the index and the tree shows in both. */
130
+ export function gitRows(status: GitStatus): GitRow[] {
131
+ const groups: Record<GitGroup, GitRow[]> = { merge: [], staged: [], changes: [] };
132
+ for (const file of status.files) {
133
+ if (GitUtil.conflict(file)) {
134
+ groups.merge.push({ file, group: 'merge', letter: '!' });
135
+ continue;
136
+ }
137
+ if (file.staged) {
138
+ groups.staged.push({ file, group: 'staged', letter: file.staged });
139
+ }
140
+ if (file.unstaged) {
141
+ groups.changes.push({ file, group: 'changes', letter: file.unstaged === '?' ? 'U' : file.unstaged });
142
+ }
143
+ }
144
+ const byPath = (a: GitRow, b: GitRow) => compareNames(a.file.path, b.file.path);
145
+ return [...groups.merge.sort(byPath), ...groups.staged.sort(byPath), ...groups.changes.sort(byPath)];
146
+ }
147
+
148
+ /** The color of a letter of git, as VS Code colors the names: theme variables of the page. */
149
+ export function gitColor(letter: string | undefined): string | undefined {
150
+ switch (letter) {
151
+ case 'A':
152
+ case 'U':
153
+ case 'R':
154
+ case 'C':
155
+ return 'var(--taw-git-added)';
156
+ case 'D':
157
+ return 'var(--taw-git-deleted)';
158
+ case '!':
159
+ return 'var(--taw-git-conflict)';
160
+ case 'M':
161
+ case 'T':
162
+ return 'var(--taw-git-modified)';
163
+ default:
164
+ return undefined;
165
+ }
166
+ }
167
+
168
+ /** Names as people sort them (`file2` before `file10`). */
169
+ export function compareNames(a: string, b: string): number {
170
+ return a.localeCompare(b, undefined, { numeric: true, sensitivity: 'base' }) || (a < b ? -1 : a > b ? 1 : 0);
171
+ }
172
+
173
+ /**
174
+ * A name typed for a new file or folder, or a rename, in a folder that holds `siblings`: as VS Code
175
+ * checks it. `a/b.ts` makes the folders on its way; `..` and a leading slash would leave the folder.
176
+ */
177
+ export function validateName(name: string, siblings: readonly string[]): NameProblem | undefined {
178
+ if (!name?.trim()) {
179
+ return { key: 'nameEmpty', severity: 'error' };
180
+ }
181
+ if (name.startsWith('/') || name.startsWith('\\')) {
182
+ return { key: 'nameSlash', severity: 'error' };
183
+ }
184
+ const parts = name.split('/').filter(Boolean);
185
+ if (parts.some(part => part === '.' || part === '..' || part.includes('\0'))) {
186
+ return { key: 'nameInvalid', severity: 'error' };
187
+ }
188
+ const first = parts[0] ?? name;
189
+ if (siblings.some(sibling => sibling.toLowerCase() === first.toLowerCase()) && parts.length === 1) {
190
+ return { key: 'nameExists', severity: 'error' };
191
+ }
192
+ if (/^\s|\s$/.test(name)) {
193
+ return { key: 'nameWhitespace', severity: 'warning' };
194
+ }
195
+ return undefined;
196
+ }
197
+
198
+ /** `dir` and `name`, with `/`. */
199
+ export function join(dir: string, name: string): string {
200
+ return dir ? `${dir}/${name}` : name;
201
+ }
202
+
203
+ /** Whether `path` is `folder` or inside it. */
204
+ export function within(path: string, folder: string): boolean {
205
+ return !folder || path === folder || path.startsWith(`${folder}/`);
206
+ }
207
+
208
+ /** Matches by file, in the order the files first come. */
209
+ export function groupMatches(matches: TextMatch[]): FileMatches[] {
210
+ const files = new Map<string, TextMatch[]>();
211
+ for (const match of matches) {
212
+ const list = files.get(match.path);
213
+ if (list) {
214
+ list.push(match);
215
+ } else {
216
+ files.set(match.path, [match]);
217
+ }
218
+ }
219
+ return [...files].map(([path, list]) => ({ path, matches: list }));
220
+ }
221
+
222
+ /**
223
+ * A preview cut into before, the match and after, to mark the match. As VS Code, at most about
224
+ * `before` characters go before it, from the start of a word, so that a match far in a long line shows.
225
+ */
226
+ export function highlight(match: Pick<TextMatch, 'preview' | 'previewColumn' | 'length'>, before = 26): [string, string, string] {
227
+ const { preview, previewColumn: at, length } = match;
228
+ return [cutBefore(preview.slice(0, at), before), preview.slice(at, at + length), preview.slice(at + length)];
229
+ }
230
+
231
+ /** The end of a text, about `max` characters from the start of a word, after an ellipsis. */
232
+ export function cutBefore(text: string, max: number): string {
233
+ if (text.length <= max) {
234
+ return text;
235
+ }
236
+ const word = (char: string | undefined) => !!char && /[\p{L}\p{N}_]/u.test(char);
237
+ let start = text.length - max;
238
+ while (start < text.length && word(text[start - 1]) && word(text[start])) {
239
+ start++;
240
+ }
241
+ return `…${text.slice(start === text.length ? text.length - max : start)}`;
242
+ }
243
+
244
+ /**
245
+ * Items by folder, as the trees of an IDE: folders before items, each by name; a folder holding only
246
+ * one folder is shown with it (`a/b`). `pathOf` gives the path of an item, with `/`; `weight` what it
247
+ * counts for in the size of its folders (1).
248
+ */
249
+ export function pathTree<T>(items: readonly T[], pathOf: (item: T) => string, weight: (item: T) => number = () => 1): PathFolder<T> {
250
+ const root: PathFolder<T> = { path: '', name: '', folders: [], items: [], size: 0 };
251
+ const folders = new Map<string, PathFolder<T>>([['', root]]);
252
+ const folderOf = (path: string): PathFolder<T> => {
253
+ let folder = folders.get(path);
254
+ if (!folder) {
255
+ folder = { path, name: basename(path), folders: [], items: [], size: 0 };
256
+ folders.set(path, folder);
257
+ folderOf(dirname(path)).folders.push(folder);
258
+ }
259
+ return folder;
260
+ };
261
+ for (const item of items) {
262
+ folderOf(dirname(pathOf(item))).items.push(item);
263
+ }
264
+ const finish = (folder: PathFolder<T>): PathFolder<T> => {
265
+ let shown = folder;
266
+ while (shown !== root && shown.items.length === 0 && shown.folders.length === 1) {
267
+ const inner = shown.folders[0];
268
+ shown = { ...inner, name: `${shown.name}/${inner.name}` };
269
+ }
270
+ shown.folders = shown.folders.map(finish).sort((a, b) => compareNames(a.name, b.name));
271
+ shown.items.sort((a, b) => compareNames(basename(pathOf(a)), basename(pathOf(b))));
272
+ shown.size = shown.items.reduce((sum, item) => sum + weight(item), 0) + shown.folders.reduce((sum, inner) => sum + inner.size, 0);
273
+ return shown;
274
+ };
275
+ return finish(root);
276
+ }
277
+
278
+ /**
279
+ * What a page in the browser of the workbench may do. One of another site keeps its own origin, so that
280
+ * it works as in a tab; one of the origin of Ta (a link may point there) gets an origin of its own, or it
281
+ * could reach the page of Ta and its token.
282
+ */
283
+ export function frameSandbox(url: string, origin: string): string {
284
+ const base = 'allow-scripts allow-forms allow-popups allow-modals allow-downloads';
285
+ let own = true;
286
+ try {
287
+ own = new URL(url, origin).origin === origin;
288
+ } catch {
289
+ // Not a URL: as unsafe as one of Ta.
290
+ }
291
+ return own ? base : `${base} allow-same-origin`;
292
+ }
293
+
294
+ /** The absolute path of `path` of the directory `cwd`; `cwd` itself for ''. */
295
+ export function absolute(cwd: string, path: string): string {
296
+ return path ? `${cwd.replace(/\/+$/, '')}/${path}` : cwd;
297
+ }
298
+
299
+ /** What the address bar holds, as a URL: a bare host gets http, a word becomes a search. */
300
+ export function toUrl(input: string): string | undefined {
301
+ const text = input.trim();
302
+ if (!text) {
303
+ return undefined;
304
+ }
305
+ if (/^[a-z][a-z0-9+.-]*:\/\//i.test(text) || text.startsWith('about:')) {
306
+ return text;
307
+ }
308
+ if (/^(localhost|\d{1,3}(\.\d{1,3}){3}|\[[0-9a-f:]+\])(:\d+)?(\/.*)?$/i.test(text)) {
309
+ return `http://${text}`;
310
+ }
311
+ if (/^[^\s/]+\.[a-z]{2,}(:\d+)?(\/.*)?$/i.test(text)) {
312
+ return `https://${text}`;
313
+ }
314
+ return `https://www.bing.com/search?q=${encodeURIComponent(text)}`;
315
+ }
316
+
317
+ /** A size in bytes, as people read it. */
318
+ export function size(bytes: number): string {
319
+ if (bytes < 1024) {
320
+ return `${bytes} B`;
321
+ }
322
+ const units = ['KB', 'MB', 'GB'];
323
+ let value = bytes / 1024;
324
+ let unit = 0;
325
+ while (value >= 1024 && unit < units.length - 1) {
326
+ value /= 1024;
327
+ unit++;
328
+ }
329
+ return `${value < 10 ? value.toFixed(1) : Math.round(value)} ${units[unit]}`;
330
+ }
331
+ }
@@ -0,0 +1,119 @@
1
+ import type { TaCommandOutput, TaRunCommandOptions } from '@celljs/ta-protocol';
2
+ import { pi } from './host';
3
+ import { type FileDiff, type GitStatus, GitUtil } from './util/git';
4
+ import { type Searcher, SearchUtil, type TextQuery, type TextResult } from './util/search';
5
+ import { WorkspaceUtil } from './util/workspace';
6
+
7
+ const SEARCH_LIMIT = 2000;
8
+ const SEARCH_BYTES = 8 * 1024 * 1024;
9
+ const SEARCHERS: Searcher[] = ['rg', 'git', 'grep'];
10
+ /** Pulling and pushing wait for the network. */
11
+ const REMOTE_TIMEOUT_MS = 120000;
12
+
13
+ /** Search, git and changes to files for the views: the programs of the server (runCommand), read here. */
14
+ export namespace WorkspaceClient {
15
+ /** The searchers that could not run, by directory: the next search skips them. */
16
+ const missing = new Map<string, Set<Searcher>>();
17
+
18
+ export async function search(cwd: string, query: TextQuery): Promise<TextResult> {
19
+ const expression = SearchUtil.queryRegExp(query);
20
+ const filter = query.include || query.exclude ? SearchUtil.pathFilter(query) : undefined;
21
+ const skip = missing.get(cwd) ?? new Set<Searcher>();
22
+ missing.set(cwd, skip);
23
+ for (const searcher of SEARCHERS.filter(candidate => !skip.has(candidate))) {
24
+ const { command, args } = SearchUtil.command(searcher, query);
25
+ const output = await pi.workspace.runCommand(command, args, { cwd, maxBytes: SEARCH_BYTES });
26
+ if (SearchUtil.unavailable(searcher, output.exitCode, output.timedOut)) {
27
+ skip.add(searcher);
28
+ continue;
29
+ }
30
+ if (output.exitCode !== 0 && output.exitCode !== 1 && !output.stdout) {
31
+ throw new Error(output.stderr.trim() || `${command} failed.`);
32
+ }
33
+ const result = SearchUtil.parseMatches(output.stdout, expression, SEARCH_LIMIT, filter);
34
+ return { ...result, truncated: result.truncated || output.truncated || output.timedOut };
35
+ }
36
+ throw new Error('Neither rg, git nor grep can run here.');
37
+ }
38
+
39
+ /** With `ignored`, also what .gitignore leaves out, for the explorer. */
40
+ export async function status(cwd: string, ignored = false): Promise<GitStatus> {
41
+ const prefix = await pi.workspace.runCommand('git', GitUtil.PREFIX, { cwd });
42
+ if (prefix.exitCode !== 0) {
43
+ return { repository: false, files: [] };
44
+ }
45
+ const status = await pi.workspace.runCommand('git', GitUtil.status(ignored), { cwd, maxBytes: SEARCH_BYTES });
46
+ if (status.exitCode !== 0) {
47
+ throw new Error(status.stderr.trim() || 'git status failed.');
48
+ }
49
+ return GitUtil.parseStatus(status.stdout, prefix.stdout.trim());
50
+ }
51
+
52
+ /** Staged: the index against HEAD. Not staged: the working tree against the index. */
53
+ export async function diff(cwd: string, path: string, staged: boolean): Promise<FileDiff> {
54
+ const show = async (revision: string) => {
55
+ const shown = await pi.workspace.runCommand('git', GitUtil.show(revision, path), { cwd });
56
+ return shown.exitCode === 0 ? shown.stdout : '';
57
+ };
58
+ if (staged) {
59
+ return { path, before: await show('HEAD'), after: await show('') };
60
+ }
61
+ const tracked = (await pi.workspace.runCommand('git', GitUtil.tracked(path), { cwd })).exitCode === 0;
62
+ const before = tracked ? await show('') : '';
63
+ const after = await pi.workspace.readFile(path, cwd).then(
64
+ file => file.text ?? '',
65
+ () => '',
66
+ );
67
+ return { path, before, after };
68
+ }
69
+
70
+ /** Runs git; a failure throws what git said. */
71
+ export async function git(cwd: string, args: string[], options: TaRunCommandOptions = {}): Promise<TaCommandOutput> {
72
+ const output = await pi.workspace.runCommand('git', args, { ...options, cwd });
73
+ if (output.timedOut) {
74
+ throw new Error(`git ${args[0]} took too long.`);
75
+ }
76
+ if (output.exitCode !== 0) {
77
+ throw new Error(output.stderr.trim() || output.stdout.trim() || `git ${args[0]} failed.`);
78
+ }
79
+ return output;
80
+ }
81
+
82
+ export function commit(cwd: string, message: string): Promise<TaCommandOutput> {
83
+ return git(cwd, GitUtil.COMMIT, { input: message });
84
+ }
85
+
86
+ export function remote(cwd: string, command: 'pull' | 'push' | 'fetch'): Promise<TaCommandOutput> {
87
+ return git(cwd, [command], { timeoutMs: REMOTE_TIMEOUT_MS });
88
+ }
89
+
90
+ /** Runs a program of the files of `cwd`; a failure throws what it said. */
91
+ async function run(cwd: string, command: string, args: string[]): Promise<void> {
92
+ const output = await pi.workspace.runCommand(command, args, { cwd });
93
+ if (output.exitCode !== 0) {
94
+ throw new Error(output.stderr.trim() || `${command} failed.`);
95
+ }
96
+ }
97
+
98
+ /** An empty file; the folders on its way are made. */
99
+ export async function createFile(cwd: string, path: string): Promise<void> {
100
+ const dir = WorkspaceUtil.dirname(path);
101
+ if (dir) {
102
+ await run(cwd, 'mkdir', ['-p', '--', dir]);
103
+ }
104
+ await pi.workspace.writeFile(path, '', cwd);
105
+ }
106
+
107
+ export function createFolder(cwd: string, path: string): Promise<void> {
108
+ return run(cwd, 'mkdir', ['-p', '--', path]);
109
+ }
110
+
111
+ /** Never over another file: `mv -n` keeps what is there. */
112
+ export function rename(cwd: string, from: string, to: string): Promise<void> {
113
+ return run(cwd, 'mv', ['-n', '--', from, to]);
114
+ }
115
+
116
+ export function remove(cwd: string, path: string): Promise<void> {
117
+ return run(cwd, 'rm', ['-rf', '--', path]);
118
+ }
119
+ }