@dooc-dev/dooc 0.0.9 → 0.0.10
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 +4 -1
- package/dist/engine/compiler/bundle-urls.js +39 -5
- package/dist/engine/compiler/download-progress.d.ts +9 -0
- package/dist/engine/compiler/download-progress.js +12 -0
- package/dist/engine/compiler/public-file.d.ts +1 -1
- package/dist/engine/compiler/public-file.js +9 -1
- package/dist/engine/compiler/textfile-remote.js +19 -1
- package/dist/server/cli.js +87 -9
- package/dist/server/editor-tools.d.ts +36 -1
- package/dist/server/editor-tools.js +6 -1
- package/dist/server/extensions.js +5 -0
- package/dist/server/git-workspace.d.ts +8 -0
- package/dist/server/git-workspace.js +375 -0
- package/dist/server/github-archive.d.ts +1 -0
- package/dist/server/github-archive.js +92 -0
- package/dist/server/languages.js +2 -1
- package/dist/server/operation-log.d.ts +4 -0
- package/dist/server/operation-log.js +45 -0
- package/dist/server/self.js +4 -47
- package/dist/server/serve.js +19 -11
- package/dist/server/static-client.js +2 -1
- package/dist/server/terminal.d.ts +22 -0
- package/dist/server/terminal.js +131 -0
- package/dist/server/workspace-server.js +7 -2
- package/dist/server/workspace-trust.d.ts +2 -0
- package/dist/server/workspace-trust.js +2 -0
- package/dist/workspace/editor-tools.d.ts +3 -3
- package/dist/workspace/editor-tools.js +25 -16
- package/dist/workspace-worker.global.js +8 -8
- package/package.json +2 -1
|
@@ -0,0 +1,375 @@
|
|
|
1
|
+
import { spawn } from "node:child_process";
|
|
2
|
+
import { createHash } from "node:crypto";
|
|
3
|
+
import { existsSync, lstatSync, mkdirSync, mkdtempSync, realpathSync, renameSync, rmSync, statSync, } from "node:fs";
|
|
4
|
+
import { devNull, homedir, tmpdir } from "node:os";
|
|
5
|
+
import { basename, dirname, isAbsolute, join, relative, sep } from "node:path";
|
|
6
|
+
import { stripVTControlCharacters } from "node:util";
|
|
7
|
+
import { reportDownloadProgress } from "../engine/compiler/download-progress.js";
|
|
8
|
+
import { isManifestFile, MANIFEST_FILE } from "../engine/core/content-metadata.js";
|
|
9
|
+
const invalidSource = () => new Error("Use an HTTPS, HTTP, or SSH Git repository URL without passwords or URL parameters.");
|
|
10
|
+
const parseSource = (source) => {
|
|
11
|
+
if (!source || source.length > 4096 || /\p{Cc}|\p{Cf}|\s/gu.test(source))
|
|
12
|
+
throw invalidSource();
|
|
13
|
+
const scp = /^([a-z\d][a-z\d._-]*)@([a-z\d][a-z\d.-]*):([^?#\\]+)$/i.exec(source);
|
|
14
|
+
let url;
|
|
15
|
+
let path;
|
|
16
|
+
if (scp) {
|
|
17
|
+
if (!scp[3] || scp[3].startsWith("-") || scp[3].split("/").some((part) => part === ".."))
|
|
18
|
+
throw invalidSource();
|
|
19
|
+
url = `${scp[1]}@${scp[2]?.toLowerCase()}:${scp[3].replace(/\/$/, "")}`;
|
|
20
|
+
path = scp[3];
|
|
21
|
+
}
|
|
22
|
+
else {
|
|
23
|
+
let parsed;
|
|
24
|
+
try {
|
|
25
|
+
parsed = new URL(source);
|
|
26
|
+
}
|
|
27
|
+
catch {
|
|
28
|
+
throw invalidSource();
|
|
29
|
+
}
|
|
30
|
+
if (!["https:", "http:", "ssh:"].includes(parsed.protocol) ||
|
|
31
|
+
!parsed.hostname ||
|
|
32
|
+
parsed.hostname.startsWith("-") ||
|
|
33
|
+
parsed.password ||
|
|
34
|
+
parsed.search ||
|
|
35
|
+
parsed.hash ||
|
|
36
|
+
source.includes("\\") ||
|
|
37
|
+
(parsed.username &&
|
|
38
|
+
(parsed.protocol !== "ssh:" || !/^[a-z\d][a-z\d._-]*$/i.test(parsed.username))) ||
|
|
39
|
+
!parsed.pathname.replaceAll("/", ""))
|
|
40
|
+
throw invalidSource();
|
|
41
|
+
parsed.pathname = parsed.pathname.replace(/\/$/, "");
|
|
42
|
+
url = parsed.href;
|
|
43
|
+
path = parsed.pathname;
|
|
44
|
+
}
|
|
45
|
+
const name = basename(path)
|
|
46
|
+
.replace(/\.git$/i, "")
|
|
47
|
+
.replace(/[^a-z\d._-]/gi, "_")
|
|
48
|
+
.replace(/[. ]+$/, "");
|
|
49
|
+
return { url, name: name && name !== "." && !name.startsWith("-") ? name : "repository" };
|
|
50
|
+
};
|
|
51
|
+
const selectedPath = (path = "") => {
|
|
52
|
+
if (path.length > 4096 ||
|
|
53
|
+
/[\\:]|\p{Cc}|\p{Cf}/u.test(path) ||
|
|
54
|
+
isAbsolute(path) ||
|
|
55
|
+
path.split("/").some((part) => part === ".." || part.toLowerCase() === ".git"))
|
|
56
|
+
throw new Error("Choose a relative folder or manifest path inside the Git repository");
|
|
57
|
+
return path;
|
|
58
|
+
};
|
|
59
|
+
const manifestIn = (repository, selected) => {
|
|
60
|
+
const root = realpathSync(repository);
|
|
61
|
+
let manifest = join(root, selected);
|
|
62
|
+
if (statSync(manifest, { throwIfNoEntry: false })?.isDirectory())
|
|
63
|
+
manifest = join(manifest, MANIFEST_FILE);
|
|
64
|
+
if (!isManifestFile(basename(manifest)) || !existsSync(manifest))
|
|
65
|
+
throw new Error(`No dooc manifest at ${selected || "."}. Choose its folder or file.`);
|
|
66
|
+
manifest = realpathSync(manifest);
|
|
67
|
+
const path = relative(root, manifest);
|
|
68
|
+
if (path === ".." ||
|
|
69
|
+
path.startsWith(`..${sep}`) ||
|
|
70
|
+
isAbsolute(path) ||
|
|
71
|
+
!statSync(manifest).isFile())
|
|
72
|
+
throw new Error("The selected manifest must be a file inside the Git repository");
|
|
73
|
+
return manifest;
|
|
74
|
+
};
|
|
75
|
+
const cleanMessage = (message) => stripVTControlCharacters(message)
|
|
76
|
+
.replace(/\p{Cc}|\p{Cf}/gu, " ")
|
|
77
|
+
.replace(/\b[a-z][a-z\d+.-]*:\/\/[^\s<>"'`]+/giu, (value) => {
|
|
78
|
+
try {
|
|
79
|
+
const url = new URL(value);
|
|
80
|
+
url.username = url.password = url.search = url.hash = "";
|
|
81
|
+
return url.href;
|
|
82
|
+
}
|
|
83
|
+
catch {
|
|
84
|
+
return "[invalid URL]";
|
|
85
|
+
}
|
|
86
|
+
})
|
|
87
|
+
.trim()
|
|
88
|
+
.slice(0, 2000);
|
|
89
|
+
export const prepareGitWorkspace = async (source, mode, options = {}) => {
|
|
90
|
+
const remote = parseSource(source);
|
|
91
|
+
const selected = selectedPath(options.path);
|
|
92
|
+
const dataHome = process.env.XDG_DATA_HOME;
|
|
93
|
+
const directory = join(dataHome && isAbsolute(dataHome) ? dataHome : join(homedir(), ".local/share"), "dooc/workspaces");
|
|
94
|
+
const hash = createHash("sha256").update(remote.url).digest("hex").slice(0, 24);
|
|
95
|
+
const saved = join(directory, `git-${hash}`);
|
|
96
|
+
const result = (container, reused) => {
|
|
97
|
+
const repository = join(container, remote.name);
|
|
98
|
+
if (!lstatSync(container).isDirectory() ||
|
|
99
|
+
!existsSync(repository) ||
|
|
100
|
+
!lstatSync(repository).isDirectory() ||
|
|
101
|
+
!existsSync(join(repository, ".git")) ||
|
|
102
|
+
!lstatSync(join(repository, ".git")).isDirectory())
|
|
103
|
+
throw new Error("Saved workspace is missing its Git repository. Restore it to reopen your edits.");
|
|
104
|
+
const manifest = manifestIn(repository, selected);
|
|
105
|
+
return {
|
|
106
|
+
root: dirname(manifest),
|
|
107
|
+
manifest,
|
|
108
|
+
reused,
|
|
109
|
+
dispose: () => {
|
|
110
|
+
if (mode === "view")
|
|
111
|
+
rmSync(container, { recursive: true, force: true });
|
|
112
|
+
},
|
|
113
|
+
};
|
|
114
|
+
};
|
|
115
|
+
let staging;
|
|
116
|
+
let child;
|
|
117
|
+
const stop = () => {
|
|
118
|
+
if (!child?.pid)
|
|
119
|
+
return;
|
|
120
|
+
try {
|
|
121
|
+
if (process.platform !== "win32")
|
|
122
|
+
process.kill(-child.pid, "SIGKILL");
|
|
123
|
+
else
|
|
124
|
+
child.kill("SIGKILL");
|
|
125
|
+
}
|
|
126
|
+
catch {
|
|
127
|
+
// The child may have exited while its close event is still queued.
|
|
128
|
+
}
|
|
129
|
+
};
|
|
130
|
+
const cleanup = () => {
|
|
131
|
+
stop();
|
|
132
|
+
if (staging)
|
|
133
|
+
rmSync(staging, { recursive: true, force: true });
|
|
134
|
+
};
|
|
135
|
+
const interrupt = () => {
|
|
136
|
+
cleanup();
|
|
137
|
+
process.exit(130);
|
|
138
|
+
};
|
|
139
|
+
const terminate = () => {
|
|
140
|
+
cleanup();
|
|
141
|
+
process.exit(143);
|
|
142
|
+
};
|
|
143
|
+
const run = (args, network = false, globalConfig = network) => new Promise((resolve, reject) => {
|
|
144
|
+
const env = { ...process.env };
|
|
145
|
+
// Inherited repository selectors must never redirect operations into the caller's repo.
|
|
146
|
+
for (const key of Object.keys(env))
|
|
147
|
+
if (key.startsWith("GIT_") &&
|
|
148
|
+
![
|
|
149
|
+
"GIT_CONFIG_GLOBAL",
|
|
150
|
+
"GIT_CONFIG_SYSTEM",
|
|
151
|
+
"GIT_CONFIG_NOSYSTEM",
|
|
152
|
+
"GIT_SSH",
|
|
153
|
+
"GIT_SSH_COMMAND",
|
|
154
|
+
"GIT_SSH_VARIANT",
|
|
155
|
+
"GIT_ASKPASS",
|
|
156
|
+
].includes(key))
|
|
157
|
+
delete env[key];
|
|
158
|
+
Object.assign(env, {
|
|
159
|
+
GIT_TERMINAL_PROMPT: "0",
|
|
160
|
+
GIT_ALLOW_PROTOCOL: "https:http:ssh",
|
|
161
|
+
GIT_OPTIONAL_LOCKS: "0",
|
|
162
|
+
LC_ALL: "C",
|
|
163
|
+
...(globalConfig ? {} : { GIT_CONFIG_NOSYSTEM: "1", GIT_CONFIG_GLOBAL: devNull }),
|
|
164
|
+
});
|
|
165
|
+
child = spawn("git", [
|
|
166
|
+
"-c",
|
|
167
|
+
`core.hooksPath=${devNull}`,
|
|
168
|
+
"-c",
|
|
169
|
+
"core.fsmonitor=false",
|
|
170
|
+
"-c",
|
|
171
|
+
"submodule.recurse=false",
|
|
172
|
+
...args,
|
|
173
|
+
], {
|
|
174
|
+
env,
|
|
175
|
+
stdio: ["ignore", "pipe", "pipe"],
|
|
176
|
+
windowsHide: true,
|
|
177
|
+
detached: process.platform !== "win32",
|
|
178
|
+
});
|
|
179
|
+
const timeout = setTimeout(stop, 180_000);
|
|
180
|
+
let stdout = "";
|
|
181
|
+
let stderr = "";
|
|
182
|
+
let pending = "";
|
|
183
|
+
child.stdout?.on("data", (chunk) => {
|
|
184
|
+
stdout += chunk.toString();
|
|
185
|
+
if (stdout.length > 8 * 1024 * 1024)
|
|
186
|
+
stop();
|
|
187
|
+
});
|
|
188
|
+
child.stderr?.on("data", (chunk) => {
|
|
189
|
+
const text = chunk.toString();
|
|
190
|
+
stderr = (stderr + text).slice(-8192);
|
|
191
|
+
if (!network)
|
|
192
|
+
return;
|
|
193
|
+
const lines = (pending + text).split(/[\r\n]/);
|
|
194
|
+
pending = lines.pop()?.slice(-2000) ?? "";
|
|
195
|
+
for (const line of lines) {
|
|
196
|
+
const detail = cleanMessage(line);
|
|
197
|
+
if (detail)
|
|
198
|
+
reportDownloadProgress({
|
|
199
|
+
url: remote.url,
|
|
200
|
+
state: "progress",
|
|
201
|
+
received: 0,
|
|
202
|
+
detail,
|
|
203
|
+
});
|
|
204
|
+
}
|
|
205
|
+
});
|
|
206
|
+
child.once("error", (error) => {
|
|
207
|
+
clearTimeout(timeout);
|
|
208
|
+
child = undefined;
|
|
209
|
+
reject(new Error(error.code === "ENOENT"
|
|
210
|
+
? "Install Git to open a remote repository"
|
|
211
|
+
: cleanMessage(error.message)));
|
|
212
|
+
});
|
|
213
|
+
child.once("close", (code) => {
|
|
214
|
+
clearTimeout(timeout);
|
|
215
|
+
child = undefined;
|
|
216
|
+
if (code === 0)
|
|
217
|
+
resolve(stdout);
|
|
218
|
+
else
|
|
219
|
+
reject(new Error(cleanMessage(stderr) || "Git command failed or timed out"));
|
|
220
|
+
});
|
|
221
|
+
});
|
|
222
|
+
const protect = async (repository) => {
|
|
223
|
+
const config = await run(["-C", repository, "config", "--null", "--list"], false, true);
|
|
224
|
+
const local = new Map((await run(["-C", repository, "config", "--local", "--null", "--list"]))
|
|
225
|
+
.split("\0")
|
|
226
|
+
.filter(Boolean)
|
|
227
|
+
.map((entry) => [
|
|
228
|
+
entry.slice(0, entry.indexOf("\n")),
|
|
229
|
+
entry.slice(entry.indexOf("\n") + 1),
|
|
230
|
+
]));
|
|
231
|
+
const drivers = new Set();
|
|
232
|
+
for (const entry of config.split("\0")) {
|
|
233
|
+
const key = entry.slice(0, entry.indexOf("\n"));
|
|
234
|
+
const match = /^filter\.(.+)\.(?:clean|smudge|process|required)$/i.exec(key);
|
|
235
|
+
if (match?.[1])
|
|
236
|
+
drivers.add(match[1]);
|
|
237
|
+
}
|
|
238
|
+
const settings = [
|
|
239
|
+
["core.hookspath", devNull],
|
|
240
|
+
["core.fsmonitor", "false"],
|
|
241
|
+
...[...drivers].flatMap((driver) => [
|
|
242
|
+
[`filter.${driver}.clean`, ""],
|
|
243
|
+
[`filter.${driver}.smudge`, ""],
|
|
244
|
+
[`filter.${driver}.process`, ""],
|
|
245
|
+
[`filter.${driver}.required`, "false"],
|
|
246
|
+
]),
|
|
247
|
+
];
|
|
248
|
+
for (const [key, value] of settings)
|
|
249
|
+
if (local.get(key) !== value)
|
|
250
|
+
await run(["-C", repository, "config", "--local", "--replace-all", key, value]);
|
|
251
|
+
};
|
|
252
|
+
if (mode === "edit" && existsSync(saved)) {
|
|
253
|
+
const workspace = result(saved, true);
|
|
254
|
+
await protect(join(saved, remote.name));
|
|
255
|
+
return workspace;
|
|
256
|
+
}
|
|
257
|
+
if (mode === "edit")
|
|
258
|
+
mkdirSync(directory, { recursive: true });
|
|
259
|
+
staging = mkdtempSync(join(mode === "edit" ? directory : tmpdir(), "dooc-git-"));
|
|
260
|
+
process.once("exit", cleanup);
|
|
261
|
+
process.once("SIGINT", interrupt);
|
|
262
|
+
process.once("SIGTERM", terminate);
|
|
263
|
+
reportDownloadProgress({
|
|
264
|
+
url: remote.url,
|
|
265
|
+
state: "start",
|
|
266
|
+
received: 0,
|
|
267
|
+
detail: "Cloning repository",
|
|
268
|
+
});
|
|
269
|
+
try {
|
|
270
|
+
const repository = join(staging, remote.name);
|
|
271
|
+
await run([
|
|
272
|
+
"clone",
|
|
273
|
+
"--progress",
|
|
274
|
+
"--no-checkout",
|
|
275
|
+
"--no-recurse-submodules",
|
|
276
|
+
"--template=",
|
|
277
|
+
"--origin=origin",
|
|
278
|
+
"--",
|
|
279
|
+
remote.url,
|
|
280
|
+
repository,
|
|
281
|
+
], true);
|
|
282
|
+
await protect(repository);
|
|
283
|
+
// Keep native credentials for cloning, but never execute global checkout filters.
|
|
284
|
+
await run(["-C", repository, "checkout", "--force"]);
|
|
285
|
+
const refs = await run([
|
|
286
|
+
"-C",
|
|
287
|
+
repository,
|
|
288
|
+
"for-each-ref",
|
|
289
|
+
"--format=%(refname:strip=3)%00%(symref)",
|
|
290
|
+
"refs/remotes/origin",
|
|
291
|
+
]);
|
|
292
|
+
const current = (await run(["-C", repository, "symbolic-ref", "--short", "HEAD"])).trim();
|
|
293
|
+
for (const line of refs.trimEnd().split("\n")) {
|
|
294
|
+
const [branch, symbolic] = line.split("\0");
|
|
295
|
+
if (branch && !symbolic && branch !== current)
|
|
296
|
+
await run([
|
|
297
|
+
"-C",
|
|
298
|
+
repository,
|
|
299
|
+
"branch",
|
|
300
|
+
"--track",
|
|
301
|
+
"--",
|
|
302
|
+
branch,
|
|
303
|
+
`refs/remotes/origin/${branch}`,
|
|
304
|
+
]);
|
|
305
|
+
}
|
|
306
|
+
manifestIn(repository, selected);
|
|
307
|
+
if (mode === "view") {
|
|
308
|
+
const workspace = result(staging, false);
|
|
309
|
+
staging = undefined;
|
|
310
|
+
reportDownloadProgress({
|
|
311
|
+
url: remote.url,
|
|
312
|
+
state: "complete",
|
|
313
|
+
received: 0,
|
|
314
|
+
detail: "Clone ready",
|
|
315
|
+
});
|
|
316
|
+
return workspace;
|
|
317
|
+
}
|
|
318
|
+
if (existsSync(saved)) {
|
|
319
|
+
cleanup();
|
|
320
|
+
staging = undefined;
|
|
321
|
+
const workspace = result(saved, true);
|
|
322
|
+
await protect(join(saved, remote.name));
|
|
323
|
+
reportDownloadProgress({
|
|
324
|
+
url: remote.url,
|
|
325
|
+
state: "complete",
|
|
326
|
+
received: 0,
|
|
327
|
+
detail: "Existing clone ready",
|
|
328
|
+
});
|
|
329
|
+
return workspace;
|
|
330
|
+
}
|
|
331
|
+
try {
|
|
332
|
+
renameSync(staging, saved);
|
|
333
|
+
}
|
|
334
|
+
catch (error) {
|
|
335
|
+
if (!existsSync(saved))
|
|
336
|
+
throw error;
|
|
337
|
+
cleanup();
|
|
338
|
+
staging = undefined;
|
|
339
|
+
const workspace = result(saved, true);
|
|
340
|
+
await protect(join(saved, remote.name));
|
|
341
|
+
reportDownloadProgress({
|
|
342
|
+
url: remote.url,
|
|
343
|
+
state: "complete",
|
|
344
|
+
received: 0,
|
|
345
|
+
detail: "Existing clone ready",
|
|
346
|
+
});
|
|
347
|
+
return workspace;
|
|
348
|
+
}
|
|
349
|
+
staging = undefined;
|
|
350
|
+
await protect(join(saved, remote.name));
|
|
351
|
+
const workspace = result(saved, false);
|
|
352
|
+
reportDownloadProgress({
|
|
353
|
+
url: remote.url,
|
|
354
|
+
state: "complete",
|
|
355
|
+
received: 0,
|
|
356
|
+
detail: "Clone ready",
|
|
357
|
+
});
|
|
358
|
+
return workspace;
|
|
359
|
+
}
|
|
360
|
+
catch (error) {
|
|
361
|
+
cleanup();
|
|
362
|
+
reportDownloadProgress({
|
|
363
|
+
url: remote.url,
|
|
364
|
+
state: "error",
|
|
365
|
+
received: 0,
|
|
366
|
+
detail: "Clone failed",
|
|
367
|
+
});
|
|
368
|
+
throw new Error(`Failed to open Git workspace: ${error instanceof Error ? error.message : String(error)}`, { cause: error });
|
|
369
|
+
}
|
|
370
|
+
finally {
|
|
371
|
+
process.removeListener("exit", cleanup);
|
|
372
|
+
process.removeListener("SIGINT", interrupt);
|
|
373
|
+
process.removeListener("SIGTERM", terminate);
|
|
374
|
+
}
|
|
375
|
+
};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export declare const downloadGitHubArchive: (url: string, folder: string, label?: "workspace" | "documentation") => Promise<Record<string, Uint8Array>>;
|
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
import { unzipSync } from "fflate";
|
|
2
|
+
import { reportDownloadProgress } from "../engine/compiler/download-progress.js";
|
|
3
|
+
const safePath = (path) => !/[\\:]/.test(path) &&
|
|
4
|
+
![...path].some((char) => char.charCodeAt(0) < 32 || char.charCodeAt(0) === 127) &&
|
|
5
|
+
path.split("/").every((part) => part && part !== "." && part !== ".." && !/[. ]$/.test(part));
|
|
6
|
+
export const downloadGitHubArchive = async (url, folder, label = "workspace") => {
|
|
7
|
+
const title = label[0]?.toUpperCase() + label.slice(1);
|
|
8
|
+
let received = 0;
|
|
9
|
+
let total;
|
|
10
|
+
const chunks = [];
|
|
11
|
+
reportDownloadProgress({ url, state: "start", received });
|
|
12
|
+
try {
|
|
13
|
+
const response = await fetch(url, { signal: AbortSignal.timeout(60_000) });
|
|
14
|
+
if (!response.ok)
|
|
15
|
+
throw new Error(`HTTP ${response.status} ${response.statusText}`);
|
|
16
|
+
if (!response.body)
|
|
17
|
+
throw new Error("Empty archive response");
|
|
18
|
+
const length = response.headers.get("content-length");
|
|
19
|
+
if (length && /^\d+$/.test(length) && Number.isSafeInteger(Number(length)))
|
|
20
|
+
total = Number(length);
|
|
21
|
+
await response.body.pipeTo(new WritableStream({
|
|
22
|
+
write(chunk) {
|
|
23
|
+
received += chunk.length;
|
|
24
|
+
if (received > 128 * 1024 * 1024)
|
|
25
|
+
throw new Error(`${title} archive exceeds 128 MiB`);
|
|
26
|
+
chunks.push(chunk);
|
|
27
|
+
reportDownloadProgress({
|
|
28
|
+
url,
|
|
29
|
+
state: "progress",
|
|
30
|
+
received,
|
|
31
|
+
...(total === undefined ? {} : { total }),
|
|
32
|
+
});
|
|
33
|
+
},
|
|
34
|
+
}));
|
|
35
|
+
reportDownloadProgress({
|
|
36
|
+
url,
|
|
37
|
+
state: "complete",
|
|
38
|
+
received,
|
|
39
|
+
...(total === undefined ? {} : { total }),
|
|
40
|
+
});
|
|
41
|
+
}
|
|
42
|
+
catch (error) {
|
|
43
|
+
reportDownloadProgress({
|
|
44
|
+
url,
|
|
45
|
+
state: "error",
|
|
46
|
+
received,
|
|
47
|
+
...(total === undefined ? {} : { total }),
|
|
48
|
+
});
|
|
49
|
+
throw error;
|
|
50
|
+
}
|
|
51
|
+
const paths = new Set();
|
|
52
|
+
let archiveRoot;
|
|
53
|
+
let extracted = 0;
|
|
54
|
+
const selected = (name) => {
|
|
55
|
+
const split = name.indexOf("/");
|
|
56
|
+
if (split <= 0 || name.endsWith("/"))
|
|
57
|
+
return;
|
|
58
|
+
const root = name.slice(0, split);
|
|
59
|
+
const path = name.slice(split + 1);
|
|
60
|
+
if (folder && !path.startsWith(`${folder}/`))
|
|
61
|
+
return;
|
|
62
|
+
if (!safePath(root) || (archiveRoot !== undefined && archiveRoot !== root))
|
|
63
|
+
throw new Error(`Invalid ${label} archive root`);
|
|
64
|
+
archiveRoot = root;
|
|
65
|
+
return folder ? path.slice(folder.length + 1) : path;
|
|
66
|
+
};
|
|
67
|
+
const files = unzipSync(Buffer.concat(chunks), {
|
|
68
|
+
filter: ({ name, size, originalSize, compression }) => {
|
|
69
|
+
const path = selected(name);
|
|
70
|
+
if (path === undefined)
|
|
71
|
+
return false;
|
|
72
|
+
if (compression === 0 && size !== originalSize)
|
|
73
|
+
throw new Error(`Invalid ${label} file size`);
|
|
74
|
+
if (!safePath(path))
|
|
75
|
+
throw new Error(`Invalid ${label} path`);
|
|
76
|
+
if (path.split("/").some((part) => part.startsWith(".")))
|
|
77
|
+
return false;
|
|
78
|
+
// Language configuration is executable and must not run from downloaded workspaces.
|
|
79
|
+
if (path.toLowerCase() === "docs.config.mjs")
|
|
80
|
+
return false;
|
|
81
|
+
const key = path.normalize("NFC").toLowerCase();
|
|
82
|
+
if (paths.has(key))
|
|
83
|
+
throw new Error(`Duplicate ${label} path`);
|
|
84
|
+
paths.add(key);
|
|
85
|
+
extracted += originalSize;
|
|
86
|
+
if (paths.size > 4096 || extracted > 256 * 1024 * 1024)
|
|
87
|
+
throw new Error(`${title} exceeds 4096 files or 256 MiB`);
|
|
88
|
+
return true;
|
|
89
|
+
},
|
|
90
|
+
});
|
|
91
|
+
return Object.fromEntries(Object.entries(files).map(([name, data]) => [selected(name), data]));
|
|
92
|
+
};
|
package/dist/server/languages.js
CHANGED
|
@@ -3,6 +3,7 @@
|
|
|
3
3
|
import { loadCodeLanguages } from "../engine/compiler/code-languages.js";
|
|
4
4
|
import { loadDocsConfig } from "../engine/compiler/config.js";
|
|
5
5
|
import { ja } from "../engine/core/languages/ja.js";
|
|
6
|
+
import { allowsWorkspaceCode } from "./workspace-trust.js";
|
|
6
7
|
export const BUILTIN_LANGUAGES = [
|
|
7
8
|
// textlint is heavy; load it on the first lint request.
|
|
8
9
|
{ ...ja, lint: async (body) => (await import("./ja-lint.js")).lintJa(body) },
|
|
@@ -12,7 +13,7 @@ export const DEFAULT_SITE_LANGUAGES = {
|
|
|
12
13
|
};
|
|
13
14
|
/** docs.config.mjs + built-ins (configured adapters first, so they override a built-in code). */
|
|
14
15
|
export const loadSiteLanguages = async (root) => {
|
|
15
|
-
const config = await loadDocsConfig(root);
|
|
16
|
+
const config = allowsWorkspaceCode() ? await loadDocsConfig(root) : { languages: [] };
|
|
16
17
|
return {
|
|
17
18
|
...(await loadCodeLanguages(root)),
|
|
18
19
|
languages: [...config.languages, ...BUILTIN_LANGUAGES],
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
import type { WorkspaceOps } from "../workspace/server.js";
|
|
2
|
+
export declare const logHttpOperation: (method: string, url: string, status: number, body?: unknown) => void;
|
|
3
|
+
/** Log actions without printing document bodies, credentials, or commit messages. */
|
|
4
|
+
export declare const loggedWorkspaceOps: <Session>(ops: WorkspaceOps<Session>) => WorkspaceOps<Session>;
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
import { terminal } from "./terminal.js";
|
|
2
|
+
export const logHttpOperation = (method, url, status, body) => {
|
|
3
|
+
const path = url.split(/[?#]/)[0] ?? "/";
|
|
4
|
+
if (method !== "POST" ||
|
|
5
|
+
!path.startsWith("/api/") ||
|
|
6
|
+
["/api/render", "/api/lint", "/api/code-tool"].includes(path))
|
|
7
|
+
return;
|
|
8
|
+
if (path === "/api/textfile" && typeof body === "string") {
|
|
9
|
+
try {
|
|
10
|
+
if (["read", "preview", "validate"].includes(JSON.parse(body)?.action))
|
|
11
|
+
return;
|
|
12
|
+
}
|
|
13
|
+
catch {
|
|
14
|
+
// Invalid requests still report their HTTP status.
|
|
15
|
+
}
|
|
16
|
+
}
|
|
17
|
+
terminal.operation(`${method} ${path}`, `HTTP ${status}`);
|
|
18
|
+
};
|
|
19
|
+
/** Log actions without printing document bodies, credentials, or commit messages. */
|
|
20
|
+
export const loggedWorkspaceOps = (ops) => Object.fromEntries(Object.entries(ops).map(([name, operation]) => [
|
|
21
|
+
name,
|
|
22
|
+
async (input, session) => {
|
|
23
|
+
const action = typeof input.action === "string" ? input.action : "";
|
|
24
|
+
const visible = ["files", "git", "history", "workspaces"].includes(name) &&
|
|
25
|
+
!["read", "list", "complete", "diff", "branches", "contribute"].includes(action);
|
|
26
|
+
try {
|
|
27
|
+
const result = await operation(input, session);
|
|
28
|
+
if (name === "http" && result && typeof result === "object") {
|
|
29
|
+
const status = result.status;
|
|
30
|
+
if (typeof status === "number")
|
|
31
|
+
logHttpOperation(String(input.method), String(input.url), status, input.body);
|
|
32
|
+
}
|
|
33
|
+
else if (visible) {
|
|
34
|
+
const detail = input.file ?? input.branch;
|
|
35
|
+
terminal.operation(`${name} ${action}`, typeof detail === "string" ? detail : undefined);
|
|
36
|
+
}
|
|
37
|
+
return result;
|
|
38
|
+
}
|
|
39
|
+
catch (error) {
|
|
40
|
+
if (visible || name === "http")
|
|
41
|
+
terminal.warn(`${name} operation failed`);
|
|
42
|
+
throw error;
|
|
43
|
+
}
|
|
44
|
+
},
|
|
45
|
+
]));
|
package/dist/server/self.js
CHANGED
|
@@ -3,8 +3,8 @@ import { existsSync, mkdirSync, mkdtempSync, realpathSync, rmSync, writeFileSync
|
|
|
3
3
|
import { tmpdir } from "node:os";
|
|
4
4
|
import { dirname, join } from "node:path";
|
|
5
5
|
import { fileURLToPath } from "node:url";
|
|
6
|
-
import { unzipSync } from "fflate";
|
|
7
6
|
import { prebuilt, readInstaller, standalone } from "./assets.js";
|
|
7
|
+
import { downloadGitHubArchive } from "./github-archive.js";
|
|
8
8
|
export const selfUpdate = () => {
|
|
9
9
|
if (!standalone) {
|
|
10
10
|
const hint = "Update with your package manager (npm: npm install -g @dooc-dev/dooc@latest).";
|
|
@@ -37,55 +37,12 @@ export const prepareSelfDocs = async () => {
|
|
|
37
37
|
rmSync(root, { recursive: true, force: true });
|
|
38
38
|
};
|
|
39
39
|
try {
|
|
40
|
-
const
|
|
41
|
-
|
|
42
|
-
});
|
|
43
|
-
if (!response.ok)
|
|
44
|
-
throw new Error(`HTTP ${response.status} ${response.statusText}`);
|
|
45
|
-
if (!response.body)
|
|
46
|
-
throw new Error("Empty archive response");
|
|
47
|
-
const chunks = [];
|
|
48
|
-
let downloaded = 0;
|
|
49
|
-
await response.body.pipeTo(new WritableStream({
|
|
50
|
-
write(chunk) {
|
|
51
|
-
downloaded += chunk.length;
|
|
52
|
-
if (downloaded > 128 * 1024 * 1024)
|
|
53
|
-
throw new Error("Documentation archive exceeds 128 MiB");
|
|
54
|
-
chunks.push(chunk);
|
|
55
|
-
},
|
|
56
|
-
}));
|
|
57
|
-
const prefix = "dooc-main/dooc-docs/";
|
|
58
|
-
const paths = new Set();
|
|
59
|
-
let extracted = 0;
|
|
60
|
-
const files = unzipSync(Buffer.concat(chunks), {
|
|
61
|
-
filter: ({ name, size, originalSize, compression }) => {
|
|
62
|
-
if (!name.startsWith(prefix) || name.endsWith("/"))
|
|
63
|
-
return false;
|
|
64
|
-
if (compression === 0 && size !== originalSize)
|
|
65
|
-
throw new Error("Invalid documentation file size");
|
|
66
|
-
const path = name.slice(prefix.length);
|
|
67
|
-
const parts = path.split("/");
|
|
68
|
-
if (/[\\:]/.test(path) ||
|
|
69
|
-
[...path].some((char) => char.charCodeAt(0) < 32 || char.charCodeAt(0) === 127) ||
|
|
70
|
-
parts.some((part) => !part || part === "." || part === ".." || /[. ]$/.test(part)))
|
|
71
|
-
throw new Error("Invalid documentation path");
|
|
72
|
-
if (parts.some((part) => part.startsWith(".")))
|
|
73
|
-
return false;
|
|
74
|
-
const key = path.normalize("NFC").toLowerCase();
|
|
75
|
-
if (paths.has(key))
|
|
76
|
-
throw new Error("Duplicate documentation path");
|
|
77
|
-
paths.add(key);
|
|
78
|
-
extracted += originalSize;
|
|
79
|
-
if (paths.size > 4096 || extracted > 256 * 1024 * 1024)
|
|
80
|
-
throw new Error("Documentation exceeds 4096 files or 256 MiB");
|
|
81
|
-
return true;
|
|
82
|
-
},
|
|
83
|
-
});
|
|
84
|
-
if (!files[`${prefix}dooc.yaml`]?.length)
|
|
40
|
+
const files = await downloadGitHubArchive("https://codeload.github.com/dooc-dev/dooc/zip/refs/heads/main", "dooc-docs", "documentation");
|
|
41
|
+
if (!files["dooc.yaml"]?.length)
|
|
85
42
|
throw new Error("GitHub main does not contain dooc-docs/dooc.yaml");
|
|
86
43
|
root = mkdtempSync(join(tmpdir(), "dooc-docs-"));
|
|
87
44
|
for (const [name, data] of Object.entries(files)) {
|
|
88
|
-
const path = join(root, name
|
|
45
|
+
const path = join(root, name);
|
|
89
46
|
mkdirSync(dirname(path), { recursive: true });
|
|
90
47
|
writeFileSync(path, data, { flag: "wx" });
|
|
91
48
|
}
|