@dooc-dev/dooc 0.0.8 → 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.
@@ -21,16 +21,18 @@ import { WORKSPACE_PATH } from "../workspace/protocol.js";
21
21
  import { createWorkspaceServer } from "../workspace/server.js";
22
22
  import { readViewerAsset, prebuilt as usePrebuiltAssets } from "./assets.js";
23
23
  import { isLocalHost, isLocalToolRequest, runCodeTool, validateCodeTools, validateTextfileCode, } from "./editor-tools.js";
24
- import { createExtensionManager, EXTENSIONS_DIR } from "./extensions.js";
24
+ import { createExtensionManager } from "./extensions.js";
25
25
  import { fontCss, readFont } from "./fonts.js";
26
26
  import { createGitHandler, validateGitOrigin } from "./git.js";
27
27
  import { gitBaseBody, gitBaseText, setSubformatChanges } from "./git-diff.js";
28
28
  import { workspaceHistory } from "./history.js";
29
29
  import { watchProject } from "./hmr.js";
30
30
  import { loadSiteLanguages } from "./languages.js";
31
+ import { loggedWorkspaceOps, logHttpOperation } from "./operation-log.js";
31
32
  import { loadViewerPlugins } from "./plugin-config.js";
32
33
  import { createLocalPluginStorage } from "./plugins/local-storage.js";
33
34
  import { createPluginHandler } from "./plugins.js";
35
+ import { terminal } from "./terminal.js";
34
36
  import { readWorkspaceSource, sourceFileBase } from "./workspace.js";
35
37
  import { nodeWorkspaceOperations } from "./workspace-server.js";
36
38
  export { assembleDoc };
