@celljs/ta-workspace 4.6.1 → 4.8.0
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/README.md +5 -5
- package/README.zh-cn.md +29 -0
- package/package.json +3 -3
- package/web/index.js +1955 -637
- package/web-src/browser-agent.ts +440 -0
- package/web-src/browser-common.tsx +278 -0
- package/web-src/browser-import.tsx +126 -0
- package/web-src/browser-webview.tsx +270 -0
- package/web-src/browser.tsx +37 -197
- package/web-src/explorer.tsx +241 -3
- package/web-src/i18n.ts +77 -2
- package/web-src/index.tsx +7 -1
- package/web-src/style.ts +35 -6
- package/web-src/terminal.tsx +53 -134
- package/web-src/util/browser-snapshot.spec.ts +96 -0
- package/web-src/util/browser-snapshot.ts +225 -0
- package/web-src/util/upload.spec.ts +66 -0
- package/web-src/util/upload.ts +123 -0
- package/web-src/util/workspace.spec.ts +42 -13
- package/web-src/util/workspace.ts +65 -0
- package/web-src/util/zip.spec.ts +60 -0
- package/web-src/util/zip.ts +137 -0
- package/web-src/workspace-client.ts +103 -1
- package/web-src/util/ansi.spec.ts +0 -66
- package/web-src/util/ansi.ts +0 -438
- package/web-src/util/keys.ts +0 -56
|
@@ -0,0 +1,225 @@
|
|
|
1
|
+
/** A node of Accessibility.getFullAXTree, as much of it as a snapshot reads. */
|
|
2
|
+
export interface AXNode {
|
|
3
|
+
nodeId: string;
|
|
4
|
+
parentId?: string;
|
|
5
|
+
ignored?: boolean;
|
|
6
|
+
role?: { value?: unknown };
|
|
7
|
+
name?: { value?: unknown };
|
|
8
|
+
value?: { value?: unknown };
|
|
9
|
+
description?: { value?: unknown };
|
|
10
|
+
properties?: { name: string; value?: { value?: unknown } }[];
|
|
11
|
+
childIds?: string[];
|
|
12
|
+
backendDOMNodeId?: number;
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
/** Roles of what one acts on: they get a ref, the number in brackets. */
|
|
16
|
+
const ACTIONABLE: ReadonlySet<string> = new Set([
|
|
17
|
+
'button',
|
|
18
|
+
'checkbox',
|
|
19
|
+
'combobox',
|
|
20
|
+
'link',
|
|
21
|
+
'listbox',
|
|
22
|
+
'menuitem',
|
|
23
|
+
'menuitemcheckbox',
|
|
24
|
+
'menuitemradio',
|
|
25
|
+
'option',
|
|
26
|
+
'radio',
|
|
27
|
+
'searchbox',
|
|
28
|
+
'slider',
|
|
29
|
+
'spinbutton',
|
|
30
|
+
'switch',
|
|
31
|
+
'tab',
|
|
32
|
+
'textbox',
|
|
33
|
+
'treeitem',
|
|
34
|
+
]);
|
|
35
|
+
/** Roles that say nothing: their children are shown in their place. */
|
|
36
|
+
const SKIPPED: ReadonlySet<string> = new Set(['none', 'presentation', 'InlineTextBox', 'LineBreak']);
|
|
37
|
+
/** Containers shown only when they have a name. */
|
|
38
|
+
const TRANSPARENT: ReadonlySet<string> = new Set([
|
|
39
|
+
'generic',
|
|
40
|
+
'group',
|
|
41
|
+
'paragraph',
|
|
42
|
+
'Section',
|
|
43
|
+
'LayoutTable',
|
|
44
|
+
'LayoutTableRow',
|
|
45
|
+
'LayoutTableCell',
|
|
46
|
+
'LabelText',
|
|
47
|
+
'RootWebArea',
|
|
48
|
+
'WebArea',
|
|
49
|
+
]);
|
|
50
|
+
const STATES = ['focused', 'checked', 'selected', 'pressed', 'disabled', 'required', 'readonly', 'invalid'] as const;
|
|
51
|
+
const MAX_NAME = 120;
|
|
52
|
+
|
|
53
|
+
export interface KeyPress {
|
|
54
|
+
key: string;
|
|
55
|
+
code: string;
|
|
56
|
+
windowsVirtualKeyCode: number;
|
|
57
|
+
/** Alt 1, Control 2, Meta 4, Shift 8, as the DevTools protocol counts them. */
|
|
58
|
+
modifiers: number;
|
|
59
|
+
/** What the key types; none for a shortcut. */
|
|
60
|
+
text?: string;
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
const MODIFIERS: Record<string, number> = { alt: 1, option: 1, control: 2, ctrl: 2, meta: 4, cmd: 4, command: 4, shift: 8 };
|
|
64
|
+
const NAMED: Record<string, [code: number, text?: string]> = {
|
|
65
|
+
Enter: [13, '\r'],
|
|
66
|
+
Tab: [9],
|
|
67
|
+
Escape: [27],
|
|
68
|
+
Backspace: [8],
|
|
69
|
+
Delete: [46],
|
|
70
|
+
ArrowUp: [38],
|
|
71
|
+
ArrowDown: [40],
|
|
72
|
+
ArrowLeft: [37],
|
|
73
|
+
ArrowRight: [39],
|
|
74
|
+
Home: [36],
|
|
75
|
+
End: [35],
|
|
76
|
+
PageUp: [33],
|
|
77
|
+
PageDown: [34],
|
|
78
|
+
Space: [32, ' '],
|
|
79
|
+
};
|
|
80
|
+
|
|
81
|
+
/** How the agent reads a page and gives it keys: the accessibility tree as lines, key names as key events. */
|
|
82
|
+
export namespace BrowserSnapshot {
|
|
83
|
+
function text(value: unknown, max = MAX_NAME): string {
|
|
84
|
+
const line = String(value ?? '')
|
|
85
|
+
.replace(/\s+/g, ' ')
|
|
86
|
+
.trim();
|
|
87
|
+
return line.length > max ? `${line.slice(0, max - 1)}…` : line;
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
function property(node: AXNode, name: string): unknown {
|
|
91
|
+
return node.properties?.find(item => item.name === name)?.value?.value;
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
/**
|
|
95
|
+
* The page as indented lines, `[ref] role "name" (states) value=…`: what one can act on has a ref (its
|
|
96
|
+
* backendDOMNodeId, the same until the page changes), containers without a name give way to their
|
|
97
|
+
* children, text is shown where its parent's name does not already say it. At most `maxLines`.
|
|
98
|
+
*/
|
|
99
|
+
export function render(nodes: AXNode[], maxLines = 800): string {
|
|
100
|
+
const byId = new Map(nodes.map(node => [node.nodeId, node]));
|
|
101
|
+
const lines: string[] = [];
|
|
102
|
+
let more = 0;
|
|
103
|
+
const add = (line: string) => {
|
|
104
|
+
if (lines.length < maxLines) {
|
|
105
|
+
lines.push(line);
|
|
106
|
+
} else {
|
|
107
|
+
more++;
|
|
108
|
+
}
|
|
109
|
+
};
|
|
110
|
+
const visit = (node: AXNode, depth: number, parentName: string, inActionable = false) => {
|
|
111
|
+
const role = String(node.role?.value ?? '');
|
|
112
|
+
const name = text(node.name?.value);
|
|
113
|
+
const children = (node.childIds ?? []).map(id => byId.get(id)).filter((child): child is AXNode => child !== undefined);
|
|
114
|
+
const pass = (nextDepth: number, nextName: string, nextInActionable = inActionable) => {
|
|
115
|
+
for (const child of children) {
|
|
116
|
+
visit(child, nextDepth, nextName, nextInActionable);
|
|
117
|
+
}
|
|
118
|
+
};
|
|
119
|
+
if (node.ignored || SKIPPED.has(role)) {
|
|
120
|
+
pass(depth, parentName);
|
|
121
|
+
return;
|
|
122
|
+
}
|
|
123
|
+
if (role === 'StaticText') {
|
|
124
|
+
if (name && !parentName.includes(name)) {
|
|
125
|
+
add(`${' '.repeat(depth)}${JSON.stringify(name)}`);
|
|
126
|
+
}
|
|
127
|
+
return;
|
|
128
|
+
}
|
|
129
|
+
// The editor inside a text field is editable too: the field is what one acts on.
|
|
130
|
+
const actionable = (ACTIONABLE.has(role) || (property(node, 'editable') !== undefined && !inActionable)) && node.backendDOMNodeId !== undefined;
|
|
131
|
+
if (!actionable && TRANSPARENT.has(role) && !name) {
|
|
132
|
+
pass(depth, parentName);
|
|
133
|
+
return;
|
|
134
|
+
}
|
|
135
|
+
let line = `${' '.repeat(depth)}${actionable ? `[${node.backendDOMNodeId}] ` : ''}${role}${name ? ` ${JSON.stringify(name)}` : ''}`;
|
|
136
|
+
const level = property(node, 'level');
|
|
137
|
+
if (level !== undefined) {
|
|
138
|
+
line += ` level=${level}`;
|
|
139
|
+
}
|
|
140
|
+
const states: string[] = STATES.filter(state => {
|
|
141
|
+
const value = property(node, state);
|
|
142
|
+
return value === true || value === 'true' || value === 'mixed';
|
|
143
|
+
}).map(state => (property(node, state) === 'mixed' ? `${state}=mixed` : state));
|
|
144
|
+
const expanded = property(node, 'expanded');
|
|
145
|
+
if (expanded !== undefined) {
|
|
146
|
+
states.push(expanded ? 'expanded' : 'collapsed');
|
|
147
|
+
}
|
|
148
|
+
if (states.length > 0) {
|
|
149
|
+
line += ` (${states.join(', ')})`;
|
|
150
|
+
}
|
|
151
|
+
const value = text(node.value?.value);
|
|
152
|
+
if (value && value !== name) {
|
|
153
|
+
line += ` value=${JSON.stringify(value)}`;
|
|
154
|
+
}
|
|
155
|
+
const description = text(node.description?.value, 80);
|
|
156
|
+
if (description && description !== name) {
|
|
157
|
+
line += ` description=${JSON.stringify(description)}`;
|
|
158
|
+
}
|
|
159
|
+
add(line);
|
|
160
|
+
pass(depth + 1, name, inActionable || actionable);
|
|
161
|
+
};
|
|
162
|
+
for (const root of nodes.filter(node => !node.parentId || !byId.has(node.parentId))) {
|
|
163
|
+
visit(root, 0, '');
|
|
164
|
+
}
|
|
165
|
+
if (more > 0) {
|
|
166
|
+
lines.push(`… ${more} more lines: scroll, or evaluate to read a part of the page.`);
|
|
167
|
+
}
|
|
168
|
+
return lines.length > 0 ? lines.join('\n') : '(the page shows nothing to read yet)';
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
/** The middle of a quad of DOM.getContentQuads: x1, y1 … x4, y4. */
|
|
172
|
+
export function center(quad: number[]): { x: number; y: number } {
|
|
173
|
+
const xs = [quad[0], quad[2], quad[4], quad[6]];
|
|
174
|
+
const ys = [quad[1], quad[3], quad[5], quad[7]];
|
|
175
|
+
return { x: (Math.min(...xs) + Math.max(...xs)) / 2, y: (Math.min(...ys) + Math.max(...ys)) / 2 };
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
/** `Enter`, `a`, `Control+A`, `Meta+Shift+ArrowLeft`, `F5`: what to send for it; `undefined` for no key. */
|
|
179
|
+
export function key(input: string): KeyPress | undefined {
|
|
180
|
+
const parts = input.split('+');
|
|
181
|
+
// "+" itself, or a shortcut ending in it ("Control++").
|
|
182
|
+
const name = input.endsWith('++') || input === '+' ? '+' : parts.pop();
|
|
183
|
+
if (!name) {
|
|
184
|
+
return undefined;
|
|
185
|
+
}
|
|
186
|
+
let modifiers = 0;
|
|
187
|
+
for (const part of input === '+' ? [] : parts.filter(Boolean)) {
|
|
188
|
+
const bit = MODIFIERS[part.toLowerCase()];
|
|
189
|
+
if (bit === undefined) {
|
|
190
|
+
return undefined;
|
|
191
|
+
}
|
|
192
|
+
modifiers |= bit;
|
|
193
|
+
}
|
|
194
|
+
const shortcut = (modifiers & (2 | 4)) !== 0;
|
|
195
|
+
const named = Object.keys(NAMED).find(candidate => candidate.toLowerCase() === name.toLowerCase());
|
|
196
|
+
if (named) {
|
|
197
|
+
const [code, typed] = NAMED[named];
|
|
198
|
+
return {
|
|
199
|
+
key: named === 'Space' ? ' ' : named,
|
|
200
|
+
code: named,
|
|
201
|
+
windowsVirtualKeyCode: code,
|
|
202
|
+
modifiers,
|
|
203
|
+
...(typed && !shortcut ? { text: typed } : {}),
|
|
204
|
+
};
|
|
205
|
+
}
|
|
206
|
+
const fn = /^F([1-9]|1[0-2])$/i.exec(name);
|
|
207
|
+
if (fn) {
|
|
208
|
+
return { key: `F${fn[1]}`, code: `F${fn[1]}`, windowsVirtualKeyCode: 111 + Number(fn[1]), modifiers };
|
|
209
|
+
}
|
|
210
|
+
if ([...name].length !== 1) {
|
|
211
|
+
return undefined;
|
|
212
|
+
}
|
|
213
|
+
const shifted = (modifiers & 8) !== 0;
|
|
214
|
+
const letter = /^[a-z]$/i.test(name);
|
|
215
|
+
const digit = /^[0-9]$/.test(name);
|
|
216
|
+
const key = letter ? (shifted ? name.toUpperCase() : name.toLowerCase()) : name;
|
|
217
|
+
return {
|
|
218
|
+
key,
|
|
219
|
+
code: letter ? `Key${name.toUpperCase()}` : digit ? `Digit${name}` : '',
|
|
220
|
+
windowsVirtualKeyCode: letter ? name.toUpperCase().charCodeAt(0) : digit ? name.charCodeAt(0) : 0,
|
|
221
|
+
modifiers,
|
|
222
|
+
...(shortcut ? {} : { text: key }),
|
|
223
|
+
};
|
|
224
|
+
}
|
|
225
|
+
}
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
import { describe, expect, it } from 'bun:test';
|
|
2
|
+
import { UploadUtil } from './upload';
|
|
3
|
+
|
|
4
|
+
function fileEntry(name: string) {
|
|
5
|
+
return { name, isFile: true, isDirectory: false, file: (done: (file: File) => void) => done(new File([name], name)) };
|
|
6
|
+
}
|
|
7
|
+
|
|
8
|
+
function folderEntry(name: string, children: object[]) {
|
|
9
|
+
return {
|
|
10
|
+
name,
|
|
11
|
+
isFile: false,
|
|
12
|
+
isDirectory: true,
|
|
13
|
+
createReader: () => {
|
|
14
|
+
// In two batches, then an empty one, as browsers read a folder.
|
|
15
|
+
const batches = [children.slice(0, 1), children.slice(1), []];
|
|
16
|
+
return { readEntries: (done: (entries: object[]) => void) => done(batches.shift() ?? []) };
|
|
17
|
+
},
|
|
18
|
+
};
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
function drop(entries: object[], files: File[] = []): Pick<DataTransfer, 'files' | 'items'> {
|
|
22
|
+
return {
|
|
23
|
+
files: files as unknown as FileList,
|
|
24
|
+
items: entries.map(entry => ({ kind: 'file', webkitGetAsEntry: () => entry })) as unknown as DataTransferItemList,
|
|
25
|
+
};
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
describe('UploadUtil', () => {
|
|
29
|
+
it('reads dropped folders through, with their empty folders', async () => {
|
|
30
|
+
const batch = await UploadUtil.fromDrop(
|
|
31
|
+
drop([folderEntry('app', [fileEntry('a.ts'), folderEntry('empty', []), folderEntry('src', [fileEntry('b.ts')])]), fileEntry('README.md')]),
|
|
32
|
+
);
|
|
33
|
+
expect(batch.files.map(file => file.path)).toEqual(['app/a.ts', 'app/src/b.ts', 'README.md']);
|
|
34
|
+
expect(batch.folders).toEqual(['app', 'app/empty', 'app/src']);
|
|
35
|
+
expect(UploadUtil.emptyFolders(batch)).toEqual(['app/empty']);
|
|
36
|
+
expect(UploadUtil.topNames(batch)).toEqual(['app', 'README.md']);
|
|
37
|
+
});
|
|
38
|
+
|
|
39
|
+
it('takes the files of a drop without entries, and those of a folder picker with their paths', async () => {
|
|
40
|
+
const file = new File(['x'], 'x.txt');
|
|
41
|
+
expect(await UploadUtil.fromDrop(drop([], [file]))).toEqual({ files: [{ path: 'x.txt', file }], folders: [] });
|
|
42
|
+
const picked = new File(['y'], 'y.txt');
|
|
43
|
+
Object.defineProperty(picked, 'webkitRelativePath', { value: 'app/src/y.txt' });
|
|
44
|
+
expect(UploadUtil.fromFiles([picked]).files[0].path).toBe('app/src/y.txt');
|
|
45
|
+
});
|
|
46
|
+
|
|
47
|
+
it('turns away paths that leave the folder', () => {
|
|
48
|
+
expect(() => UploadUtil.segments('../etc/passwd')).toThrow('Not a path');
|
|
49
|
+
expect(() => UploadUtil.segments('')).toThrow('Not a path');
|
|
50
|
+
expect(UploadUtil.segments('a\\b/./c')).toEqual(['a', 'b', 'c']);
|
|
51
|
+
});
|
|
52
|
+
|
|
53
|
+
it('cuts a file into parts, one empty part for an empty file', () => {
|
|
54
|
+
expect(UploadUtil.parts(10, 4)).toEqual([
|
|
55
|
+
[0, 4],
|
|
56
|
+
[4, 8],
|
|
57
|
+
[8, 10],
|
|
58
|
+
]);
|
|
59
|
+
expect(UploadUtil.parts(0, 4)).toEqual([[0, 0]]);
|
|
60
|
+
});
|
|
61
|
+
|
|
62
|
+
it('writes base64 of large buffers', () => {
|
|
63
|
+
const bytes = new Uint8Array(100000).map((_, i) => i % 256);
|
|
64
|
+
expect(UploadUtil.toBase64(bytes)).toBe(Buffer.from(bytes).toString('base64'));
|
|
65
|
+
});
|
|
66
|
+
});
|
|
@@ -0,0 +1,123 @@
|
|
|
1
|
+
/** A file to upload, at a path relative to the folder it goes to (`docs/a.md`). */
|
|
2
|
+
export interface UploadFile {
|
|
3
|
+
path: string;
|
|
4
|
+
file: Blob & { readonly name: string };
|
|
5
|
+
}
|
|
6
|
+
|
|
7
|
+
/** What a drop or a picker gives: files, and folders, as the empty ones a dropped folder holds. */
|
|
8
|
+
export interface UploadBatch {
|
|
9
|
+
files: UploadFile[];
|
|
10
|
+
folders: string[];
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
/** An entry of a folder dropped from the system (the File System API of browsers, `webkitGetAsEntry`). */
|
|
14
|
+
interface DroppedEntry {
|
|
15
|
+
readonly name: string;
|
|
16
|
+
readonly isFile: boolean;
|
|
17
|
+
readonly isDirectory: boolean;
|
|
18
|
+
file?(success: (file: File) => void, failure?: (error: unknown) => void): void;
|
|
19
|
+
createReader?(): { readEntries(success: (entries: DroppedEntry[]) => void, failure?: (error: unknown) => void): void };
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
/** Files of the user's machine to the files of a directory: what they are, read from a drop or a picker. */
|
|
23
|
+
export namespace UploadUtil {
|
|
24
|
+
/** The parts of a relative path; throws for one that would leave its folder. */
|
|
25
|
+
export function segments(path: string): string[] {
|
|
26
|
+
const parts = path.split(/[\\/]+/).filter(part => part && part !== '.');
|
|
27
|
+
if (!parts.length || parts.some(part => part === '..' || part.includes('\0'))) {
|
|
28
|
+
throw new Error(`Not a path to upload to: ${path}`);
|
|
29
|
+
}
|
|
30
|
+
return parts;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/** Files of `<input type="file">`; a folder picker gives each its path in it (`webkitRelativePath`). */
|
|
34
|
+
export function fromFiles(files: Iterable<File>): UploadBatch {
|
|
35
|
+
return { files: Array.from(files, file => ({ path: file.webkitRelativePath || file.name, file })), folders: [] };
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/**
|
|
39
|
+
* Files and folders dropped from the system, folders read through. The entries are taken before the first
|
|
40
|
+
* await: the browser empties the items of a drop once its event returns.
|
|
41
|
+
*/
|
|
42
|
+
export async function fromDrop(dataTransfer: Pick<DataTransfer, 'files' | 'items'>): Promise<UploadBatch> {
|
|
43
|
+
const entries = Array.from(dataTransfer.items ?? [])
|
|
44
|
+
.filter(item => item.kind === 'file')
|
|
45
|
+
.map(item => item.webkitGetAsEntry?.() as DroppedEntry | null | undefined);
|
|
46
|
+
if (!entries.length || entries.some(entry => !entry)) {
|
|
47
|
+
return fromFiles(Array.from(dataTransfer.files ?? []));
|
|
48
|
+
}
|
|
49
|
+
const batch: UploadBatch = { files: [], folders: [] };
|
|
50
|
+
for (const entry of entries as DroppedEntry[]) {
|
|
51
|
+
await collect(entry, '', batch);
|
|
52
|
+
}
|
|
53
|
+
return batch;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
async function collect(entry: DroppedEntry, folder: string, batch: UploadBatch): Promise<void> {
|
|
57
|
+
const path = folder ? `${folder}/${entry.name}` : entry.name;
|
|
58
|
+
if (entry.isFile && entry.file) {
|
|
59
|
+
const read = entry.file.bind(entry);
|
|
60
|
+
batch.files.push({ path, file: await new Promise<File>((resolve, reject) => read(resolve, reject)) });
|
|
61
|
+
} else if (entry.isDirectory && entry.createReader) {
|
|
62
|
+
batch.folders.push(path);
|
|
63
|
+
const reader = entry.createReader();
|
|
64
|
+
// A reader gives a folder in batches (about 100 entries), then an empty one.
|
|
65
|
+
for (;;) {
|
|
66
|
+
const children = await new Promise<DroppedEntry[]>((resolve, reject) => reader.readEntries(resolve, reject));
|
|
67
|
+
if (!children.length) {
|
|
68
|
+
break;
|
|
69
|
+
}
|
|
70
|
+
for (const child of children) {
|
|
71
|
+
await collect(child, path, batch);
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
/** The names the batch puts in the folder it goes to: what may already be there. */
|
|
78
|
+
export function topNames(batch: UploadBatch): string[] {
|
|
79
|
+
const names = new Set<string>();
|
|
80
|
+
for (const path of [...batch.files.map(file => file.path), ...batch.folders]) {
|
|
81
|
+
names.add(segments(path)[0]);
|
|
82
|
+
}
|
|
83
|
+
return [...names];
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
/** The folders no file of the batch is in: uploading the files makes the others. */
|
|
87
|
+
export function emptyFolders(batch: UploadBatch): string[] {
|
|
88
|
+
const filled = new Set<string>();
|
|
89
|
+
for (const { path } of batch.files) {
|
|
90
|
+
const parts = segments(path);
|
|
91
|
+
for (let i = 1; i < parts.length; i++) {
|
|
92
|
+
filled.add(parts.slice(0, i).join('/'));
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
const folders = batch.folders.map(folder => segments(folder).join('/'));
|
|
96
|
+
return [...new Set(folders)].filter(folder => !filled.has(folder) && !folders.some(other => other.startsWith(`${folder}/`)));
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
export function totalBytes(batch: UploadBatch): number {
|
|
100
|
+
return batch.files.reduce((sum, { file }) => sum + file.size, 0);
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
/** The parts a file of `size` bytes is sent in, as [start, end) offsets; one empty part for an empty file. */
|
|
104
|
+
export function parts(size: number, partBytes: number): [number, number][] {
|
|
105
|
+
if (size === 0) {
|
|
106
|
+
return [[0, 0]];
|
|
107
|
+
}
|
|
108
|
+
const out: [number, number][] = [];
|
|
109
|
+
for (let start = 0; start < size; start += partBytes) {
|
|
110
|
+
out.push([start, Math.min(size, start + partBytes)]);
|
|
111
|
+
}
|
|
112
|
+
return out;
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
/** Bytes in base64, in pieces so that a large buffer does not overflow the arguments of a call. */
|
|
116
|
+
export function toBase64(bytes: Uint8Array): string {
|
|
117
|
+
let binary = '';
|
|
118
|
+
for (let i = 0; i < bytes.length; i += 0x8000) {
|
|
119
|
+
binary += String.fromCharCode(...bytes.subarray(i, i + 0x8000));
|
|
120
|
+
}
|
|
121
|
+
return btoa(binary);
|
|
122
|
+
}
|
|
123
|
+
}
|
|
@@ -1,6 +1,5 @@
|
|
|
1
1
|
import { describe, expect, it } from 'bun:test';
|
|
2
2
|
import type { TaDirEntry } from '@celljs/ta-protocol';
|
|
3
|
-
import { TerminalKeys } from './keys';
|
|
4
3
|
import { WorkspaceUtil } from './workspace';
|
|
5
4
|
|
|
6
5
|
const dir = (path: string): TaDirEntry => ({ name: WorkspaceUtil.basename(path), path, kind: 'directory' });
|
|
@@ -141,18 +140,6 @@ describe('WorkspaceUtil', () => {
|
|
|
141
140
|
});
|
|
142
141
|
});
|
|
143
142
|
|
|
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
143
|
describe('WorkspaceUtil links', () => {
|
|
157
144
|
it('makes the path of a link absolute', () => {
|
|
158
145
|
expect(WorkspaceUtil.absolute('/repo', 'src')).toBe('/repo/src');
|
|
@@ -188,4 +175,46 @@ describe('WorkspaceUtil kept state', () => {
|
|
|
188
175
|
expect(WorkspaceUtil.paths(['src', 1, 'src/a'])).toEqual(['src', 'src/a']);
|
|
189
176
|
expect(WorkspaceUtil.paths('src')).toEqual([]);
|
|
190
177
|
});
|
|
178
|
+
|
|
179
|
+
it('tells the port of a page of localhost, and moves it to another', () => {
|
|
180
|
+
expect(WorkspaceUtil.localPort('http://localhost:5173/app')).toBe(5173);
|
|
181
|
+
expect(WorkspaceUtil.localPort('http://127.0.0.1/')).toBe(80);
|
|
182
|
+
expect(WorkspaceUtil.localPort('http://[::1]:3000')).toBe(3000);
|
|
183
|
+
expect(WorkspaceUtil.localPort('https://example.com:3000')).toBeUndefined();
|
|
184
|
+
expect(WorkspaceUtil.localPort('not a url')).toBeUndefined();
|
|
185
|
+
expect(WorkspaceUtil.withPort('http://localhost:5173/app?x=1#y', 61000)).toBe('http://localhost:61000/app?x=1#y');
|
|
186
|
+
expect(WorkspaceUtil.withPort('http://0.0.0.0:8080/', 61001)).toBe('http://localhost:61001/');
|
|
187
|
+
});
|
|
188
|
+
|
|
189
|
+
it('shows a page of a forwarded port at the address asked for', () => {
|
|
190
|
+
const asked = 'http://localhost:3000/';
|
|
191
|
+
const shown = 'http://localhost:61000/';
|
|
192
|
+
expect(WorkspaceUtil.unforward('http://localhost:61000/app?x=1', asked, shown)).toBe('http://localhost:3000/app?x=1');
|
|
193
|
+
expect(WorkspaceUtil.unforward('https://github.com/login', asked, shown)).toBe('https://github.com/login');
|
|
194
|
+
expect(WorkspaceUtil.unforward('https://x.dev/a', 'https://x.dev/', 'https://x.dev/')).toBe('https://x.dev/a');
|
|
195
|
+
expect(WorkspaceUtil.unforward('http://localhost:3000/', asked, undefined)).toBe('http://localhost:3000/');
|
|
196
|
+
expect(WorkspaceUtil.unforward('about:blank', '', undefined)).toBe('about:blank');
|
|
197
|
+
});
|
|
198
|
+
it('moves what can move into a folder, and finds where it went', () => {
|
|
199
|
+
expect(WorkspaceUtil.movable(['src', 'README.md'], 'src/lib')).toEqual(['README.md']);
|
|
200
|
+
expect(WorkspaceUtil.movable(['src/a.ts'], 'src')).toEqual([]);
|
|
201
|
+
expect(WorkspaceUtil.movable(['src', 'src/a.ts', 'docs'], 'lib')).toEqual(['src', 'docs']);
|
|
202
|
+
expect(WorkspaceUtil.movable(['src'], 'srcs')).toEqual(['src']);
|
|
203
|
+
expect(WorkspaceUtil.movable(['docs/a.md'], '')).toEqual(['docs/a.md']);
|
|
204
|
+
expect(WorkspaceUtil.movedTo('src/lib/b.ts', ['src'], 'docs')).toBe('docs/src/lib/b.ts');
|
|
205
|
+
expect(WorkspaceUtil.movedTo('docs/a.md', ['docs/a.md'], '')).toBe('a.md');
|
|
206
|
+
expect(WorkspaceUtil.movedTo('other.ts', ['src'], 'docs')).toBeUndefined();
|
|
207
|
+
});
|
|
208
|
+
|
|
209
|
+
it('quotes paths for a shell', () => {
|
|
210
|
+
expect(WorkspaceUtil.shellQuote('/work/app/src/a.ts')).toBe('/work/app/src/a.ts');
|
|
211
|
+
expect(WorkspaceUtil.shellQuote("/work/my app/it's.md")).toBe("'/work/my app/it'\\''s.md'");
|
|
212
|
+
expect(WorkspaceUtil.shellQuote('C:\\work\\my app', true)).toBe('"C:\\work\\my app"');
|
|
213
|
+
});
|
|
214
|
+
|
|
215
|
+
it('names the file manager of each system', () => {
|
|
216
|
+
expect(WorkspaceUtil.fileManagerLabel('darwin')).toBe('revealInFinder');
|
|
217
|
+
expect(WorkspaceUtil.fileManagerLabel('win32')).toBe('revealInFileExplorer');
|
|
218
|
+
expect(WorkspaceUtil.fileManagerLabel('linux')).toBe('openContainingFolder');
|
|
219
|
+
});
|
|
191
220
|
});
|
|
@@ -205,6 +205,34 @@ export namespace WorkspaceUtil {
|
|
|
205
205
|
return !folder || path === folder || path.startsWith(`${folder}/`);
|
|
206
206
|
}
|
|
207
207
|
|
|
208
|
+
/**
|
|
209
|
+
* What of `paths` can move into `folder`: not a folder into itself or a folder inside it, not what is
|
|
210
|
+
* there already, and not what goes along with a folder that moves too.
|
|
211
|
+
*/
|
|
212
|
+
export function movable(paths: readonly string[], folder: string): string[] {
|
|
213
|
+
const unique = [...new Set(paths)].filter(path => path && !within(folder, path) && dirname(path) !== folder);
|
|
214
|
+
return unique.filter(path => !unique.some(other => other !== path && within(path, other)));
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
/** Where `path` is once `moved` went into `folder`; undefined when it did not move. */
|
|
218
|
+
export function movedTo(path: string, moved: readonly string[], folder: string): string | undefined {
|
|
219
|
+
const from = moved.find(source => within(path, source));
|
|
220
|
+
return from === undefined ? undefined : join(folder, basename(from)) + path.slice(from.length);
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
/** A path as a shell takes it as one word: quoted when it holds more than letters, digits and `_@%+=:,./-`. */
|
|
224
|
+
export function shellQuote(path: string, windows = false): string {
|
|
225
|
+
if (/^[\w@%+=:,./-]+$/.test(path)) {
|
|
226
|
+
return path;
|
|
227
|
+
}
|
|
228
|
+
return windows ? `"${path.replace(/"/g, '""')}"` : `'${path.replace(/'/g, "'\\''")}'`;
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
/** What the file manager of the system is called, by Node's `process.platform`, as VS Code names it in its menu. */
|
|
232
|
+
export function fileManagerLabel(platform: string): 'revealInFinder' | 'revealInFileExplorer' | 'openContainingFolder' {
|
|
233
|
+
return platform === 'darwin' ? 'revealInFinder' : platform === 'win32' ? 'revealInFileExplorer' : 'openContainingFolder';
|
|
234
|
+
}
|
|
235
|
+
|
|
208
236
|
/** Matches by file, in the order the files first come. */
|
|
209
237
|
export function groupMatches(matches: TextMatch[]): FileMatches[] {
|
|
210
238
|
const files = new Map<string, TextMatch[]>();
|
|
@@ -296,6 +324,43 @@ export namespace WorkspaceUtil {
|
|
|
296
324
|
return path ? `${cwd.replace(/\/+$/, '')}/${path}` : cwd;
|
|
297
325
|
}
|
|
298
326
|
|
|
327
|
+
/** The port of a page of localhost (`localhost`, `127.0.0.1`, `0.0.0.0`, `[::1]`); undefined for others. */
|
|
328
|
+
export function localPort(url: string): number | undefined {
|
|
329
|
+
try {
|
|
330
|
+
const parsed = new URL(url);
|
|
331
|
+
if (!/^https?:$/.test(parsed.protocol) || !['localhost', '127.0.0.1', '0.0.0.0', '[::1]'].includes(parsed.hostname)) {
|
|
332
|
+
return undefined;
|
|
333
|
+
}
|
|
334
|
+
return Number(parsed.port || (parsed.protocol === 'https:' ? 443 : 80));
|
|
335
|
+
} catch {
|
|
336
|
+
return undefined;
|
|
337
|
+
}
|
|
338
|
+
}
|
|
339
|
+
|
|
340
|
+
/** The URL on another port of localhost. */
|
|
341
|
+
export function withPort(url: string, port: number): string {
|
|
342
|
+
const parsed = new URL(url);
|
|
343
|
+
if (parsed.hostname === '0.0.0.0') {
|
|
344
|
+
parsed.hostname = 'localhost';
|
|
345
|
+
}
|
|
346
|
+
parsed.port = String(port);
|
|
347
|
+
return parsed.toString();
|
|
348
|
+
}
|
|
349
|
+
|
|
350
|
+
/**
|
|
351
|
+
* `url` of a page loaded at `shown` for the address `asked` (a port of another machine forwarded here),
|
|
352
|
+
* at the origin asked for; as it is when nothing was forwarded or it went to another site.
|
|
353
|
+
*/
|
|
354
|
+
export function unforward(url: string, asked: string, shown: string | undefined): string {
|
|
355
|
+
try {
|
|
356
|
+
const from = new URL(shown ?? asked).origin;
|
|
357
|
+
const to = new URL(asked).origin;
|
|
358
|
+
return from !== to && url.startsWith(`${from}/`) ? `${to}${url.slice(from.length)}` : url;
|
|
359
|
+
} catch {
|
|
360
|
+
return url;
|
|
361
|
+
}
|
|
362
|
+
}
|
|
363
|
+
|
|
299
364
|
/** What the address bar holds, as a URL: a bare host gets http, a word becomes a search. */
|
|
300
365
|
export function toUrl(input: string): string | undefined {
|
|
301
366
|
const text = input.trim();
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
import { describe, expect, it } from 'bun:test';
|
|
2
|
+
import { deflateRawSync, inflateRawSync } from 'node:zlib';
|
|
3
|
+
import { ZipUtil } from './zip';
|
|
4
|
+
|
|
5
|
+
/** Reads an archive back by its central directory, as unzip does. */
|
|
6
|
+
function read(zip: Uint8Array): Record<string, string> {
|
|
7
|
+
const view = new DataView(zip.buffer, zip.byteOffset, zip.byteLength);
|
|
8
|
+
const end = zip.length - 22;
|
|
9
|
+
expect(view.getUint32(end, true)).toBe(0x06054b50);
|
|
10
|
+
const count = view.getUint16(end + 10, true);
|
|
11
|
+
let at = view.getUint32(end + 16, true);
|
|
12
|
+
const files: Record<string, string> = {};
|
|
13
|
+
for (let i = 0; i < count; i++) {
|
|
14
|
+
expect(view.getUint32(at, true)).toBe(0x02014b50);
|
|
15
|
+
const method = view.getUint16(at + 10, true);
|
|
16
|
+
const crc = view.getUint32(at + 16, true);
|
|
17
|
+
const size = view.getUint32(at + 24, true);
|
|
18
|
+
const nameLength = view.getUint16(at + 28, true);
|
|
19
|
+
const local = view.getUint32(at + 42, true);
|
|
20
|
+
const name = new TextDecoder().decode(zip.subarray(at + 46, at + 46 + nameLength));
|
|
21
|
+
const start = local + 30 + view.getUint16(local + 26, true);
|
|
22
|
+
const stored = zip.subarray(start, start + view.getUint32(local + 18, true));
|
|
23
|
+
const data = method === 8 ? new Uint8Array(inflateRawSync(stored)) : stored;
|
|
24
|
+
expect(data.length).toBe(size);
|
|
25
|
+
expect(ZipUtil.crc32(data)).toBe(crc);
|
|
26
|
+
files[name] = new TextDecoder().decode(data);
|
|
27
|
+
at += 46 + nameLength;
|
|
28
|
+
}
|
|
29
|
+
return files;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
describe('ZipUtil', () => {
|
|
33
|
+
it('computes the CRC-32 of zip', () => {
|
|
34
|
+
expect(ZipUtil.crc32(new TextEncoder().encode('123456789'))).toBe(0xcbf43926);
|
|
35
|
+
expect(ZipUtil.crc32(new Uint8Array())).toBe(0);
|
|
36
|
+
});
|
|
37
|
+
|
|
38
|
+
it('stores files, with UTF-8 names', async () => {
|
|
39
|
+
const zip = await ZipUtil.create([
|
|
40
|
+
{ path: 'app/src/a.ts', data: new TextEncoder().encode('export const a = 1;\n') },
|
|
41
|
+
{ path: 'app/说明.md', data: new TextEncoder().encode('# 你好') },
|
|
42
|
+
{ path: 'app/empty.txt', data: new Uint8Array() },
|
|
43
|
+
]);
|
|
44
|
+
expect(read(zip)).toEqual({ 'app/src/a.ts': 'export const a = 1;\n', 'app/说明.md': '# 你好', 'app/empty.txt': '' });
|
|
45
|
+
});
|
|
46
|
+
|
|
47
|
+
it('deflates what gets smaller, and stores the rest', async () => {
|
|
48
|
+
const text = 'line of text\n'.repeat(500);
|
|
49
|
+
const deflate = async (data: Uint8Array) => new Uint8Array(deflateRawSync(data));
|
|
50
|
+
const zip = await ZipUtil.create(
|
|
51
|
+
[
|
|
52
|
+
{ path: 'big.txt', data: new TextEncoder().encode(text) },
|
|
53
|
+
{ path: 'tiny.txt', data: new TextEncoder().encode('a') },
|
|
54
|
+
],
|
|
55
|
+
deflate,
|
|
56
|
+
);
|
|
57
|
+
expect(zip.length).toBeLessThan(text.length / 4);
|
|
58
|
+
expect(read(zip)).toEqual({ 'big.txt': text, 'tiny.txt': 'a' });
|
|
59
|
+
});
|
|
60
|
+
});
|