@@ -173,7 +175,7 @@ export const startServer = async (mode, port = 5179, pluginModule, startup) => {
173
175
  delete editOps.git;
174
176
  // The boot id changes on every process start; it is how an open page notices a restart.
175
177
  // A preview only listens for changes, so it gets no operations.
176
- const workspaceServer = createWorkspaceServer(mode === "edit" ? editOps : {}, {
178
+ const workspaceServer = createWorkspaceServer(mode === "edit" ? loggedWorkspaceOps(editOps) : {}, {
177
179
  boot: `${process.pid}-${Date.now()}`,
178
180
  ...(sharedBranch === undefined ? {} : { shared: true }),
179
181
  });
@@ -254,7 +256,7 @@ export const startServer = async (mode, port = 5179, pluginModule, startup) => {
254
256
  .restore()
255
257
  .catch((error) => [error instanceof Error ? error.message : String(error)]);
256
258
  for (const error of extensionErrors)
257
- console.error(`Plugin: ${error}`);
259
+ terminal.error(`Plugin: ${error}`);
258
260
  if (startup?.file && startup.data) {
259
261
  const result = (await handleExtensions({
260
262
  action: "install",
@@ -263,12 +265,12 @@ export const startServer = async (mode, port = 5179, pluginModule, startup) => {
263
265
  base: null,
264
266
  }));
265
267
  loginPlugins = result.items.find((item) => item.file === startup.file)?.plugins ?? [];
266
- console.log(`Installed ${startup.file} in ${join(root, EXTENSIONS_DIR)}`);
268
+ terminal.operation("Installed plugin", startup.file);
267
269
  }
268
270
  // DOCS_HMR=0 = no hot reload (nothing is watched = changes need a manual reload).
269
271
  if (process.env.DOCS_HMR !== "0") {
270
272
  const watcher = watchProject(root, pkgRoot, (kind, files) => {
271
- console.log(`hmr: ${kind} (${files.join(", ")})`);
273
+ terminal.operation(kind === "client" ? "Reloaded client" : "Changed", files.join(", "));
272
274
  if (kind === "client") {
273
275
  bundleCache.clear();
274
276
  graphChunks = undefined;
@@ -387,7 +389,13 @@ export const startServer = async (mode, port = 5179, pluginModule, startup) => {
387
389
  await application.handle(mode, req, res);
388
390
  };
389
391
  const listener = (req, res) => {
390
- handle(req, res).catch((e) => {
392
+ handle(req, res)
393
+ .then(() => {
394
+ if (typeof res.statusCode === "number")
395
+ logHttpOperation(req.method ?? "GET", req.url ?? "/", res.statusCode);
396
+ })
397
+ .catch((e) => {
398
+ terminal.error(`Request failed: ${req.method ?? "GET"} ${(req.url ?? "/").split(/[?#]/)[0]}`);
391
399
  if (!res.headersSent) {
392
400
  res.writeHead(500, { "content-type": "text/plain; charset=utf-8" });
393
401
  }
@@ -464,15 +472,15 @@ export const startServer = async (mode, port = 5179, pluginModule, startup) => {
464
472
  server.once("listening", () => {
465
473
  const addr = server.address();
466
474
  const p = typeof addr === "object" && addr ? addr.port : port;
467
- console.log(`dooc ${mode} (${root}): ${scheme}://localhost:${p}/`);
475
+ terminal.ready(mode === "preview" ? "view" : mode, root, `${scheme}://localhost:${p}/`);
468
476
  if (startup?.open) {
469
477
  const url = `${scheme}://localhost:${p}/`;
470
478
  const command = process.platform === "darwin" ? "open" : "xdg-open";
471
479
  const browser = spawn(command, [url], { stdio: "ignore", detached: true });
472
- browser.on("error", () => console.error(`Open ${url} in your browser.`));
480
+ browser.on("error", () => terminal.warn(`Open ${url} in your browser.`));
473
481
  browser.on("exit", (code) => {
474
482
  if (code)
475
- console.error(`Open ${url} in your browser.`);
483
+ terminal.warn(`Open ${url} in your browser.`);
476
484
  });
477
485
  browser.unref();
478
486
  }
@@ -481,7 +489,7 @@ export const startServer = async (mode, port = 5179, pluginModule, startup) => {
481
489
  console.log(`Log in to ${plugin}: ${handlePlugins.loginLink(plugin, `${scheme}://localhost:${p}`)}`);
482
490
  }
483
491
  catch (error) {
484
- console.error(error instanceof Error ? error.message : String(error));
492
+ terminal.error(error instanceof Error ? error.message : String(error));
485
493
  }
486
494
  }
487
495
  if (loginPlugins.length)
@@ -490,7 +498,7 @@ export const startServer = async (mode, port = 5179, pluginModule, startup) => {
490
498
  const listen = (p, left) => {
491
499
  server.once("error", (err) => {
492
500
  if (err.code === "EADDRINUSE" && left > 0) {
493
- console.log(`port ${p} in use → trying ${p + 1}`);
501
+ terminal.warn(`Port ${p} is in use; trying ${p + 1}`);
494
502
  listen(p + 1, left - 1);
495
503
  return;
496
504
  }
@@ -3,6 +3,7 @@ import { createServer } from "node:http";
3
3
  import { dirname, join } from "node:path";
4
4
  import { prebuilt, readViewerAsset } from "./assets.js";
5
5
  import { bundleClient } from "./serve.js";
6
+ import { terminal } from "./terminal.js";
6
7
  export const validateServerUrl = (value) => {
7
8
  const url = new URL(value);
8
9
  if (url.protocol === "http:")
@@ -112,6 +113,6 @@ export const startStaticClient = async (port = 5180, socket) => {
112
113
  server.listen(port, "127.0.0.1", resolve);
113
114
  });
114
115
  const address = server.address();
115
- console.log(`dooc client: http://localhost:${typeof address === "object" && address ? address.port : port}`);
116
+ terminal.ready("client", socket ?? "Browser workspaces", `http://localhost:${typeof address === "object" && address ? address.port : port}/`);
116
117
  return server;
117
118
  };
@@ -0,0 +1,22 @@
1
+ import type { Writable } from "node:stream";
2
+ import type { DownloadProgress } from "../engine/compiler/download-progress.js";
3
+ export declare function createTerminal(output?: Writable & {
4
+ isTTY?: boolean;
5
+ }): {
6
+ ready(mode: string, root: string, url: string): void;
7
+ info(message: string): void;
8
+ warn(message: string): void;
9
+ error(message: string): void;
10
+ operation(action: string, detail?: string): void;
11
+ download(event: DownloadProgress): void;
12
+ close: () => void;
13
+ };
14
+ export declare const terminal: {
15
+ ready(mode: string, root: string, url: string): void;
16
+ info(message: string): void;
17
+ warn(message: string): void;
18
+ error(message: string): void;
19
+ operation(action: string, detail?: string): void;
20
+ download(event: DownloadProgress): void;
21
+ close: () => void;
22
+ };
@@ -0,0 +1,131 @@
1
+ import { stripVTControlCharacters, styleText } from "node:util";
2
+ import { log, spinner } from "@clack/prompts";
3
+ function safeText(value) {
4
+ return stripVTControlCharacters(value)
5
+ .replace(/\p{Cc}|\p{Cf}/gu, " ")
6
+ .replace(/\b[a-z][a-z\d+.-]*:\/\/[^\s<>"'`]+/giu, (value) => {
7
+ try {
8
+ const url = new URL(value);
9
+ url.username = url.password = url.search = url.hash = "";
10
+ return url.href;
11
+ }
12
+ catch {
13
+ return "[invalid URL]";
14
+ }
15
+ });
16
+ }
17
+ function bytes(value) {
18
+ const size = Math.max(0, Number.isFinite(value) ? value : 0);
19
+ const unit = Math.min(3, Math.floor(Math.log2(Math.max(1, size)) / 10));
20
+ return `${unit ? (size / 1024 ** unit).toFixed(1) : Math.floor(size)} ${["B", "KiB", "MiB", "GiB"][unit]}`;
21
+ }
22
+ function amount(received, total) {
23
+ return total !== undefined && Number.isFinite(total) && total > 0
24
+ ? `${bytes(received)} / ${bytes(total)} (${Math.min(100, Math.floor((received / total) * 100))}%)`
25
+ : bytes(received);
26
+ }
27
+ export function createTerminal(output = process.stderr) {
28
+ const rich = output.isTTY === true &&
29
+ process.stdin.isTTY === true &&
30
+ process.env.NO_COLOR === undefined &&
31
+ !process.env.CI &&
32
+ process.env.TERM !== "dumb";
33
+ const options = { output, spacing: 0, withGuide: false };
34
+ const active = new Map();
35
+ let progress;
36
+ let updated = 0;
37
+ const color = (name, text) => rich ? styleText(name, text, { validateStream: false }) : text;
38
+ const clear = () => {
39
+ progress?.clear();
40
+ progress = undefined;
41
+ };
42
+ const close = () => {
43
+ active.clear();
44
+ clear();
45
+ };
46
+ const summary = () => {
47
+ const downloads = [...active.values()];
48
+ const received = downloads.reduce((sum, item) => sum + item.received, 0);
49
+ const total = downloads.every((item) => item.total !== undefined)
50
+ ? downloads.reduce((sum, item) => sum + (item.total ?? 0), 0)
51
+ : undefined;
52
+ const label = downloads.length === 1
53
+ ? safeText(downloads[0]?.url ?? "")
54
+ : `${downloads.length} files`;
55
+ const detail = downloads.length === 1 ? downloads[0]?.detail : undefined;
56
+ return `Downloading ${label} · ${detail === undefined ? amount(received, total) : safeText(detail)}`;
57
+ };
58
+ const render = () => {
59
+ if (!rich || !active.size)
60
+ return;
61
+ if (!progress) {
62
+ progress = spinner({
63
+ output,
64
+ withGuide: false,
65
+ onCancel: () => {
66
+ close();
67
+ process.exit(130);
68
+ },
69
+ });
70
+ progress.start(summary());
71
+ }
72
+ else
73
+ progress.message(summary());
74
+ };
75
+ const write = (label, message, tone = "gray") => {
76
+ clear();
77
+ log.message(`${color(tone, label)} ${safeText(message)}`, options);
78
+ render();
79
+ };
80
+ return {
81
+ ready(mode, root, url) {
82
+ clear();
83
+ log.message([
84
+ "",
85
+ color("bold", `dooc · ${safeText(mode)}`),
86
+ ` ${color("cyan", safeText(url))}`,
87
+ ` ${safeText(root)}`,
88
+ color("gray", " Ctrl+C to stop"),
89
+ "",
90
+ ], options);
91
+ render();
92
+ },
93
+ info(message) {
94
+ write("Info", message, "cyan");
95
+ },
96
+ warn(message) {
97
+ write("Warning", message, "yellow");
98
+ },
99
+ error(message) {
100
+ write("Error", message, "red");
101
+ },
102
+ operation(action, detail) {
103
+ write(new Date().toTimeString().slice(0, 8), `${action}${detail ? ` ${detail}` : ""}`);
104
+ },
105
+ download(event) {
106
+ if (event.state === "complete" || event.state === "error") {
107
+ active.delete(event.url);
108
+ write(event.state === "complete" ? "Downloaded" : "Download failed", `${event.url} · ${event.detail ?? amount(event.received, event.total)}`, event.state === "complete" ? "green" : "red");
109
+ return;
110
+ }
111
+ active.set(event.url, event);
112
+ const now = Date.now();
113
+ if (event.state === "start") {
114
+ updated = now;
115
+ if (rich)
116
+ render();
117
+ else
118
+ write("Downloading", `${event.url} · ${event.detail ?? amount(event.received, event.total)}`);
119
+ }
120
+ else if (now - updated >= (rich ? 250 : 1000)) {
121
+ updated = now;
122
+ if (rich)
123
+ render();
124
+ else
125
+ write("Progress", summary());
126
+ }
127
+ },
128
+ close,
129
+ };
130
+ }
131
+ export const terminal = createTerminal();
@@ -19,7 +19,9 @@ import { gitBaseBody, gitBaseText, setSubformatChanges } from "./git-diff.js";
19
19
  import { workspaceHistory } from "./history.js";
20
20
  import { watchProject } from "./hmr.js";
21
21
  import { loadSiteLanguages } from "./languages.js";
22
+ import { loggedWorkspaceOps } from "./operation-log.js";
22
23
  import { loadViewerPlugins } from "./plugin-config.js";
24
+ import { terminal } from "./terminal.js";
23
25
  import { readWorkspaceSource, sourceFileBase } from "./workspace.js";
24
26
  export const clientOrigin = (value) => {
25
27
  const url = new URL(value);
@@ -207,7 +209,9 @@ export const startWorkspaceServer = async (manifest, port = 5179, origin = "http
207
209
  const allowed = clientOrigin(origin);
208
210
  let channel;
209
211
  const manager = await nodeWorkspaceOperations(manifest, pluginModule, (event, data) => channel?.broadcast(event, data));
210
- const activeChannel = createWorkspaceServer(manager.ops, { boot: crypto.randomUUID() });
212
+ const activeChannel = createWorkspaceServer(loggedWorkspaceOps(manager.ops), {
213
+ boot: crypto.randomUUID(),
214
+ });
211
215
  channel = activeChannel;
212
216
  const server = createServer((_req, res) => {
213
217
  res.writeHead(404);
@@ -261,6 +265,7 @@ export const startWorkspaceServer = async (manifest, port = 5179, origin = "http
261
265
  throw error;
262
266
  }
263
267
  const address = server.address();
264
- console.log(`dooc server: ws://localhost:${typeof address === "object" && address ? address.port : port}${WORKSPACE_PATH} (client: ${allowed})`);
268
+ terminal.ready("server", manifest, `ws://localhost:${typeof address === "object" && address ? address.port : port}${WORKSPACE_PATH}`);
269
+ terminal.info(`Client origin: ${allowed}`);
265
270
  return server;
266
271
  };
@@ -0,0 +1,2 @@
1
+ /** Remote CLI sessions retain repository files without executing their workspace configuration. */
2
+ export declare const allowsWorkspaceCode: () => boolean;
@@ -0,0 +1,2 @@
1
+ /** Remote CLI sessions retain repository files without executing their workspace configuration. */
2
+ export const allowsWorkspaceCode = () => process.env.DOOC_REMOTE_WORKSPACE !== "1";
@@ -6,7 +6,7 @@ export declare const requestScheme: (req: {
6
6
  socket: object;
7
7
  }) => "http" | "https";
8
8
  export declare function isLocalToolRequest(host: string, origin: string | undefined, contentType: string | undefined): boolean;
9
- export declare function runCodeTool(root: string, body: string, position: number, action: "format" | "lint"): Promise<{
9
+ export declare function runCodeTool(root: string, body: string, position: number, action: "format" | "lint", allowExternal?: boolean): Promise<{
10
10
  findings: {
11
11
  range: [number, number];
12
12
  message: string;
@@ -21,7 +21,7 @@ export declare function runCodeTool(root: string, body: string, position: number
21
21
  };
22
22
  findings?: undefined;
23
23
  }>;
24
- export declare function validateCodeTools(root: string, body: string): Promise<{
24
+ export declare function validateCodeTools(root: string, body: string, allowExternal?: boolean): Promise<{
25
25
  changes: {
26
26
  from: number;
27
27
  to: number;
@@ -34,7 +34,7 @@ export declare function validateCodeTools(root: string, body: string): Promise<{
34
34
  }[];
35
35
  }>;
36
36
  /** Apply the same registered formatter/linter to a complete file without writing to disk. */
37
- export declare function validateTextfileCode(root: string, language: string, content: string): Promise<{
37
+ export declare function validateTextfileCode(root: string, language: string, content: string, allowExternal?: boolean): Promise<{
38
38
  content: string;
39
39
  findings: {
40
40
  range: [number, number];
@@ -44,21 +44,25 @@ function execute(args, cwd, input, lint) {
44
44
  child.stdin?.end(input);
45
45
  });
46
46
  }
47
- export async function runCodeTool(root, body, position, action) {
47
+ export async function runCodeTool(root, body, position, action, allowExternal = true) {
48
48
  const block = codeBlockAt(body, position);
49
49
  if (!/^[a-zA-Z0-9][a-zA-Z0-9_+-]*$/.test(block.language))
50
50
  throw new Error("Unsupported code language identifier");
51
51
  const path = join(root, ".dooc", "editor-tools", `${block.language}.json`);
52
- let config;
53
- try {
54
- config = JSON.parse(await readFile(path, "utf8"));
52
+ let config = {};
53
+ if (allowExternal) {
54
+ try {
55
+ config = JSON.parse(await readFile(path, "utf8"));
56
+ }
57
+ catch (error) {
58
+ if (error.code !== "ENOENT")
59
+ throw error;
60
+ if (block.language !== "json")
61
+ throw new Error(`Create .dooc/editor-tools/${block.language}.json to configure this language`);
62
+ }
55
63
  }
56
- catch (error) {
57
- if (error.code !== "ENOENT")
58
- throw error;
59
- if (block.language !== "json")
60
- throw new Error(`Create .dooc/editor-tools/${block.language}.json to configure this language`);
61
- config = {};
64
+ else if (block.language !== "json") {
65
+ throw new Error("External editor tools are disabled in remote sessions");
62
66
  }
63
67
  if (!config || typeof config !== "object")
64
68
  throw new Error("Invalid editor tool configuration");
@@ -139,7 +143,7 @@ export async function runCodeTool(root, body, position, action) {
139
143
  });
140
144
  return { findings };
141
145
  }
142
- export async function validateCodeTools(root, body) {
146
+ export async function validateCodeTools(root, body, allowExternal = true) {
143
147
  const original = body;
144
148
  const configuredBlocks = async (text, tool) => {
145
149
  const blocks = [];
@@ -160,6 +164,11 @@ export async function validateCodeTools(root, body) {
160
164
  !node.lang ||
161
165
  !/^[a-zA-Z0-9][a-zA-Z0-9_+-]*$/.test(node.lang))
162
166
  continue;
167
+ if (!allowExternal) {
168
+ if (node.lang === "json")
169
+ blocks.push(node.position.start.offset);
170
+ continue;
171
+ }
163
172
  let raw;
164
173
  try {
165
174
  raw = await readFile(join(root, ".dooc/editor-tools", `${node.lang}.json`), "utf8");
@@ -182,14 +191,14 @@ export async function validateCodeTools(root, body) {
182
191
  };
183
192
  const originalFindings = [];
184
193
  for (const position of await configuredBlocks(body, "linter")) {
185
- const result = await runCodeTool(root, body, position, "lint");
194
+ const result = await runCodeTool(root, body, position, "lint", allowExternal);
186
195
  originalFindings.push(...(result.findings ?? []));
187
196
  }
188
197
  if (originalFindings.some((finding) => finding.ruleId === "error")) {
189
198
  return { changes: [], findings: originalFindings };
190
199
  }
191
200
  for (const position of (await configuredBlocks(body, "formatter")).reverse()) {
192
- const { change } = await runCodeTool(root, body, position, "format");
201
+ const { change } = await runCodeTool(root, body, position, "format", allowExternal);
193
202
  if (change && body.slice(change.from, change.to) !== change.insert) {
194
203
  body = body.slice(0, change.from) + change.insert + body.slice(change.to);
195
204
  }
@@ -199,7 +208,7 @@ export async function validateCodeTools(root, body) {
199
208
  return { changes: [], findings: originalFindings };
200
209
  const findings = [];
201
210
  for (const position of await configuredBlocks(body, "linter")) {
202
- const result = await runCodeTool(root, body, position, "lint");
211
+ const result = await runCodeTool(root, body, position, "lint", allowExternal);
203
212
  findings.push(...(result.findings ?? []));
204
213
  }
205
214
  if (findings.some((finding) => finding.ruleId === "error")) {
@@ -220,7 +229,7 @@ export async function validateCodeTools(root, body) {
220
229
  };
221
230
  }
222
231
  /** Apply the same registered formatter/linter to a complete file without writing to disk. */
223
- export async function validateTextfileCode(root, language, content) {
232
+ export async function validateTextfileCode(root, language, content, allowExternal = true) {
224
233
  if (!/^[a-zA-Z0-9][a-zA-Z0-9_+-]*$/.test(language) || content.includes("\0"))
225
234
  throw new Error("Invalid text file tool request");
226
235
  const eol = content.includes("\r\n") ? "\r\n" : "\n";
@@ -228,7 +237,7 @@ export async function validateTextfileCode(root, language, content) {
228
237
  const prefix = `${marker}${language}${eol}`;
229
238
  const separator = content && !content.endsWith("\n") ? eol : "";
230
239
  let body = `${prefix}${content}${separator}${marker}${eol}`;
231
- const result = await validateCodeTools(root, body);
240
+ const result = await validateCodeTools(root, body, allowExternal);
232
241
  for (const change of [...result.changes].reverse())
233
242
  body = body.slice(0, change.from) + change.insert + body.slice(change.to);
234
243
  const block = codeBlockAt(body, 0);