dsh-typst-plugin 0.1.0-alpha.0 → 0.1.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.en.md +86 -52
- package/README.md +93 -59
- package/cordis.patch.yml +1 -1
- package/docs/images/icon.png +0 -0
- package/lib/client.js +2088 -1136
- package/lib/client.js.map +4 -4
- package/lib/config.d.ts +66 -9
- package/lib/config.d.ts.map +1 -1
- package/lib/config.js +161 -25
- package/lib/config.js.map +1 -7
- package/lib/constants.d.ts +21 -2
- package/lib/constants.d.ts.map +1 -1
- package/lib/constants.js +83 -60
- package/lib/constants.js.map +1 -7
- package/lib/contract.d.ts +90 -6
- package/lib/contract.d.ts.map +1 -1
- package/lib/contract.js +9 -1
- package/lib/contract.js.map +1 -7
- package/lib/diagnostic-text.d.ts +13 -0
- package/lib/diagnostic-text.d.ts.map +1 -0
- package/lib/diagnostic-text.js +28 -0
- package/lib/diagnostic-text.js.map +1 -0
- package/lib/errors.d.ts +57 -15
- package/lib/errors.d.ts.map +1 -1
- package/lib/errors.js +154 -79
- package/lib/errors.js.map +1 -7
- package/lib/host/facts.d.ts.map +1 -1
- package/lib/host/facts.js +133 -139
- package/lib/host/facts.js.map +1 -7
- package/lib/host/which.d.ts +20 -0
- package/lib/host/which.d.ts.map +1 -0
- package/lib/host/which.js +50 -0
- package/lib/host/which.js.map +1 -0
- package/lib/index.js +2 -5
- package/lib/index.js.map +1 -7
- package/lib/remote.d.ts +5 -4
- package/lib/remote.d.ts.map +1 -1
- package/lib/remote.js +153 -143
- package/lib/remote.js.map +1 -7
- package/lib/service.d.ts +28 -4
- package/lib/service.d.ts.map +1 -1
- package/lib/service.js +202 -99
- package/lib/service.js.map +1 -7
- package/lib/skills/typst.js +74 -68
- package/lib/skills/typst.js.map +1 -7
- package/lib/status-codec.js +10 -5
- package/lib/status-codec.js.map +1 -7
- package/lib/tools/registration.d.ts +4 -3
- package/lib/tools/registration.d.ts.map +1 -1
- package/lib/tools/registration.js +726 -493
- package/lib/tools/registration.js.map +1 -7
- package/lib/tools/shared.d.ts +4 -5
- package/lib/tools/shared.d.ts.map +1 -1
- package/lib/tools/shared.js +73 -64
- package/lib/tools/shared.js.map +1 -7
- package/lib/typert.d.ts +5 -3
- package/lib/typert.d.ts.map +1 -1
- package/lib/typert.js +113 -64
- package/lib/typert.js.map +1 -7
- package/lib/typst/diagnostics.d.ts.map +1 -1
- package/lib/typst/diagnostics.js +218 -152
- package/lib/typst/diagnostics.js.map +1 -7
- package/lib/typst/flags.d.ts +8 -0
- package/lib/typst/flags.d.ts.map +1 -0
- package/lib/typst/flags.js +8 -0
- package/lib/typst/flags.js.map +1 -0
- package/lib/typst/locate.d.ts +6 -13
- package/lib/typst/locate.d.ts.map +1 -1
- package/lib/typst/locate.js +138 -180
- package/lib/typst/locate.js.map +1 -7
- package/lib/typst/mainfile.d.ts +23 -4
- package/lib/typst/mainfile.d.ts.map +1 -1
- package/lib/typst/mainfile.js +131 -59
- package/lib/typst/mainfile.js.map +1 -7
- package/lib/typst/match.d.ts +9 -1
- package/lib/typst/match.d.ts.map +1 -1
- package/lib/typst/match.js +213 -157
- package/lib/typst/match.js.map +1 -7
- package/lib/typst/oneshot.d.ts +8 -5
- package/lib/typst/oneshot.d.ts.map +1 -1
- package/lib/typst/oneshot.js +76 -66
- package/lib/typst/oneshot.js.map +1 -7
- package/lib/typst/owners.d.ts +28 -0
- package/lib/typst/owners.d.ts.map +1 -0
- package/lib/typst/owners.js +98 -0
- package/lib/typst/owners.js.map +1 -0
- package/lib/typst/pdf-extract.d.ts +1 -2
- package/lib/typst/pdf-extract.d.ts.map +1 -1
- package/lib/typst/pdf-extract.js +98 -74
- package/lib/typst/pdf-extract.js.map +1 -7
- package/lib/typst/process.d.ts +73 -0
- package/lib/typst/process.d.ts.map +1 -0
- package/lib/typst/process.js +147 -0
- package/lib/typst/process.js.map +1 -0
- package/lib/typst/text.d.ts +4 -7
- package/lib/typst/text.d.ts.map +1 -1
- package/lib/typst/text.js +258 -290
- package/lib/typst/text.js.map +1 -7
- package/lib/typst/watcher.d.ts +16 -17
- package/lib/typst/watcher.d.ts.map +1 -1
- package/lib/typst/watcher.js +199 -208
- package/lib/typst/watcher.js.map +1 -7
- package/lib/wire-schemas.d.ts +8 -153
- package/lib/wire-schemas.d.ts.map +1 -1
- package/lib/wire-schemas.js +405 -361
- package/lib/wire-schemas.js.map +1 -7
- package/lib/workspace/containment.d.ts +25 -0
- package/lib/workspace/containment.d.ts.map +1 -0
- package/lib/workspace/containment.js +54 -0
- package/lib/workspace/containment.js.map +1 -0
- package/lib/workspace/session.d.ts +73 -14
- package/lib/workspace/session.d.ts.map +1 -1
- package/lib/workspace/session.js +1516 -1172
- package/lib/workspace/session.js.map +1 -7
- package/locale/en.json +8 -2
- package/locale/zh.json +8 -2
- package/package.json +36 -179
- package/release-provenance.json +137 -0
- package/lib/typst/pdfjs-worker.d.js +0 -1
- package/lib/typst/pdfjs-worker.d.js.map +0 -7
package/lib/workspace/session.js
CHANGED
|
@@ -1,1232 +1,1576 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
1
|
+
/**
|
|
2
|
+
* One workspace's Typst workbench state: toolchain detection, main-file
|
|
3
|
+
* choice, the `typst watch` lifecycle, preview snapshots, agent highlights,
|
|
4
|
+
* source matching, and the settle algorithm `typst_check` relies on.
|
|
5
|
+
* Ported from the ZCode typst-workbench server (0.2.0) `src/app/session.ts`,
|
|
6
|
+
* adapted to this repository's error domain and framed as a plain class the
|
|
7
|
+
* cordis service registers per workspace root (unit-testable without a
|
|
8
|
+
* harness). Host half only.
|
|
9
|
+
* @module dsh-typst/workspace/session
|
|
10
|
+
*/
|
|
11
|
+
import { createHash } from "node:crypto";
|
|
12
|
+
import { mkdir, lstat, open, readFile, realpath, rm, stat, } from "node:fs/promises";
|
|
10
13
|
import { tmpdir } from "node:os";
|
|
11
|
-
import {
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
isAbsolute,
|
|
16
|
-
join,
|
|
17
|
-
relative,
|
|
18
|
-
resolve,
|
|
19
|
-
sep
|
|
20
|
-
} from "node:path";
|
|
21
|
-
import {
|
|
22
|
-
LIMITS,
|
|
23
|
-
SOURCE_FILE_MAX_BYTES,
|
|
24
|
-
SOURCE_FILES_MAX,
|
|
25
|
-
INPUT_FILES_MAX
|
|
26
|
-
} from "../constants.js";
|
|
27
|
-
import {
|
|
28
|
-
INSTALL_HINT,
|
|
29
|
-
TypstError,
|
|
30
|
-
TYPST_INVALID_ARGUMENT,
|
|
31
|
-
TYPST_MISSING,
|
|
32
|
-
TYPST_NOT_FOUND,
|
|
33
|
-
TYPST_NO_MAIN,
|
|
34
|
-
TYPST_NO_PREVIEW,
|
|
35
|
-
TYPST_PATH_OUTSIDE_WORKSPACE,
|
|
36
|
-
TYPST_QUOTE_NOT_FOUND,
|
|
37
|
-
TYPST_TIMEOUT,
|
|
38
|
-
TYPST_TOO_OLD,
|
|
39
|
-
TYPST_UNUSABLE,
|
|
40
|
-
TYPST_WATCH_FAILED
|
|
41
|
-
} from "../errors.js";
|
|
14
|
+
import { basename, dirname, extname, isAbsolute, join, relative, resolve, sep, } from "node:path";
|
|
15
|
+
import { workspaceWritableRoots, SandboxInvalidRootError, } from "@deepseek-ai/dsh-sandbox";
|
|
16
|
+
import { LIMITS, SOURCE_BYTES_MAX, SOURCE_FILE_MAX_BYTES, SOURCE_FILES_MAX, INPUT_FILES_MAX, } from "../constants.js";
|
|
17
|
+
import { INSTALL_HINT, TypstError, TYPST_INVALID_ARGUMENT, TYPST_MAIN_CHANGED, TYPST_MISSING, TYPST_NOT_FOUND, TYPST_NO_MAIN, TYPST_NO_PREVIEW, TYPST_PAGE_OUT_OF_RANGE, TYPST_PATH_OUTSIDE_WORKSPACE, TYPST_QUOTE_NOT_FOUND, TYPST_SANDBOX_INVALID_ROOT, TYPST_SANDBOX_READ_ONLY, TYPST_TIMEOUT, TYPST_TOO_OLD, TYPST_UNUSABLE, TYPST_WATCH_FAILED, } from "../errors.js";
|
|
42
18
|
import { detectFacts, cargoSpec } from "../host/facts.js";
|
|
43
19
|
import { locateTypst, searchedDirs } from "../typst/locate.js";
|
|
44
20
|
import { chooseMain, indexTypFiles } from "../typst/mainfile.js";
|
|
45
21
|
import { pageCount, extractPages, pdfjsDataDir } from "../typst/pdf-extract.js";
|
|
46
|
-
import {
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
} from "../typst/
|
|
50
|
-
import {
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
22
|
+
import { exportPdf, renderPages, } from "../typst/oneshot.js";
|
|
23
|
+
import { parsePages, findQuote, rectsFor, textAt, } from "../typst/text.js";
|
|
24
|
+
import { fuzzyFind, skeleton, lineStarts, lineRange, locateInSources, } from "../typst/match.js";
|
|
25
|
+
import { Watcher } from "../typst/watcher.js";
|
|
26
|
+
import { makeBuildDir } from "../typst/owners.js";
|
|
27
|
+
import { ProcessRunner } from "../typst/process.js";
|
|
28
|
+
import { isWithin, resolveInside } from "./containment.js";
|
|
29
|
+
import { withFileLock, writeFileAtomic } from "@deepseek-ai/dsh-atomic-write";
|
|
30
|
+
/**
|
|
31
|
+
* The real path of a file, or the path itself when it cannot be resolved.
|
|
32
|
+
*
|
|
33
|
+
* typst reports the paths it resolved, and a resolved path is the real one:
|
|
34
|
+
* macOS's temporary directory is a symlink to /private/var, so the report and
|
|
35
|
+
* the workspace root spell the same file two ways. Both sides are resolved
|
|
36
|
+
* before they are compared.
|
|
37
|
+
* @param path - the path to resolve.
|
|
38
|
+
* @returns the real path, or the input when it does not exist.
|
|
39
|
+
*/
|
|
64
40
|
async function realish(path) {
|
|
65
|
-
|
|
41
|
+
return realpath(path).catch(() => path);
|
|
66
42
|
}
|
|
67
|
-
class WorkspaceSession {
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
indexing = null;
|
|
90
|
-
indexingPromise = null;
|
|
91
|
-
mainQueue = Promise.resolve();
|
|
92
|
-
/**
|
|
93
|
-
* The candidates the current document includes, as typst's own dependency
|
|
94
|
-
* report names them. Kept between compiles so the panel can list fragments
|
|
95
|
-
* apart from documents before the first successful compile settles.
|
|
96
|
-
*/
|
|
97
|
-
fragments = [];
|
|
98
|
-
status = { phase: "idle", run: 0 };
|
|
99
|
-
diagnostics = [];
|
|
100
|
-
watcher = null;
|
|
101
|
-
watcherStartedAt = 0;
|
|
102
|
-
buildDir = null;
|
|
103
|
-
/** When the in-flight compile started; also when the last finished one started (check uses this). */
|
|
104
|
-
compilingSince = null;
|
|
105
|
-
finishedStartedAt = 0;
|
|
106
|
-
finishWaiters = /* @__PURE__ */ new Set();
|
|
107
|
-
restartTimer = null;
|
|
108
|
-
snapshots = /* @__PURE__ */ new Map();
|
|
109
|
-
current = null;
|
|
110
|
-
seq = 0;
|
|
111
|
-
highlights = [];
|
|
112
|
-
highlightSeq = 0;
|
|
113
|
-
view = null;
|
|
114
|
-
viewSeq = 0;
|
|
115
|
-
activation = null;
|
|
116
|
-
activated = false;
|
|
117
|
-
closed = false;
|
|
118
|
-
pagesCache = /* @__PURE__ */ new Map();
|
|
119
|
-
// Setup page: host facts, "handed to the agent", re-lookup while open.
|
|
120
|
-
facts = null;
|
|
121
|
-
factsPending = null;
|
|
122
|
-
setupTimer = null;
|
|
123
|
-
setupTicks = 0;
|
|
124
|
-
setupSubscribers = 0;
|
|
125
|
-
rechecking = null;
|
|
126
|
-
constructor(options) {
|
|
127
|
-
this.options = options;
|
|
128
|
-
this.workspaceRoot = resolve(options.workspaceRoot);
|
|
129
|
-
this.log = options.log ?? (() => void 0);
|
|
130
|
-
this.env = options.env ?? process.env;
|
|
131
|
-
}
|
|
132
|
-
onChange(listener) {
|
|
133
|
-
this.listeners.add(listener);
|
|
134
|
-
return () => this.listeners.delete(listener);
|
|
135
|
-
}
|
|
136
|
-
/**
|
|
137
|
-
* Await state changes until `signal` aborts, yielding once per coalesced
|
|
138
|
-
* burst (the watch stream's push side). Every yielded tick means "state
|
|
139
|
-
* changed since the last frame"; the caller re-reads `state()`.
|
|
140
|
-
*/
|
|
141
|
-
async *onChangeWaiter(signal) {
|
|
142
|
-
const queue = [];
|
|
143
|
-
let wake = null;
|
|
144
|
-
const off = this.onChange(() => {
|
|
145
|
-
queue.push(/* @__PURE__ */ Symbol("change"));
|
|
146
|
-
wake?.();
|
|
147
|
-
wake = null;
|
|
148
|
-
});
|
|
149
|
-
const abort = () => {
|
|
150
|
-
wake?.();
|
|
151
|
-
wake = null;
|
|
43
|
+
export class WorkspaceSession {
|
|
44
|
+
workspaceRoot;
|
|
45
|
+
realRoot = null;
|
|
46
|
+
log;
|
|
47
|
+
env;
|
|
48
|
+
process;
|
|
49
|
+
options;
|
|
50
|
+
listeners = new Set();
|
|
51
|
+
stateVersion = 0;
|
|
52
|
+
toolchain = { state: "missing" };
|
|
53
|
+
main = null;
|
|
54
|
+
candidates = [];
|
|
55
|
+
candidatesAt = 0;
|
|
56
|
+
generation = 1;
|
|
57
|
+
compileToken = 0;
|
|
58
|
+
startingWatcher = null;
|
|
59
|
+
previewError = null;
|
|
60
|
+
discovery = {
|
|
61
|
+
scanning: false,
|
|
62
|
+
includeExcluded: false,
|
|
63
|
+
visited: 0,
|
|
64
|
+
errors: [],
|
|
152
65
|
};
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
66
|
+
indexing = null;
|
|
67
|
+
indexingPromise = null;
|
|
68
|
+
mainQueue = Promise.resolve();
|
|
69
|
+
/**
|
|
70
|
+
* The candidates the current document includes, as typst's own dependency
|
|
71
|
+
* report names them. Kept between compiles so the panel can list fragments
|
|
72
|
+
* apart from documents before the first successful compile settles.
|
|
73
|
+
*/
|
|
74
|
+
fragments = [];
|
|
75
|
+
status = { phase: "idle", run: 0 };
|
|
76
|
+
diagnostics = [];
|
|
77
|
+
/** Full diagnostic count of the last round, before the frame cap. */
|
|
78
|
+
diagnosticsTotal = 0;
|
|
79
|
+
watcher = null;
|
|
80
|
+
retiring = null;
|
|
81
|
+
stopPromise = Promise.resolve();
|
|
82
|
+
watcherStartedAt = 0;
|
|
83
|
+
buildDir = null;
|
|
84
|
+
/** Cancellation handles for in-flight one-shot compiles. */
|
|
85
|
+
liveOneshots = new Set();
|
|
86
|
+
/** When the in-flight compile started; also when the last finished one started (check uses this). */
|
|
87
|
+
compilingSince = null;
|
|
88
|
+
finishedStartedAt = 0;
|
|
89
|
+
finishGeneration = 0;
|
|
90
|
+
/** Monotonic count of finished compiles; lets settle notice a wake it missed. */
|
|
91
|
+
finishVersion = 0;
|
|
92
|
+
/** Input signature the last completed compile consumed. */
|
|
93
|
+
compiledInputs = null;
|
|
94
|
+
finishWaiters = new Set();
|
|
95
|
+
restartTimer = null;
|
|
96
|
+
snapshots = new Map();
|
|
97
|
+
current = null;
|
|
98
|
+
seq = 0;
|
|
99
|
+
highlights = [];
|
|
100
|
+
highlightSeq = 0;
|
|
101
|
+
view = null;
|
|
102
|
+
viewSeq = 0;
|
|
103
|
+
activation = null;
|
|
104
|
+
activated = false;
|
|
105
|
+
closed = false;
|
|
106
|
+
pagesCache = new Map();
|
|
107
|
+
/** Per-compile excerpt cache: one read per file, keyed by mtime. */
|
|
108
|
+
excerptCache = new Map();
|
|
109
|
+
// Setup page: host facts, "handed to the agent", re-lookup while open.
|
|
110
|
+
facts = null;
|
|
111
|
+
factsPending = null;
|
|
112
|
+
setupTimer = null;
|
|
113
|
+
setupTicks = 0;
|
|
114
|
+
setupSubscribers = 0;
|
|
115
|
+
rechecking = null;
|
|
116
|
+
recheckShell = false;
|
|
117
|
+
constructor(options) {
|
|
118
|
+
this.options = options;
|
|
119
|
+
this.workspaceRoot = resolve(options.workspaceRoot);
|
|
120
|
+
this.log = options.log ?? (() => undefined);
|
|
121
|
+
this.env = options.env ?? process.env;
|
|
122
|
+
this.process = new ProcessRunner(options.subprocess);
|
|
168
123
|
}
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
)
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
toolchainView() {
|
|
203
|
-
const toolchain = this.toolchain;
|
|
204
|
-
switch (toolchain.state) {
|
|
205
|
-
case "ready":
|
|
206
|
-
return {
|
|
207
|
-
state: "ready",
|
|
208
|
-
version: toolchain.version,
|
|
209
|
-
path: toolchain.path,
|
|
210
|
-
source: toolchain.source
|
|
211
|
-
};
|
|
212
|
-
case "missing":
|
|
213
|
-
return { state: "missing" };
|
|
214
|
-
case "too_old":
|
|
215
|
-
return {
|
|
216
|
-
state: "too_old",
|
|
217
|
-
version: toolchain.version,
|
|
218
|
-
path: toolchain.path,
|
|
219
|
-
source: toolchain.source,
|
|
220
|
-
error: toolchain.error
|
|
124
|
+
/**
|
|
125
|
+
* The plugin settings this session compiles with, read per request. The
|
|
126
|
+
* settings page commits volatile values in place, so a long-lived session
|
|
127
|
+
* sees a change without being rebuilt.
|
|
128
|
+
*/
|
|
129
|
+
settings() {
|
|
130
|
+
return (this.options.resolveSettings?.() ?? {
|
|
131
|
+
typstPath: this.options.typstPath ?? "",
|
|
132
|
+
fontPaths: this.options.fontPaths ?? [],
|
|
133
|
+
packagePath: this.options.packagePath ?? "",
|
|
134
|
+
excludeDirs: this.options.excludeDirs ?? [],
|
|
135
|
+
});
|
|
136
|
+
}
|
|
137
|
+
onChange(listener) {
|
|
138
|
+
this.listeners.add(listener);
|
|
139
|
+
return () => this.listeners.delete(listener);
|
|
140
|
+
}
|
|
141
|
+
/**
|
|
142
|
+
* Await state changes until `signal` aborts, yielding once per coalesced
|
|
143
|
+
* burst (the watch stream's push side). Every yielded tick means "state
|
|
144
|
+
* changed since the last frame"; the caller re-reads `state()`.
|
|
145
|
+
*/
|
|
146
|
+
async *onChangeWaiter(signal) {
|
|
147
|
+
const queue = [];
|
|
148
|
+
let wake = null;
|
|
149
|
+
const off = this.onChange(() => {
|
|
150
|
+
queue.push(Symbol("change"));
|
|
151
|
+
wake?.();
|
|
152
|
+
wake = null;
|
|
153
|
+
});
|
|
154
|
+
const abort = () => {
|
|
155
|
+
wake?.();
|
|
156
|
+
wake = null;
|
|
221
157
|
};
|
|
222
|
-
|
|
158
|
+
signal.addEventListener("abort", abort, { once: true });
|
|
159
|
+
try {
|
|
160
|
+
while (!signal.aborted) {
|
|
161
|
+
if (queue.length === 0) {
|
|
162
|
+
await new Promise((done) => {
|
|
163
|
+
wake = done;
|
|
164
|
+
});
|
|
165
|
+
}
|
|
166
|
+
if (signal.aborted)
|
|
167
|
+
return;
|
|
168
|
+
// Coalesce the burst: one frame per drain, not per emit.
|
|
169
|
+
queue.length = 0;
|
|
170
|
+
yield Symbol("change");
|
|
171
|
+
}
|
|
172
|
+
}
|
|
173
|
+
finally {
|
|
174
|
+
off();
|
|
175
|
+
signal.removeEventListener("abort", abort);
|
|
176
|
+
}
|
|
177
|
+
}
|
|
178
|
+
emit() {
|
|
179
|
+
this.stateVersion += 1;
|
|
180
|
+
for (const listener of this.listeners)
|
|
181
|
+
listener();
|
|
182
|
+
}
|
|
183
|
+
/** The full state frame the panel renders. */
|
|
184
|
+
state() {
|
|
223
185
|
return {
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
186
|
+
version: this.stateVersion,
|
|
187
|
+
generation: this.generation,
|
|
188
|
+
previewError: this.previewError,
|
|
189
|
+
discovery: { ...this.discovery },
|
|
190
|
+
toolchain: this.toolchainView(),
|
|
191
|
+
workspace: basename(this.workspaceRoot),
|
|
192
|
+
workspaceRoot: this.workspaceRoot,
|
|
193
|
+
main: this.main,
|
|
194
|
+
candidates: this.candidates,
|
|
195
|
+
fragments: this.fragments,
|
|
196
|
+
status: this.status,
|
|
197
|
+
diagnostics: this.diagnostics,
|
|
198
|
+
diagnosticsTotal: this.diagnosticsTotal,
|
|
199
|
+
diagnosticsTruncated: this.diagnosticsTotal > this.diagnostics.length,
|
|
200
|
+
snapshot: this.current,
|
|
201
|
+
highlights: this.highlights,
|
|
202
|
+
view: this.view,
|
|
203
|
+
viewSeq: this.viewSeq,
|
|
204
|
+
setup: {
|
|
205
|
+
facts: this.facts,
|
|
206
|
+
searched: searchedDirs(process.platform, this.env, this.env.HOME ?? this.env.USERPROFILE ?? ""),
|
|
207
|
+
},
|
|
228
208
|
};
|
|
229
209
|
}
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
}
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
210
|
+
toolchainView() {
|
|
211
|
+
const toolchain = this.toolchain;
|
|
212
|
+
switch (toolchain.state) {
|
|
213
|
+
case "ready":
|
|
214
|
+
return {
|
|
215
|
+
state: "ready",
|
|
216
|
+
version: toolchain.version,
|
|
217
|
+
path: toolchain.path,
|
|
218
|
+
source: toolchain.source,
|
|
219
|
+
};
|
|
220
|
+
case "missing":
|
|
221
|
+
return { state: "missing" };
|
|
222
|
+
case "too_old":
|
|
223
|
+
return {
|
|
224
|
+
state: "too_old",
|
|
225
|
+
version: toolchain.version,
|
|
226
|
+
path: toolchain.path,
|
|
227
|
+
source: toolchain.source,
|
|
228
|
+
error: toolchain.error,
|
|
229
|
+
};
|
|
230
|
+
case "error":
|
|
231
|
+
return {
|
|
232
|
+
state: "error",
|
|
233
|
+
path: toolchain.path,
|
|
234
|
+
source: toolchain.source,
|
|
235
|
+
error: toolchain.error,
|
|
236
|
+
};
|
|
237
|
+
}
|
|
238
|
+
}
|
|
239
|
+
/**
|
|
240
|
+
* Whether this session has started, or is starting, its watch. A session
|
|
241
|
+
* that never ran reads the new settings when its first request activates
|
|
242
|
+
* it, so a settings commit must not activate one just to restart it.
|
|
243
|
+
*/
|
|
244
|
+
get active() {
|
|
245
|
+
return this.activation !== null;
|
|
246
|
+
}
|
|
247
|
+
// -------------------------------------------------------------------------
|
|
248
|
+
// Startup: toolchain, main file, watch
|
|
249
|
+
// -------------------------------------------------------------------------
|
|
250
|
+
/** Started on the first tool call or panel subscription; a no-op afterwards. */
|
|
251
|
+
activate() {
|
|
252
|
+
this.activation ??= (async () => {
|
|
253
|
+
this.realRoot = await realpath(this.workspaceRoot).catch(() => this.workspaceRoot);
|
|
254
|
+
void this.detectFacts();
|
|
255
|
+
await this.detectToolchain();
|
|
256
|
+
await this.refreshCandidates(true);
|
|
257
|
+
if (!this.main)
|
|
258
|
+
this.main = await this.selectInitialMain();
|
|
259
|
+
await this.startWatcher();
|
|
260
|
+
this.activated = true;
|
|
261
|
+
this.emit();
|
|
262
|
+
})().catch((error) => {
|
|
263
|
+
this.activation = null;
|
|
264
|
+
throw error;
|
|
265
|
+
});
|
|
266
|
+
return this.activation;
|
|
267
|
+
}
|
|
268
|
+
/** Whether a located toolchain differs from the previously cached one. */
|
|
269
|
+
toolchainChanged(before, after) {
|
|
270
|
+
return (before.state !== after.state ||
|
|
271
|
+
(before.state !== "missing" &&
|
|
272
|
+
after.state !== "missing" &&
|
|
273
|
+
before.path !== after.path) ||
|
|
274
|
+
(before.state === "ready" &&
|
|
275
|
+
after.state === "ready" &&
|
|
276
|
+
before.version !== after.version));
|
|
277
|
+
}
|
|
278
|
+
async detectToolchain(shell = true) {
|
|
279
|
+
const before = this.toolchain;
|
|
280
|
+
this.toolchain = await locateTypst({
|
|
281
|
+
setting: this.settings().typstPath,
|
|
282
|
+
env: this.env,
|
|
283
|
+
shell,
|
|
284
|
+
process: this.process,
|
|
285
|
+
cwd: this.workspaceRoot,
|
|
286
|
+
});
|
|
287
|
+
if (!this.toolchainChanged(before, this.toolchain))
|
|
288
|
+
return;
|
|
289
|
+
if (this.toolchain.state === "ready") {
|
|
290
|
+
this.log(`typst ${this.toolchain.version} at ${this.toolchain.path} (${this.toolchain.source})`);
|
|
291
|
+
}
|
|
292
|
+
else {
|
|
293
|
+
this.log(`typst not usable: ${this.toolchain.state} ${"error" in this.toolchain ? this.toolchain.error : ""}`);
|
|
294
|
+
}
|
|
295
|
+
}
|
|
296
|
+
/** Host facts are probed once (OS, arch, package managers do not change mid-session). */
|
|
297
|
+
detectFacts(force = false) {
|
|
298
|
+
if (this.facts && !force)
|
|
299
|
+
return Promise.resolve();
|
|
300
|
+
this.factsPending ??= detectFacts([cargoSpec(this.env)])
|
|
301
|
+
.then((facts) => {
|
|
302
|
+
if (JSON.stringify(facts) === JSON.stringify(this.facts))
|
|
303
|
+
return;
|
|
304
|
+
this.facts = facts;
|
|
305
|
+
this.emit();
|
|
306
|
+
})
|
|
307
|
+
.catch((error) => this.log(`could not detect host facts: ${error}`))
|
|
308
|
+
.finally(() => {
|
|
309
|
+
this.factsPending = null;
|
|
310
|
+
});
|
|
311
|
+
return this.factsPending;
|
|
312
|
+
}
|
|
313
|
+
// -------------------------------------------------------------------------
|
|
314
|
+
// Setup page: re-lookup, hand-off
|
|
315
|
+
// -------------------------------------------------------------------------
|
|
316
|
+
/**
|
|
317
|
+
* Look Typst up again (the agent or the user just installed it). A usable
|
|
318
|
+
* Typst rescans files and starts the preview. `shell: false` skips the
|
|
319
|
+
* login shell (the panel's periodic recheck uses it to avoid spawning
|
|
320
|
+
* shells frequently).
|
|
321
|
+
*/
|
|
322
|
+
async recheck(shell = true) {
|
|
323
|
+
if (this.rechecking !== null) {
|
|
324
|
+
// A caller that needs the login-shell probe must not be dropped because
|
|
325
|
+
// a shell-less panel recheck happened to be in flight.
|
|
326
|
+
if (shell)
|
|
327
|
+
this.recheckShell = true;
|
|
328
|
+
await this.rechecking;
|
|
329
|
+
return;
|
|
330
|
+
}
|
|
331
|
+
this.rechecking = this.runRecheck(shell).finally(() => {
|
|
332
|
+
this.rechecking = null;
|
|
333
|
+
});
|
|
334
|
+
await this.rechecking;
|
|
335
|
+
if (this.recheckShell) {
|
|
336
|
+
this.recheckShell = false;
|
|
337
|
+
await this.recheck(true);
|
|
338
|
+
}
|
|
339
|
+
}
|
|
340
|
+
async runRecheck(shell) {
|
|
341
|
+
await this.activate();
|
|
342
|
+
const before = this.toolchain;
|
|
343
|
+
await this.detectToolchain(shell);
|
|
344
|
+
if (!this.toolchainChanged(before, this.toolchain))
|
|
345
|
+
return;
|
|
346
|
+
if (this.toolchain.state === "ready") {
|
|
347
|
+
await this.stopWatcher();
|
|
348
|
+
await this.refreshCandidates(true);
|
|
349
|
+
if (!this.main)
|
|
350
|
+
this.main = await this.selectInitialMain();
|
|
351
|
+
await this.startWatcher();
|
|
352
|
+
}
|
|
353
|
+
this.emit();
|
|
270
354
|
}
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
this.rechecking ??= (async () => {
|
|
295
|
-
await this.activate();
|
|
296
|
-
const before = this.toolchain;
|
|
297
|
-
await this.detectToolchain(shell);
|
|
298
|
-
const changed = before.state !== this.toolchain.state || before.state !== "missing" && this.toolchain.state !== "missing" && before.path !== this.toolchain.path || before.state === "ready" && this.toolchain.state === "ready" && before.version !== this.toolchain.version;
|
|
299
|
-
if (!changed) return;
|
|
300
|
-
if (this.toolchain.state === "ready") {
|
|
355
|
+
/** While the panel subscribes and Typst is unusable, re-lookup every few seconds; the preview starts by itself once Typst runs. */
|
|
356
|
+
watchSetup(enabled) {
|
|
357
|
+
this.setupSubscribers = Math.max(0, this.setupSubscribers + (enabled ? 1 : -1));
|
|
358
|
+
if (enabled && !this.setupTimer && !this.closed) {
|
|
359
|
+
this.setupTicks = 0;
|
|
360
|
+
this.setupTimer = setInterval(() => {
|
|
361
|
+
if (this.toolchain.state === "ready" || this.rechecking)
|
|
362
|
+
return;
|
|
363
|
+
const shell = ++this.setupTicks % LIMITS.setupShellEvery === 0;
|
|
364
|
+
if (shell)
|
|
365
|
+
void this.detectFacts(true);
|
|
366
|
+
void this.recheck(shell).catch((error) => this.log(`recheck failed: ${error}`));
|
|
367
|
+
}, LIMITS.setupWatchMs);
|
|
368
|
+
this.setupTimer.unref?.();
|
|
369
|
+
}
|
|
370
|
+
else if (!enabled && this.setupSubscribers === 0 && this.setupTimer) {
|
|
371
|
+
clearInterval(this.setupTimer);
|
|
372
|
+
this.setupTimer = null;
|
|
373
|
+
}
|
|
374
|
+
}
|
|
375
|
+
/** Locate typst again, rescan files, and restart the watch (the panel's restart button). */
|
|
376
|
+
async restart() {
|
|
377
|
+
await this.activate();
|
|
301
378
|
await this.stopWatcher();
|
|
379
|
+
await this.detectToolchain();
|
|
302
380
|
await this.refreshCandidates(true);
|
|
303
|
-
if (!this.main)
|
|
381
|
+
if (!this.main)
|
|
382
|
+
this.main = await this.selectInitialMain();
|
|
304
383
|
await this.startWatcher();
|
|
305
|
-
|
|
306
|
-
|
|
307
|
-
|
|
308
|
-
|
|
309
|
-
|
|
310
|
-
|
|
311
|
-
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
|
|
323
|
-
|
|
324
|
-
|
|
325
|
-
|
|
326
|
-
|
|
327
|
-
|
|
328
|
-
|
|
329
|
-
|
|
330
|
-
|
|
331
|
-
|
|
384
|
+
this.emit();
|
|
385
|
+
}
|
|
386
|
+
/** Refresh complete discovery; indexed absence never proves the selected main disappeared. */
|
|
387
|
+
async refreshCandidates(force = false) {
|
|
388
|
+
if (!force && Date.now() - this.candidatesAt < 2_000)
|
|
389
|
+
return;
|
|
390
|
+
const mainAtStart = this.main;
|
|
391
|
+
if (this.indexingPromise && this.indexing)
|
|
392
|
+
await this.indexingPromise;
|
|
393
|
+
else
|
|
394
|
+
await this.discover(this.discovery.includeExcluded);
|
|
395
|
+
if (mainAtStart && !(await this.validMain(mainAtStart))) {
|
|
396
|
+
// A concurrent setMain may have chosen a different main while discovery
|
|
397
|
+
// was in flight; never overwrite that choice with this refresh's view.
|
|
398
|
+
if (this.main !== mainAtStart)
|
|
399
|
+
return;
|
|
400
|
+
await this.stopWatcher();
|
|
401
|
+
this.candidates = this.candidates.filter((path) => path !== mainAtStart);
|
|
402
|
+
this.main = chooseMain(this.candidates, null);
|
|
403
|
+
this.resetPreview();
|
|
404
|
+
await this.startWatcher();
|
|
405
|
+
}
|
|
406
|
+
else if (!this.main && this.activated) {
|
|
407
|
+
this.main = await this.selectInitialMain();
|
|
408
|
+
await this.startWatcher();
|
|
409
|
+
}
|
|
410
|
+
this.emit();
|
|
332
411
|
}
|
|
333
|
-
|
|
334
|
-
|
|
335
|
-
|
|
336
|
-
|
|
337
|
-
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
|
|
341
|
-
|
|
342
|
-
|
|
343
|
-
|
|
344
|
-
|
|
345
|
-
|
|
346
|
-
|
|
347
|
-
|
|
348
|
-
else await this.discover(this.discovery.includeExcluded);
|
|
349
|
-
if (this.main && !await this.validMain(this.main)) {
|
|
350
|
-
await this.stopWatcher();
|
|
351
|
-
this.candidates = this.candidates.filter((path) => path !== this.main);
|
|
352
|
-
this.main = chooseMain(this.candidates, null);
|
|
353
|
-
this.resetPreview();
|
|
354
|
-
await this.startWatcher();
|
|
355
|
-
} else if (!this.main && this.activated) {
|
|
356
|
-
this.main = await this.selectInitialMain();
|
|
357
|
-
await this.startWatcher();
|
|
412
|
+
async validMain(path) {
|
|
413
|
+
try {
|
|
414
|
+
return (await stat(await this.insideWorkspace(path))).isFile();
|
|
415
|
+
}
|
|
416
|
+
catch (error) {
|
|
417
|
+
const code = error.code;
|
|
418
|
+
if (code === "ENOENT" ||
|
|
419
|
+
code === "ENOTDIR" ||
|
|
420
|
+
code === TYPST_PATH_OUTSIDE_WORKSPACE)
|
|
421
|
+
return false;
|
|
422
|
+
// A transient stat failure must not silently discard the main file and
|
|
423
|
+
// clear the preview; keep the choice and try again next refresh.
|
|
424
|
+
this.log(`Could not inspect ${path}: ${String(error)}`);
|
|
425
|
+
return true;
|
|
426
|
+
}
|
|
358
427
|
}
|
|
359
|
-
|
|
360
|
-
|
|
361
|
-
|
|
362
|
-
|
|
363
|
-
|
|
364
|
-
} catch {
|
|
365
|
-
return false;
|
|
428
|
+
async selectInitialMain() {
|
|
429
|
+
const remembered = await this.remembered();
|
|
430
|
+
return remembered && (await this.validMain(remembered))
|
|
431
|
+
? remembered
|
|
432
|
+
: chooseMain(this.candidates, null);
|
|
366
433
|
}
|
|
367
|
-
|
|
368
|
-
|
|
369
|
-
|
|
370
|
-
|
|
371
|
-
|
|
372
|
-
|
|
373
|
-
|
|
374
|
-
|
|
375
|
-
this.indexing = controller;
|
|
376
|
-
const stopped = signal ? AbortSignal.any([signal, controller.signal]) : controller.signal;
|
|
377
|
-
this.discovery = {
|
|
378
|
-
scanning: true,
|
|
379
|
-
includeExcluded,
|
|
380
|
-
visited: 0,
|
|
381
|
-
errors: []
|
|
382
|
-
};
|
|
383
|
-
this.emit();
|
|
384
|
-
const operation = (async () => {
|
|
385
|
-
try {
|
|
386
|
-
for await (const batch of indexTypFiles(
|
|
387
|
-
this.workspaceRoot,
|
|
388
|
-
includeExcluded,
|
|
389
|
-
stopped
|
|
390
|
-
)) {
|
|
391
|
-
if (this.closed || stopped.aborted || this.indexing !== controller)
|
|
392
|
-
return;
|
|
393
|
-
this.candidates = [
|
|
394
|
-
.../* @__PURE__ */ new Set([...batch.files, ...this.main ? [this.main] : []])
|
|
395
|
-
];
|
|
396
|
-
this.discovery = {
|
|
434
|
+
async discover(includeExcluded, signal) {
|
|
435
|
+
this.indexing?.abort();
|
|
436
|
+
const controller = new AbortController();
|
|
437
|
+
this.indexing = controller;
|
|
438
|
+
const stopped = signal
|
|
439
|
+
? AbortSignal.any([signal, controller.signal])
|
|
440
|
+
: controller.signal;
|
|
441
|
+
this.discovery = {
|
|
397
442
|
scanning: true,
|
|
398
443
|
includeExcluded,
|
|
399
|
-
visited:
|
|
400
|
-
errors:
|
|
401
|
-
|
|
402
|
-
|
|
403
|
-
|
|
404
|
-
|
|
405
|
-
|
|
406
|
-
|
|
407
|
-
|
|
408
|
-
|
|
409
|
-
|
|
410
|
-
|
|
411
|
-
|
|
412
|
-
|
|
413
|
-
|
|
414
|
-
|
|
415
|
-
|
|
416
|
-
|
|
417
|
-
|
|
418
|
-
|
|
419
|
-
|
|
420
|
-
|
|
421
|
-
|
|
422
|
-
|
|
423
|
-
|
|
424
|
-
|
|
425
|
-
|
|
426
|
-
|
|
427
|
-
|
|
428
|
-
|
|
429
|
-
|
|
430
|
-
const fontPaths = await this.fontPaths();
|
|
431
|
-
const watcher = new Watcher(
|
|
432
|
-
{
|
|
433
|
-
typst: this.toolchain.path,
|
|
434
|
-
version: this.toolchain.version,
|
|
435
|
-
cwd: this.workspaceRoot,
|
|
436
|
-
root: this.workspaceRoot,
|
|
437
|
-
fontPaths,
|
|
438
|
-
main: this.main,
|
|
439
|
-
buildDir: this.buildDir,
|
|
440
|
-
env: this.env,
|
|
441
|
-
toFile: (path) => this.displayPath(path),
|
|
442
|
-
log: this.log
|
|
443
|
-
},
|
|
444
|
-
{
|
|
445
|
-
compiling: (startedAt) => {
|
|
446
|
-
if (this.watcher !== watcher) return;
|
|
447
|
-
this.compileToken++;
|
|
448
|
-
this.compilingSince = startedAt;
|
|
449
|
-
this.status = {
|
|
450
|
-
...this.status,
|
|
451
|
-
phase: "compiling",
|
|
452
|
-
error: void 0
|
|
453
|
-
};
|
|
454
|
-
this.emit();
|
|
455
|
-
},
|
|
456
|
-
finished: async (result) => {
|
|
457
|
-
if (this.watcher !== watcher) return;
|
|
458
|
-
await this.finish(
|
|
459
|
-
result.outcome,
|
|
460
|
-
result.diagnostics,
|
|
461
|
-
result.durationMs,
|
|
462
|
-
result.bytes,
|
|
463
|
-
result.previewError
|
|
464
|
-
);
|
|
465
|
-
},
|
|
466
|
-
fatal: (message) => {
|
|
467
|
-
if (this.watcher !== watcher) return;
|
|
468
|
-
void this.finish("error", [
|
|
469
|
-
{
|
|
470
|
-
severity: "error",
|
|
471
|
-
message,
|
|
472
|
-
location: null,
|
|
473
|
-
hints: [],
|
|
474
|
-
trace: []
|
|
444
|
+
visited: 0,
|
|
445
|
+
errors: [],
|
|
446
|
+
};
|
|
447
|
+
this.emit();
|
|
448
|
+
const operation = (async () => {
|
|
449
|
+
const found = new Set();
|
|
450
|
+
let lastEmit = 0;
|
|
451
|
+
try {
|
|
452
|
+
for await (const batch of indexTypFiles(this.workspaceRoot, includeExcluded, stopped, this.settings().excludeDirs)) {
|
|
453
|
+
if (this.closed || stopped.aborted || this.indexing !== controller)
|
|
454
|
+
return;
|
|
455
|
+
for (const file of batch.added)
|
|
456
|
+
found.add(file);
|
|
457
|
+
if (this.main)
|
|
458
|
+
found.add(this.main);
|
|
459
|
+
const now = Date.now();
|
|
460
|
+
if (batch.done || now - lastEmit >= LIMITS.notifyMs) {
|
|
461
|
+
lastEmit = now;
|
|
462
|
+
this.candidates = [...found];
|
|
463
|
+
this.discovery = {
|
|
464
|
+
scanning: true,
|
|
465
|
+
includeExcluded,
|
|
466
|
+
visited: batch.visited,
|
|
467
|
+
errors: batch.errors,
|
|
468
|
+
};
|
|
469
|
+
this.emit();
|
|
470
|
+
}
|
|
471
|
+
}
|
|
472
|
+
this.candidates = [...found];
|
|
473
|
+
this.candidatesAt = Date.now();
|
|
474
|
+
this.emit();
|
|
475
475
|
}
|
|
476
|
-
|
|
477
|
-
|
|
478
|
-
|
|
479
|
-
|
|
480
|
-
|
|
481
|
-
|
|
482
|
-
|
|
483
|
-
|
|
484
|
-
|
|
485
|
-
|
|
486
|
-
|
|
487
|
-
|
|
488
|
-
|
|
489
|
-
|
|
490
|
-
|
|
491
|
-
|
|
492
|
-
|
|
493
|
-
|
|
494
|
-
this.restartTimer = null;
|
|
495
|
-
void this.startWatcher().then(() => this.emit());
|
|
496
|
-
}, 1e3);
|
|
497
|
-
}
|
|
498
|
-
}
|
|
499
|
-
}
|
|
500
|
-
);
|
|
501
|
-
this.watcher = watcher;
|
|
502
|
-
this.watcherStartedAt = Date.now();
|
|
503
|
-
this.compilingSince = null;
|
|
504
|
-
this.status = { ...this.status, phase: "starting", error: void 0 };
|
|
505
|
-
try {
|
|
506
|
-
watcher.start();
|
|
507
|
-
} catch (error) {
|
|
508
|
-
this.watcher = null;
|
|
509
|
-
this.status = {
|
|
510
|
-
...this.status,
|
|
511
|
-
phase: "crashed",
|
|
512
|
-
error: error instanceof Error ? error.message : String(error)
|
|
513
|
-
};
|
|
476
|
+
catch (error) {
|
|
477
|
+
// A newer discover supersedes this one; that is normal and must not
|
|
478
|
+
// reject the caller (refreshCandidates, setMain, restart) with an
|
|
479
|
+
// AbortError it did not cause.
|
|
480
|
+
if (stopped.aborted || this.indexing !== controller)
|
|
481
|
+
return;
|
|
482
|
+
throw error;
|
|
483
|
+
}
|
|
484
|
+
finally {
|
|
485
|
+
if (this.indexing === controller) {
|
|
486
|
+
this.indexing = null;
|
|
487
|
+
this.discovery = { ...this.discovery, scanning: false };
|
|
488
|
+
this.emit();
|
|
489
|
+
}
|
|
490
|
+
}
|
|
491
|
+
})();
|
|
492
|
+
this.indexingPromise = operation;
|
|
493
|
+
return operation;
|
|
514
494
|
}
|
|
515
|
-
|
|
516
|
-
|
|
517
|
-
|
|
518
|
-
|
|
519
|
-
|
|
520
|
-
if (this.restartTimer) clearTimeout(this.restartTimer);
|
|
521
|
-
this.restartTimer = null;
|
|
522
|
-
await watcher?.stop();
|
|
523
|
-
}
|
|
524
|
-
async makeBuildDir() {
|
|
525
|
-
const base = join(
|
|
526
|
-
this.options.dataDir ?? join(tmpdir(), "dsh-typst"),
|
|
527
|
-
"build"
|
|
528
|
-
);
|
|
529
|
-
await mkdir(base, { recursive: true });
|
|
530
|
-
await reapOrphans(base, this.log);
|
|
531
|
-
const dir = join(base, `${process.pid}-${randomBytes(4).toString("hex")}`);
|
|
532
|
-
await mkdir(dir, { recursive: true });
|
|
533
|
-
return dir;
|
|
534
|
-
}
|
|
535
|
-
async finish(outcome, diagnostics, durationMs, bytes, previewFailure) {
|
|
536
|
-
const generation = this.generation;
|
|
537
|
-
const token = this.compileToken;
|
|
538
|
-
const startedAt = this.compilingSince ?? Date.now();
|
|
539
|
-
const diagnosticsWithExcerpts = await Promise.all(
|
|
540
|
-
diagnostics.map((entry) => this.withExcerpt(entry))
|
|
541
|
-
);
|
|
542
|
-
if (generation !== this.generation || token !== this.compileToken || this.closed)
|
|
543
|
-
return;
|
|
544
|
-
const run = this.status.run + 1;
|
|
545
|
-
if (outcome !== "error") {
|
|
546
|
-
this.previewError = previewFailure ?? null;
|
|
547
|
-
if (bytes) await this.addSnapshot(bytes, generation, token, run);
|
|
548
|
-
else
|
|
549
|
-
this.previewError ??= "Typst did not produce preview bytes. Retry the preview.";
|
|
495
|
+
startWatcher() {
|
|
496
|
+
this.startingWatcher ??= this.performStartWatcher().finally(() => {
|
|
497
|
+
this.startingWatcher = null;
|
|
498
|
+
});
|
|
499
|
+
return this.startingWatcher;
|
|
550
500
|
}
|
|
551
|
-
|
|
552
|
-
|
|
553
|
-
|
|
554
|
-
|
|
555
|
-
|
|
556
|
-
|
|
557
|
-
|
|
558
|
-
|
|
559
|
-
|
|
560
|
-
|
|
561
|
-
|
|
562
|
-
|
|
563
|
-
|
|
564
|
-
|
|
565
|
-
|
|
566
|
-
|
|
567
|
-
|
|
568
|
-
|
|
569
|
-
|
|
570
|
-
|
|
571
|
-
|
|
572
|
-
|
|
573
|
-
|
|
574
|
-
|
|
575
|
-
|
|
576
|
-
|
|
577
|
-
|
|
578
|
-
|
|
579
|
-
|
|
580
|
-
|
|
581
|
-
|
|
582
|
-
|
|
583
|
-
|
|
584
|
-
|
|
585
|
-
|
|
586
|
-
|
|
587
|
-
|
|
588
|
-
|
|
589
|
-
|
|
590
|
-
|
|
591
|
-
|
|
592
|
-
|
|
501
|
+
async performStartWatcher() {
|
|
502
|
+
await this.stopPromise;
|
|
503
|
+
if (this.closed ||
|
|
504
|
+
this.watcher ||
|
|
505
|
+
this.toolchain.state !== "ready" ||
|
|
506
|
+
!this.main) {
|
|
507
|
+
if (!this.watcher)
|
|
508
|
+
this.status = { phase: "idle", run: this.status.run };
|
|
509
|
+
return;
|
|
510
|
+
}
|
|
511
|
+
if (!this.buildDir)
|
|
512
|
+
this.buildDir = await this.makeBuildDir();
|
|
513
|
+
if (this.closed ||
|
|
514
|
+
this.watcher ||
|
|
515
|
+
!this.main ||
|
|
516
|
+
this.toolchain.state !== "ready")
|
|
517
|
+
return;
|
|
518
|
+
const settings = this.settings();
|
|
519
|
+
const fontPaths = await this.fontPaths(settings.fontPaths);
|
|
520
|
+
const watcher = new Watcher({
|
|
521
|
+
typst: this.toolchain.path,
|
|
522
|
+
version: this.toolchain.version,
|
|
523
|
+
cwd: this.workspaceRoot,
|
|
524
|
+
root: this.workspaceRoot,
|
|
525
|
+
fontPaths,
|
|
526
|
+
packagePath: settings.packagePath || undefined,
|
|
527
|
+
main: this.main,
|
|
528
|
+
buildDir: this.buildDir,
|
|
529
|
+
process: this.process,
|
|
530
|
+
env: this.env,
|
|
531
|
+
toFile: (path) => this.displayPath(path),
|
|
532
|
+
log: this.log,
|
|
533
|
+
}, {
|
|
534
|
+
compiling: (startedAt) => {
|
|
535
|
+
if (this.watcher !== watcher)
|
|
536
|
+
return;
|
|
537
|
+
this.compileToken++;
|
|
538
|
+
this.compilingSince = startedAt;
|
|
539
|
+
this.status = {
|
|
540
|
+
...this.status,
|
|
541
|
+
phase: "compiling",
|
|
542
|
+
error: undefined,
|
|
543
|
+
};
|
|
544
|
+
this.emit();
|
|
545
|
+
},
|
|
546
|
+
finished: async (result) => {
|
|
547
|
+
if (this.watcher !== watcher)
|
|
548
|
+
return;
|
|
549
|
+
await this.finish(result.outcome, result.diagnostics, result.durationMs, result.bytes, result.previewError);
|
|
550
|
+
},
|
|
551
|
+
fatal: (message) => {
|
|
552
|
+
if (this.watcher !== watcher)
|
|
553
|
+
return;
|
|
554
|
+
void this.finish("error", [
|
|
555
|
+
{
|
|
556
|
+
severity: "error",
|
|
557
|
+
message,
|
|
558
|
+
location: null,
|
|
559
|
+
hints: [],
|
|
560
|
+
trace: [],
|
|
561
|
+
},
|
|
562
|
+
]);
|
|
563
|
+
},
|
|
564
|
+
exit: ({ code, signal, tail, expected }) => {
|
|
565
|
+
if (this.watcher !== watcher)
|
|
566
|
+
return;
|
|
567
|
+
this.watcher = null;
|
|
568
|
+
if (expected || this.closed)
|
|
569
|
+
return;
|
|
570
|
+
this.log(`typst watch exited (code ${code}, signal ${signal}): ${tail}`);
|
|
571
|
+
this.status = {
|
|
572
|
+
...this.status,
|
|
573
|
+
phase: "crashed",
|
|
574
|
+
error: tail.split("\n").filter(Boolean).slice(-6).join("\n") ||
|
|
575
|
+
`typst exited with code ${code}`,
|
|
576
|
+
};
|
|
577
|
+
this.wakeWaiters();
|
|
578
|
+
this.emit();
|
|
579
|
+
if (Date.now() - this.watcherStartedAt > 10_000 &&
|
|
580
|
+
!this.restartTimer) {
|
|
581
|
+
this.restartTimer = setTimeout(() => {
|
|
582
|
+
this.restartTimer = null;
|
|
583
|
+
void this.startWatcher().then(() => this.emit());
|
|
584
|
+
}, 1_000);
|
|
585
|
+
}
|
|
586
|
+
},
|
|
587
|
+
});
|
|
588
|
+
this.watcher = watcher;
|
|
589
|
+
this.watcherStartedAt = Date.now();
|
|
590
|
+
this.compilingSince = null;
|
|
591
|
+
this.status = { ...this.status, phase: "starting", error: undefined };
|
|
592
|
+
try {
|
|
593
|
+
watcher.start();
|
|
594
|
+
}
|
|
595
|
+
catch (error) {
|
|
596
|
+
this.watcher = null;
|
|
597
|
+
this.status = {
|
|
598
|
+
...this.status,
|
|
599
|
+
phase: "crashed",
|
|
600
|
+
error: error instanceof Error ? error.message : String(error),
|
|
601
|
+
};
|
|
602
|
+
}
|
|
603
|
+
}
|
|
604
|
+
stopWatcher() {
|
|
605
|
+
const watcher = this.watcher;
|
|
606
|
+
this.watcher = null;
|
|
607
|
+
if (this.restartTimer)
|
|
608
|
+
clearTimeout(this.restartTimer);
|
|
609
|
+
this.restartTimer = null;
|
|
610
|
+
this.compileToken++;
|
|
611
|
+
if (!watcher)
|
|
612
|
+
return this.stopPromise;
|
|
613
|
+
this.retiring = watcher;
|
|
614
|
+
const done = watcher.stop().finally(() => {
|
|
615
|
+
if (this.retiring === watcher)
|
|
616
|
+
this.retiring = null;
|
|
617
|
+
});
|
|
618
|
+
this.stopPromise = done;
|
|
619
|
+
return done;
|
|
593
620
|
}
|
|
594
|
-
|
|
595
|
-
|
|
596
|
-
|
|
597
|
-
|
|
598
|
-
|
|
599
|
-
|
|
600
|
-
|
|
601
|
-
|
|
602
|
-
|
|
603
|
-
|
|
604
|
-
|
|
605
|
-
|
|
606
|
-
|
|
607
|
-
|
|
608
|
-
|
|
609
|
-
|
|
610
|
-
|
|
611
|
-
|
|
612
|
-
|
|
613
|
-
|
|
614
|
-
|
|
615
|
-
|
|
616
|
-
|
|
617
|
-
|
|
618
|
-
|
|
619
|
-
|
|
620
|
-
|
|
621
|
-
|
|
622
|
-
|
|
623
|
-
|
|
624
|
-
|
|
625
|
-
|
|
626
|
-
|
|
627
|
-
|
|
628
|
-
|
|
629
|
-
|
|
630
|
-
|
|
631
|
-
|
|
632
|
-
|
|
633
|
-
|
|
634
|
-
|
|
635
|
-
|
|
636
|
-
|
|
637
|
-
|
|
638
|
-
|
|
639
|
-
|
|
640
|
-
|
|
641
|
-
|
|
642
|
-
|
|
643
|
-
|
|
644
|
-
|
|
645
|
-
|
|
621
|
+
async makeBuildDir() {
|
|
622
|
+
return makeBuildDir(this.options.dataDir ?? join(tmpdir(), "dsh-typst"), this.log);
|
|
623
|
+
}
|
|
624
|
+
async finish(outcome, diagnostics, durationMs, bytes, previewFailure) {
|
|
625
|
+
const generation = this.generation;
|
|
626
|
+
const token = this.compileToken;
|
|
627
|
+
const startedAt = this.compilingSince ?? Date.now();
|
|
628
|
+
const shown = diagnostics.slice(0, LIMITS.diagnostics);
|
|
629
|
+
const diagnosticsWithExcerpts = await Promise.all(shown.map((entry) => this.withExcerpt(entry)));
|
|
630
|
+
if (generation !== this.generation ||
|
|
631
|
+
token !== this.compileToken ||
|
|
632
|
+
this.closed)
|
|
633
|
+
return;
|
|
634
|
+
const run = this.status.run + 1;
|
|
635
|
+
if (outcome !== "error") {
|
|
636
|
+
this.previewError = previewFailure ?? null;
|
|
637
|
+
if (bytes)
|
|
638
|
+
await this.addSnapshot(bytes, generation, token, run);
|
|
639
|
+
else
|
|
640
|
+
this.previewError ??=
|
|
641
|
+
"Typst did not produce preview bytes. Retry the preview.";
|
|
642
|
+
}
|
|
643
|
+
if (generation !== this.generation ||
|
|
644
|
+
token !== this.compileToken ||
|
|
645
|
+
this.closed)
|
|
646
|
+
return;
|
|
647
|
+
this.finishedStartedAt = startedAt;
|
|
648
|
+
this.finishGeneration = generation;
|
|
649
|
+
this.compiledInputs = (await this.inputsModifiedAt()).signature;
|
|
650
|
+
this.compilingSince = null;
|
|
651
|
+
this.diagnostics = diagnosticsWithExcerpts;
|
|
652
|
+
this.diagnosticsTotal = diagnostics.length;
|
|
653
|
+
this.status = {
|
|
654
|
+
phase: outcome,
|
|
655
|
+
run: this.status.run + 1,
|
|
656
|
+
durationMs,
|
|
657
|
+
finishedAt: Date.now(),
|
|
658
|
+
};
|
|
659
|
+
// The fragment set belongs to the state a waiter reads, so it is settled
|
|
660
|
+
// before the waiters wake: a caller that waits for the compile must see
|
|
661
|
+
// the document's fragments in the frame it gets.
|
|
662
|
+
if (outcome !== "error")
|
|
663
|
+
await this.refreshFragments(generation, token);
|
|
664
|
+
if (generation !== this.generation ||
|
|
665
|
+
token !== this.compileToken ||
|
|
666
|
+
this.closed)
|
|
667
|
+
return;
|
|
668
|
+
// With no highlights there is nothing to extract: wake immediately. With
|
|
669
|
+
// highlights, the relocated identities are part of the state a waiter
|
|
670
|
+
// reads, so finish that before waking.
|
|
671
|
+
if (this.current && this.highlights.length > 0) {
|
|
672
|
+
await this.relocateHighlights(this.current.seq);
|
|
673
|
+
if (generation !== this.generation ||
|
|
674
|
+
token !== this.compileToken ||
|
|
675
|
+
this.closed)
|
|
676
|
+
return;
|
|
677
|
+
}
|
|
678
|
+
this.wakeWaiters();
|
|
679
|
+
this.finishVersion++;
|
|
680
|
+
this.emit();
|
|
681
|
+
void this.refreshCandidates().catch((error) => this.log(`Discovery failed: ${String(error)}`));
|
|
646
682
|
}
|
|
647
|
-
|
|
648
|
-
|
|
649
|
-
|
|
650
|
-
|
|
651
|
-
|
|
652
|
-
|
|
653
|
-
|
|
654
|
-
|
|
655
|
-
|
|
656
|
-
|
|
683
|
+
/**
|
|
684
|
+
* Recompute the fragment set from typst's dependency report.
|
|
685
|
+
*
|
|
686
|
+
* typst names every file it loaded for the current root, so the candidates
|
|
687
|
+
* among them other than the main file are exactly the fragments the
|
|
688
|
+
* document pulls in. The report is empty until the first successful
|
|
689
|
+
* compile, and the previous set is kept rather than emptied, so the panel
|
|
690
|
+
* does not lose the distinction mid-session.
|
|
691
|
+
*/
|
|
692
|
+
async refreshFragments(generation, token) {
|
|
693
|
+
const deps = (await this.watcher?.deps().catch(() => [])) ?? [];
|
|
694
|
+
if (deps.length === 0)
|
|
695
|
+
return;
|
|
696
|
+
// typst reports the paths it resolved, and a resolved path is the real
|
|
697
|
+
// one: both sides are resolved before they are compared.
|
|
698
|
+
const loaded = new Set(await Promise.all(deps.map((path) => realish(path))));
|
|
699
|
+
const fragments = [];
|
|
700
|
+
for (const candidate of this.candidates) {
|
|
701
|
+
if (candidate === this.main)
|
|
702
|
+
continue;
|
|
703
|
+
const absolute = resolve(this.workspaceRoot, candidate);
|
|
704
|
+
if (loaded.has(await realish(absolute)))
|
|
705
|
+
fragments.push(candidate);
|
|
706
|
+
}
|
|
707
|
+
if (generation !== this.generation ||
|
|
708
|
+
token !== this.compileToken ||
|
|
709
|
+
this.closed ||
|
|
710
|
+
fragments.join("\n") === this.fragments.join("\n"))
|
|
711
|
+
return;
|
|
712
|
+
this.fragments = fragments;
|
|
713
|
+
this.emit();
|
|
657
714
|
}
|
|
658
|
-
|
|
659
|
-
|
|
660
|
-
|
|
661
|
-
}
|
|
662
|
-
setMain(path) {
|
|
663
|
-
const operation = this.mainQueue.then(() => this.selectMain(path));
|
|
664
|
-
this.mainQueue = operation.catch(() => void 0);
|
|
665
|
-
return operation;
|
|
666
|
-
}
|
|
667
|
-
async selectMain(path) {
|
|
668
|
-
await this.activate();
|
|
669
|
-
const absolute = await this.insideWorkspace(path);
|
|
670
|
-
if (extname(absolute) !== ".typ") {
|
|
671
|
-
throw new TypstError(
|
|
672
|
-
`${path} is not a .typ file.`,
|
|
673
|
-
TYPST_INVALID_ARGUMENT
|
|
674
|
-
);
|
|
715
|
+
wakeWaiters() {
|
|
716
|
+
for (const wake of this.finishWaiters)
|
|
717
|
+
wake();
|
|
675
718
|
}
|
|
676
|
-
|
|
677
|
-
|
|
678
|
-
|
|
679
|
-
|
|
680
|
-
|
|
681
|
-
|
|
682
|
-
|
|
683
|
-
|
|
684
|
-
|
|
685
|
-
|
|
686
|
-
|
|
687
|
-
|
|
688
|
-
|
|
719
|
+
waitForFinish(ms, signal) {
|
|
720
|
+
return new Promise((done) => {
|
|
721
|
+
let settled = false;
|
|
722
|
+
let timer;
|
|
723
|
+
const finish = (value) => {
|
|
724
|
+
if (settled)
|
|
725
|
+
return;
|
|
726
|
+
settled = true;
|
|
727
|
+
clearTimeout(timer);
|
|
728
|
+
this.finishWaiters.delete(wake);
|
|
729
|
+
signal?.removeEventListener("abort", onAbort);
|
|
730
|
+
done(value);
|
|
731
|
+
};
|
|
732
|
+
const wake = () => finish(true);
|
|
733
|
+
const onAbort = () => finish(false);
|
|
734
|
+
timer = setTimeout(() => finish(false), ms);
|
|
735
|
+
timer.unref?.();
|
|
736
|
+
this.finishWaiters.add(wake);
|
|
737
|
+
if (signal !== undefined) {
|
|
738
|
+
if (signal.aborted)
|
|
739
|
+
finish(false);
|
|
740
|
+
else
|
|
741
|
+
signal.addEventListener("abort", onAbort, { once: true });
|
|
742
|
+
}
|
|
743
|
+
});
|
|
689
744
|
}
|
|
690
|
-
|
|
691
|
-
|
|
692
|
-
|
|
693
|
-
|
|
694
|
-
|
|
695
|
-
|
|
696
|
-
|
|
697
|
-
|
|
698
|
-
|
|
699
|
-
|
|
700
|
-
|
|
701
|
-
|
|
702
|
-
|
|
703
|
-
|
|
704
|
-
|
|
705
|
-
|
|
706
|
-
);
|
|
745
|
+
resetPreview() {
|
|
746
|
+
this.generation++;
|
|
747
|
+
this.compileToken++;
|
|
748
|
+
this.finishGeneration = 0;
|
|
749
|
+
this.compiledInputs = null;
|
|
750
|
+
this.previewError = null;
|
|
751
|
+
this.snapshots.clear();
|
|
752
|
+
this.pagesCache.clear();
|
|
753
|
+
this.excerptCache.clear();
|
|
754
|
+
this.current = null;
|
|
755
|
+
this.diagnostics = [];
|
|
756
|
+
this.diagnosticsTotal = 0;
|
|
757
|
+
this.highlights = [];
|
|
758
|
+
this.fragments = [];
|
|
759
|
+
this.view = null;
|
|
760
|
+
this.status = { phase: "idle", run: this.status.run };
|
|
707
761
|
}
|
|
708
|
-
|
|
709
|
-
|
|
710
|
-
|
|
711
|
-
|
|
712
|
-
|
|
762
|
+
// -------------------------------------------------------------------------
|
|
763
|
+
// Main file
|
|
764
|
+
// -------------------------------------------------------------------------
|
|
765
|
+
get mainsFile() {
|
|
766
|
+
return this.options.dataDir
|
|
767
|
+
? join(this.options.dataDir, "main-files.json")
|
|
768
|
+
: null;
|
|
713
769
|
}
|
|
714
|
-
|
|
715
|
-
|
|
716
|
-
|
|
717
|
-
|
|
718
|
-
|
|
770
|
+
async remembered() {
|
|
771
|
+
const file = this.mainsFile;
|
|
772
|
+
if (!file)
|
|
773
|
+
return null;
|
|
774
|
+
try {
|
|
775
|
+
const saved = JSON.parse(await readFile(file, "utf8"));
|
|
776
|
+
if (typeof saved === "object" && saved !== null) {
|
|
777
|
+
const value = saved[this.realRoot ?? this.workspaceRoot];
|
|
778
|
+
return typeof value === "string" ? value : null;
|
|
779
|
+
}
|
|
780
|
+
return null;
|
|
781
|
+
}
|
|
782
|
+
catch {
|
|
783
|
+
return null;
|
|
784
|
+
}
|
|
719
785
|
}
|
|
720
|
-
|
|
721
|
-
|
|
722
|
-
|
|
723
|
-
|
|
724
|
-
|
|
786
|
+
async remember(main) {
|
|
787
|
+
const file = this.mainsFile;
|
|
788
|
+
if (!file)
|
|
789
|
+
return;
|
|
790
|
+
await mkdir(dirname(file), { recursive: true, mode: 0o700 });
|
|
791
|
+
await withFileLock(file, async () => {
|
|
792
|
+
let saved = {};
|
|
793
|
+
try {
|
|
794
|
+
const parsed = JSON.parse(await readFile(file, "utf8"));
|
|
795
|
+
if (typeof parsed === "object" && parsed !== null)
|
|
796
|
+
saved = parsed;
|
|
797
|
+
}
|
|
798
|
+
catch {
|
|
799
|
+
// First save.
|
|
800
|
+
}
|
|
801
|
+
saved[this.realRoot ?? this.workspaceRoot] = main;
|
|
802
|
+
await writeFileAtomic(file, JSON.stringify(saved, null, 2), {
|
|
803
|
+
mode: 0o600,
|
|
804
|
+
dirMode: 0o700,
|
|
805
|
+
});
|
|
806
|
+
}, { waitMs: 2_000 });
|
|
725
807
|
}
|
|
726
|
-
|
|
727
|
-
|
|
728
|
-
|
|
729
|
-
|
|
730
|
-
if (!files.length) {
|
|
731
|
-
files = [this.main, ...this.candidates].filter((path) => typeof path === "string").map((path) => resolve(this.workspaceRoot, path));
|
|
808
|
+
setMain(path) {
|
|
809
|
+
const operation = this.mainQueue.then(() => this.selectMain(path));
|
|
810
|
+
this.mainQueue = operation.catch(() => undefined);
|
|
811
|
+
return operation;
|
|
732
812
|
}
|
|
733
|
-
|
|
734
|
-
|
|
735
|
-
|
|
736
|
-
|
|
737
|
-
|
|
738
|
-
|
|
739
|
-
|
|
740
|
-
|
|
741
|
-
|
|
742
|
-
|
|
743
|
-
|
|
744
|
-
|
|
745
|
-
|
|
746
|
-
|
|
747
|
-
|
|
748
|
-
|
|
749
|
-
|
|
750
|
-
|
|
751
|
-
|
|
752
|
-
|
|
753
|
-
|
|
754
|
-
|
|
755
|
-
|
|
756
|
-
}
|
|
757
|
-
restarted = true;
|
|
758
|
-
await this.startWatcher();
|
|
759
|
-
this.emit();
|
|
760
|
-
if (!this.watcher) {
|
|
761
|
-
throw new TypstError(
|
|
762
|
-
this.status.error ?? "typst watch could not start.",
|
|
763
|
-
TYPST_WATCH_FAILED
|
|
764
|
-
);
|
|
765
|
-
}
|
|
766
|
-
continue;
|
|
767
|
-
}
|
|
768
|
-
const busy = this.status.phase === "starting" || this.status.phase === "compiling";
|
|
769
|
-
const inputs = await this.inputsModifiedAt();
|
|
770
|
-
if (!busy && this.status.run > 0 && this.finishedStartedAt >= inputs)
|
|
771
|
-
return;
|
|
772
|
-
const remaining = deadline - Date.now();
|
|
773
|
-
if (remaining <= 0) {
|
|
774
|
-
throw new TypstError(
|
|
775
|
-
`Typst did not finish compiling within ${Math.round(timeoutMs / 1e3)} s. The document may be very large or stuck in a loop.`,
|
|
776
|
-
TYPST_TIMEOUT
|
|
777
|
-
);
|
|
778
|
-
}
|
|
779
|
-
const finished = await this.waitForFinish(
|
|
780
|
-
busy ? remaining : Math.min(remaining, LIMITS.settleMs)
|
|
781
|
-
);
|
|
782
|
-
if (!finished && !busy && !restarted) {
|
|
783
|
-
this.log(
|
|
784
|
-
"typst watch did not pick up the latest changes; restarting it"
|
|
785
|
-
);
|
|
786
|
-
restarted = true;
|
|
787
|
-
await this.stopWatcher();
|
|
788
|
-
await this.startWatcher();
|
|
813
|
+
async selectMain(path) {
|
|
814
|
+
await this.activate();
|
|
815
|
+
const absolute = await this.insideWorkspace(path);
|
|
816
|
+
if (extname(absolute) !== ".typ") {
|
|
817
|
+
throw new TypstError(`${path} is not a .typ file.`, TYPST_INVALID_ARGUMENT);
|
|
818
|
+
}
|
|
819
|
+
const info = await stat(absolute).catch(() => null);
|
|
820
|
+
if (!info?.isFile())
|
|
821
|
+
throw new TypstError(`${path} does not exist.`, TYPST_NOT_FOUND);
|
|
822
|
+
const main = this.relativePath(absolute);
|
|
823
|
+
await this.refreshCandidates(true);
|
|
824
|
+
if (!this.candidates.includes(main))
|
|
825
|
+
this.candidates = [...this.candidates, main];
|
|
826
|
+
if (main !== this.main || !this.watcher) {
|
|
827
|
+
await this.stopWatcher();
|
|
828
|
+
this.main = main;
|
|
829
|
+
// The fragment set belongs to the root that reported it; a new root
|
|
830
|
+
// has to compile before the panel can tell its fragments again.
|
|
831
|
+
this.fragments = [];
|
|
832
|
+
this.resetPreview();
|
|
833
|
+
await this.startWatcher();
|
|
834
|
+
}
|
|
835
|
+
await this.remember(main).catch((error) => this.log(`could not remember the main file: ${error}`));
|
|
789
836
|
this.emit();
|
|
790
|
-
|
|
837
|
+
return main;
|
|
791
838
|
}
|
|
792
|
-
|
|
793
|
-
|
|
794
|
-
|
|
795
|
-
|
|
796
|
-
|
|
797
|
-
|
|
798
|
-
|
|
799
|
-
|
|
839
|
+
// -------------------------------------------------------------------------
|
|
840
|
+
// Check: wait until the latest changes have compiled
|
|
841
|
+
// -------------------------------------------------------------------------
|
|
842
|
+
/** Both the toolchain and the main file are ready, or a telling error is thrown. */
|
|
843
|
+
requireReady() {
|
|
844
|
+
const toolchain = this.toolchain;
|
|
845
|
+
if (toolchain.state === "missing") {
|
|
846
|
+
throw new TypstError(`Typst was not found on this computer. ${INSTALL_HINT}`, TYPST_MISSING);
|
|
847
|
+
}
|
|
848
|
+
if (toolchain.state === "too_old") {
|
|
849
|
+
throw new TypstError(`${toolchain.error} Update Typst (${toolchain.path}).`, TYPST_TOO_OLD);
|
|
850
|
+
}
|
|
851
|
+
if (toolchain.state !== "ready") {
|
|
852
|
+
throw new TypstError("error" in toolchain ? toolchain.error : "Typst is not available.", TYPST_UNUSABLE);
|
|
853
|
+
}
|
|
854
|
+
if (!this.main) {
|
|
855
|
+
throw new TypstError(this.candidates.length
|
|
856
|
+
? `Choose the main file with typst_set_main. .typ files in the workspace: ${this.candidates.slice(0, 20).join(", ")}${this.candidates.length > 20 ? ", …" : ""}.`
|
|
857
|
+
: "There are no .typ files in the workspace yet. Create one (for example main.typ), then call typst_set_main or typst_check.", TYPST_NO_MAIN);
|
|
858
|
+
}
|
|
800
859
|
}
|
|
801
|
-
|
|
802
|
-
|
|
803
|
-
|
|
804
|
-
|
|
805
|
-
|
|
806
|
-
|
|
807
|
-
|
|
860
|
+
/**
|
|
861
|
+
* Newest modification and a stable signature over the input files (typst's
|
|
862
|
+
* deps; else the main file and the workspace's .typ files). The signature
|
|
863
|
+
* includes size and mtime, so a rolled-back mtime or a same-mtime rewrite is
|
|
864
|
+
* still detected as a different input set.
|
|
865
|
+
*/
|
|
866
|
+
async inputsModifiedAt() {
|
|
867
|
+
let files = (await this.watcher?.deps()) ?? [];
|
|
868
|
+
if (!files.length) {
|
|
869
|
+
files = [this.main, ...this.candidates]
|
|
870
|
+
.filter((path) => typeof path === "string")
|
|
871
|
+
.map((path) => resolve(this.workspaceRoot, path));
|
|
872
|
+
}
|
|
873
|
+
let latest = 0;
|
|
874
|
+
const parts = [];
|
|
875
|
+
await Promise.all(files.slice(0, INPUT_FILES_MAX).map(async (file) => {
|
|
876
|
+
const info = await stat(file).catch(() => null);
|
|
877
|
+
if (!info) {
|
|
878
|
+
parts.push(`${file}:missing`);
|
|
879
|
+
return;
|
|
880
|
+
}
|
|
881
|
+
latest = Math.max(latest, info.mtimeMs);
|
|
882
|
+
parts.push(`${file}:${info.mtimeMs}:${info.size}`);
|
|
883
|
+
}));
|
|
884
|
+
parts.sort();
|
|
885
|
+
return {
|
|
886
|
+
max: latest,
|
|
887
|
+
future: latest > Date.now() + 1_000,
|
|
888
|
+
signature: parts.join("\n"),
|
|
889
|
+
};
|
|
808
890
|
}
|
|
809
|
-
|
|
810
|
-
|
|
811
|
-
|
|
812
|
-
|
|
813
|
-
|
|
814
|
-
|
|
815
|
-
|
|
816
|
-
|
|
817
|
-
|
|
818
|
-
|
|
819
|
-
|
|
820
|
-
|
|
821
|
-
|
|
822
|
-
|
|
823
|
-
|
|
824
|
-
|
|
825
|
-
|
|
826
|
-
|
|
891
|
+
/** Wait until every change already on disk has compiled (restart the watch when it missed changes). */
|
|
892
|
+
async settle(timeoutMs = LIMITS.checkTimeoutMs, signal) {
|
|
893
|
+
await this.activate();
|
|
894
|
+
if (this.closed) {
|
|
895
|
+
throw new TypstError("The workspace session is closed.", TYPST_WATCH_FAILED);
|
|
896
|
+
}
|
|
897
|
+
if (!this.main)
|
|
898
|
+
await this.refreshCandidates(true);
|
|
899
|
+
this.requireReady();
|
|
900
|
+
const deadline = Date.now() + timeoutMs;
|
|
901
|
+
let restarted = false;
|
|
902
|
+
for (;;) {
|
|
903
|
+
signal?.throwIfAborted();
|
|
904
|
+
if (this.closed) {
|
|
905
|
+
throw new TypstError("The workspace session is closed.", TYPST_WATCH_FAILED);
|
|
906
|
+
}
|
|
907
|
+
if (!this.watcher) {
|
|
908
|
+
if (restarted) {
|
|
909
|
+
throw new TypstError(`typst watch stopped: ${this.status.error ?? "unknown error"}`, TYPST_WATCH_FAILED);
|
|
910
|
+
}
|
|
911
|
+
restarted = true;
|
|
912
|
+
await this.startWatcher();
|
|
913
|
+
this.emit();
|
|
914
|
+
if (!this.watcher) {
|
|
915
|
+
throw new TypstError(this.status.error ?? "typst watch could not start.", TYPST_WATCH_FAILED);
|
|
916
|
+
}
|
|
917
|
+
continue;
|
|
918
|
+
}
|
|
919
|
+
const version = this.finishVersion;
|
|
920
|
+
const busy = this.status.phase === "starting" || this.status.phase === "compiling";
|
|
921
|
+
const inputs = await this.inputsModifiedAt();
|
|
922
|
+
// A compile may finish while the input signatures are being read; its
|
|
923
|
+
// wake happened before the waiter below exists, so re-evaluate instead.
|
|
924
|
+
if (this.finishVersion !== version)
|
|
925
|
+
continue;
|
|
926
|
+
if (!busy &&
|
|
927
|
+
this.status.run > 0 &&
|
|
928
|
+
this.finishGeneration === this.generation &&
|
|
929
|
+
this.compiledInputs !== null &&
|
|
930
|
+
this.compiledInputs === inputs.signature)
|
|
931
|
+
return;
|
|
932
|
+
if (!busy &&
|
|
933
|
+
this.status.run > 0 &&
|
|
934
|
+
this.finishGeneration === this.generation &&
|
|
935
|
+
this.compiledInputs === null &&
|
|
936
|
+
!inputs.future &&
|
|
937
|
+
this.finishedStartedAt >= inputs.max)
|
|
938
|
+
return;
|
|
939
|
+
const remaining = deadline - Date.now();
|
|
940
|
+
if (remaining <= 0) {
|
|
941
|
+
throw new TypstError(`Typst did not finish compiling within ${Math.round(timeoutMs / 1e3)} s. The document may be very large or stuck in a loop.`, TYPST_TIMEOUT);
|
|
942
|
+
}
|
|
943
|
+
const finished = await this.waitForFinish(busy ? remaining : Math.min(remaining, LIMITS.settleMs), signal);
|
|
944
|
+
signal?.throwIfAborted();
|
|
945
|
+
if (!finished && !busy && !restarted) {
|
|
946
|
+
this.log("typst watch did not pick up the latest changes; restarting it");
|
|
947
|
+
restarted = true;
|
|
948
|
+
await this.stopWatcher();
|
|
949
|
+
await this.startWatcher();
|
|
950
|
+
this.emit();
|
|
951
|
+
}
|
|
952
|
+
}
|
|
953
|
+
}
|
|
954
|
+
// -------------------------------------------------------------------------
|
|
955
|
+
// Snapshots
|
|
956
|
+
// -------------------------------------------------------------------------
|
|
957
|
+
async addSnapshot(bytes, generation, token, run) {
|
|
958
|
+
if (bytes.length > LIMITS.pdfBytes) {
|
|
959
|
+
this.previewError = `Preview PDF exceeds ${LIMITS.pdfBytes} bytes (${bytes.length}).`;
|
|
960
|
+
return;
|
|
961
|
+
}
|
|
962
|
+
const sha256 = createHash("sha256").update(bytes).digest("hex");
|
|
963
|
+
let pages;
|
|
964
|
+
try {
|
|
965
|
+
pages =
|
|
966
|
+
this.current?.sha256 === sha256
|
|
967
|
+
? this.current.pages
|
|
968
|
+
: await pageCount(bytes);
|
|
969
|
+
}
|
|
970
|
+
catch (error) {
|
|
971
|
+
this.previewError = `Could not read the preview PDF: ${String(error)}`;
|
|
972
|
+
return;
|
|
973
|
+
}
|
|
974
|
+
if (generation !== this.generation ||
|
|
975
|
+
token !== this.compileToken ||
|
|
976
|
+
!this.main)
|
|
977
|
+
return;
|
|
978
|
+
const info = {
|
|
979
|
+
generation,
|
|
980
|
+
main: this.main,
|
|
981
|
+
run,
|
|
982
|
+
seq: ++this.seq,
|
|
983
|
+
bytes: bytes.length,
|
|
984
|
+
pages,
|
|
985
|
+
sha256,
|
|
986
|
+
createdAt: Date.now(),
|
|
987
|
+
};
|
|
988
|
+
this.snapshots.set(info.seq, { info, bytes });
|
|
989
|
+
const retainedBytes = () => {
|
|
990
|
+
let total = 0;
|
|
991
|
+
for (const snapshot of this.snapshots.values())
|
|
992
|
+
total += snapshot.bytes.length;
|
|
993
|
+
return total;
|
|
994
|
+
};
|
|
995
|
+
while (this.snapshots.size > LIMITS.snapshots ||
|
|
996
|
+
retainedBytes() > LIMITS.snapshotBytes) {
|
|
997
|
+
if (this.snapshots.size <= 1)
|
|
998
|
+
break;
|
|
999
|
+
const oldest = this.snapshots.keys().next().value;
|
|
1000
|
+
if (oldest === undefined)
|
|
1001
|
+
break;
|
|
1002
|
+
this.snapshots.delete(oldest);
|
|
1003
|
+
this.pagesCache.delete(oldest);
|
|
1004
|
+
}
|
|
1005
|
+
this.current = info;
|
|
827
1006
|
}
|
|
828
|
-
|
|
829
|
-
|
|
830
|
-
|
|
831
|
-
|
|
832
|
-
|
|
833
|
-
|
|
834
|
-
|
|
835
|
-
|
|
836
|
-
|
|
1007
|
+
/** Read precisely the requested retained artifact, never silently substitute the latest. */
|
|
1008
|
+
previewBytes(identity) {
|
|
1009
|
+
const snapshot = this.snapshots.get(identity.seq);
|
|
1010
|
+
if (!snapshot ||
|
|
1011
|
+
snapshot.info.generation !== identity.generation ||
|
|
1012
|
+
snapshot.info.sha256 !== identity.sha256) {
|
|
1013
|
+
throw new TypstError("The requested preview expired or belongs to another main file. Refresh the preview.", TYPST_NOT_FOUND);
|
|
1014
|
+
}
|
|
1015
|
+
return snapshot;
|
|
837
1016
|
}
|
|
838
|
-
|
|
839
|
-
|
|
840
|
-
|
|
841
|
-
|
|
842
|
-
|
|
843
|
-
|
|
844
|
-
|
|
845
|
-
|
|
846
|
-
|
|
847
|
-
|
|
848
|
-
const snapshot = this.snapshots.get(identity.seq);
|
|
849
|
-
if (!snapshot || snapshot.info.generation !== identity.generation || snapshot.info.sha256 !== identity.sha256) {
|
|
850
|
-
throw new TypstError(
|
|
851
|
-
"The requested preview expired or belongs to another main file. Refresh the preview.",
|
|
852
|
-
TYPST_NOT_FOUND
|
|
853
|
-
);
|
|
1017
|
+
async pagesOf(seq) {
|
|
1018
|
+
const cached = this.pagesCache.get(seq);
|
|
1019
|
+
if (cached)
|
|
1020
|
+
return cached;
|
|
1021
|
+
const snapshot = this.snapshots.get(seq);
|
|
1022
|
+
if (!snapshot)
|
|
1023
|
+
throw new TypstError(`Preview ${seq} is no longer available.`, TYPST_NOT_FOUND);
|
|
1024
|
+
const pages = await extractPages(snapshot.bytes, pdfjsDataDir());
|
|
1025
|
+
this.pagesCache.set(seq, pages);
|
|
1026
|
+
return pages;
|
|
854
1027
|
}
|
|
855
|
-
|
|
856
|
-
|
|
857
|
-
|
|
858
|
-
|
|
859
|
-
|
|
860
|
-
|
|
861
|
-
|
|
862
|
-
|
|
863
|
-
`Preview ${seq} is no longer available.`,
|
|
864
|
-
TYPST_NOT_FOUND
|
|
865
|
-
);
|
|
866
|
-
const pages = await extractPages(snapshot.bytes, pdfjsDataDir());
|
|
867
|
-
this.pagesCache.set(seq, pages);
|
|
868
|
-
return pages;
|
|
869
|
-
}
|
|
870
|
-
/** A preview is required (something compiled successfully). */
|
|
871
|
-
requireSnapshot() {
|
|
872
|
-
if (!this.current) {
|
|
873
|
-
throw new TypstError(
|
|
874
|
-
this.status.phase === "error" ? "The document has not compiled successfully yet; fix the errors first (see typst_check)." : "There is no preview yet.",
|
|
875
|
-
TYPST_NO_PREVIEW
|
|
876
|
-
);
|
|
1028
|
+
/** A preview is required (something compiled successfully). */
|
|
1029
|
+
requireSnapshot() {
|
|
1030
|
+
if (!this.current) {
|
|
1031
|
+
throw new TypstError(this.status.phase === "error"
|
|
1032
|
+
? "The document has not compiled successfully yet; fix the errors first (see typst_check)."
|
|
1033
|
+
: "There is no preview yet.", TYPST_NO_PREVIEW);
|
|
1034
|
+
}
|
|
1035
|
+
return this.current;
|
|
877
1036
|
}
|
|
878
|
-
|
|
879
|
-
|
|
880
|
-
|
|
881
|
-
|
|
882
|
-
|
|
883
|
-
|
|
884
|
-
|
|
885
|
-
|
|
886
|
-
|
|
887
|
-
|
|
888
|
-
|
|
889
|
-
|
|
1037
|
+
// -------------------------------------------------------------------------
|
|
1038
|
+
// Panel view and highlights
|
|
1039
|
+
// -------------------------------------------------------------------------
|
|
1040
|
+
showPage(pageIndex) {
|
|
1041
|
+
const snapshot = this.requireSnapshot();
|
|
1042
|
+
if (!Number.isInteger(pageIndex) ||
|
|
1043
|
+
pageIndex < 0 ||
|
|
1044
|
+
pageIndex >= snapshot.pages) {
|
|
1045
|
+
throw new TypstError(`The document has ${snapshot.pages} page(s).`, TYPST_INVALID_ARGUMENT);
|
|
1046
|
+
}
|
|
1047
|
+
this.view = {
|
|
1048
|
+
kind: "page",
|
|
1049
|
+
pageIndex,
|
|
1050
|
+
identity: {
|
|
1051
|
+
generation: snapshot.generation,
|
|
1052
|
+
seq: snapshot.seq,
|
|
1053
|
+
sha256: snapshot.sha256,
|
|
1054
|
+
},
|
|
1055
|
+
};
|
|
1056
|
+
this.viewSeq += 1;
|
|
1057
|
+
this.emit();
|
|
890
1058
|
}
|
|
891
|
-
|
|
892
|
-
|
|
893
|
-
|
|
894
|
-
|
|
895
|
-
|
|
896
|
-
|
|
897
|
-
|
|
898
|
-
|
|
899
|
-
|
|
900
|
-
|
|
901
|
-
|
|
902
|
-
|
|
903
|
-
|
|
904
|
-
|
|
905
|
-
|
|
906
|
-
|
|
907
|
-
|
|
908
|
-
|
|
909
|
-
|
|
910
|
-
|
|
911
|
-
|
|
912
|
-
|
|
913
|
-
|
|
914
|
-
|
|
915
|
-
|
|
916
|
-
|
|
917
|
-
|
|
918
|
-
}
|
|
1059
|
+
/**
|
|
1060
|
+
* When a highlight is created from source lines, count how many times the
|
|
1061
|
+
* same rendered passage occurred before the recorded range. Typst emits
|
|
1062
|
+
* repeated text in document order, so that ordinal disambiguates identical
|
|
1063
|
+
* quotes on the same page.
|
|
1064
|
+
*/
|
|
1065
|
+
async occurrenceForSource(text, source) {
|
|
1066
|
+
const files = await this.sourceFiles().catch(() => []);
|
|
1067
|
+
const file = files.find((entry) => entry.path === source.file);
|
|
1068
|
+
if (!file)
|
|
1069
|
+
return 0;
|
|
1070
|
+
const starts = lineStarts(file.text);
|
|
1071
|
+
const before = file.text.slice(0, starts[source.line - 1] ?? 0);
|
|
1072
|
+
const folded = (value) => value.replace(/\s+/g, " ").trim().toLowerCase();
|
|
1073
|
+
const needle = folded(text);
|
|
1074
|
+
if (!needle)
|
|
1075
|
+
return 0;
|
|
1076
|
+
const haystack = folded(before);
|
|
1077
|
+
let ordinal = 0;
|
|
1078
|
+
let from = 0;
|
|
1079
|
+
for (;;) {
|
|
1080
|
+
const at = haystack.indexOf(needle, from);
|
|
1081
|
+
if (at < 0)
|
|
1082
|
+
return ordinal;
|
|
1083
|
+
ordinal++;
|
|
1084
|
+
from = at + needle.length;
|
|
1085
|
+
}
|
|
919
1086
|
}
|
|
920
|
-
|
|
921
|
-
|
|
922
|
-
|
|
923
|
-
|
|
924
|
-
|
|
925
|
-
|
|
926
|
-
|
|
927
|
-
|
|
928
|
-
|
|
929
|
-
|
|
930
|
-
|
|
931
|
-
|
|
932
|
-
|
|
933
|
-
|
|
934
|
-
|
|
935
|
-
|
|
936
|
-
|
|
937
|
-
|
|
938
|
-
|
|
939
|
-
|
|
940
|
-
|
|
941
|
-
}
|
|
942
|
-
const range = lineRange(content, starts, target.line, endLine);
|
|
943
|
-
text = content.slice(range.start, range.end);
|
|
944
|
-
source = {
|
|
945
|
-
file: this.relativePath(absolute),
|
|
946
|
-
line: target.line,
|
|
947
|
-
endLine: Math.min(endLine, starts.length)
|
|
948
|
-
};
|
|
949
|
-
} else {
|
|
950
|
-
throw new TypstError(
|
|
951
|
-
"Give a quote, or a file and line.",
|
|
952
|
-
TYPST_INVALID_ARGUMENT
|
|
953
|
-
);
|
|
1087
|
+
/** Find text in the preview: quote matching first (tolerant of whitespace, quotes, line breaks), then skeleton approximation. */
|
|
1088
|
+
findText(pages, text, preferredPage, from, occurrence) {
|
|
1089
|
+
const exact = findQuote(pages, text, preferredPage, from, occurrence);
|
|
1090
|
+
if (exact)
|
|
1091
|
+
return {
|
|
1092
|
+
pageIndex: exact.pageIndex,
|
|
1093
|
+
start: exact.start,
|
|
1094
|
+
end: exact.end,
|
|
1095
|
+
score: 1,
|
|
1096
|
+
};
|
|
1097
|
+
let best = null;
|
|
1098
|
+
for (const page of pages) {
|
|
1099
|
+
const [hit] = fuzzyFind(text, skeleton(page.text), { max: 1 });
|
|
1100
|
+
if (hit &&
|
|
1101
|
+
(!best ||
|
|
1102
|
+
hit.score > best.score + 0.05 ||
|
|
1103
|
+
(preferredPage === page.index && hit.score >= best.score - 0.05))) {
|
|
1104
|
+
best = { pageIndex: page.index, ...hit };
|
|
1105
|
+
}
|
|
1106
|
+
}
|
|
1107
|
+
return best;
|
|
954
1108
|
}
|
|
955
|
-
|
|
956
|
-
|
|
957
|
-
|
|
958
|
-
|
|
959
|
-
|
|
960
|
-
|
|
961
|
-
|
|
962
|
-
|
|
963
|
-
|
|
964
|
-
|
|
965
|
-
|
|
1109
|
+
async highlight(target, comment = "") {
|
|
1110
|
+
const snapshot = this.requireSnapshot();
|
|
1111
|
+
const pages = await this.pagesOf(snapshot.seq);
|
|
1112
|
+
let text;
|
|
1113
|
+
let source;
|
|
1114
|
+
if (target.quote) {
|
|
1115
|
+
text = target.quote;
|
|
1116
|
+
}
|
|
1117
|
+
else if (target.file && target.line) {
|
|
1118
|
+
if (extname(target.file).toLowerCase() !== ".typ") {
|
|
1119
|
+
throw new TypstError(`${target.file} is not a .typ file.`, TYPST_INVALID_ARGUMENT);
|
|
1120
|
+
}
|
|
1121
|
+
const absolute = await this.insideWorkspace(target.file);
|
|
1122
|
+
const handle = await open(absolute, "r").catch(() => {
|
|
1123
|
+
throw new TypstError(`${target.file} does not exist.`, TYPST_NOT_FOUND);
|
|
1124
|
+
});
|
|
1125
|
+
let content;
|
|
1126
|
+
try {
|
|
1127
|
+
const info = await handle.stat();
|
|
1128
|
+
if (!info.isFile()) {
|
|
1129
|
+
throw new TypstError(`${target.file} is not a regular file.`, TYPST_INVALID_ARGUMENT);
|
|
1130
|
+
}
|
|
1131
|
+
if (info.size > SOURCE_FILE_MAX_BYTES) {
|
|
1132
|
+
throw new TypstError(`${target.file} is too large to inspect (${info.size} bytes).`, TYPST_INVALID_ARGUMENT);
|
|
1133
|
+
}
|
|
1134
|
+
content = await handle.readFile("utf8");
|
|
1135
|
+
}
|
|
1136
|
+
finally {
|
|
1137
|
+
await handle.close();
|
|
1138
|
+
}
|
|
1139
|
+
const starts = lineStarts(content);
|
|
1140
|
+
const endLine = Math.max(target.line, target.endLine ?? target.line);
|
|
1141
|
+
if (target.line > starts.length) {
|
|
1142
|
+
throw new TypstError(`${target.file} has ${starts.length} lines.`, TYPST_INVALID_ARGUMENT);
|
|
1143
|
+
}
|
|
1144
|
+
const range = lineRange(content, starts, target.line, endLine);
|
|
1145
|
+
text = content.slice(range.start, range.end);
|
|
1146
|
+
source = {
|
|
1147
|
+
file: this.relativePath(absolute),
|
|
1148
|
+
line: target.line,
|
|
1149
|
+
endLine: Math.min(endLine, starts.length),
|
|
1150
|
+
};
|
|
1151
|
+
}
|
|
1152
|
+
else {
|
|
1153
|
+
throw new TypstError("Give a quote, or a file and line.", TYPST_INVALID_ARGUMENT);
|
|
1154
|
+
}
|
|
1155
|
+
if (this.closed ||
|
|
1156
|
+
snapshot.generation !== this.generation ||
|
|
1157
|
+
snapshot.seq !== this.current?.seq)
|
|
1158
|
+
throw new TypstError("The preview changed while locating the quote. Run typst_check and try again.", TYPST_NOT_FOUND);
|
|
1159
|
+
const occurrence = source
|
|
1160
|
+
? await this.occurrenceForSource(text, source)
|
|
1161
|
+
: undefined;
|
|
1162
|
+
const found = this.findText(pages, text, undefined, undefined, occurrence);
|
|
1163
|
+
if (!found) {
|
|
1164
|
+
throw new TypstError(source
|
|
1165
|
+
? `No text from ${source.file}:${source.line}${source.endLine !== source.line ? `\u2013${source.endLine}` : ""} was found in the preview. The lines may contain only markup or code, or the preview may be out of date (run typst_check).`
|
|
1166
|
+
: "The quote was not found in the preview. Copy the words as they appear in the rendered document (markup is ignored), or point at source lines with file and line.", TYPST_QUOTE_NOT_FOUND);
|
|
1167
|
+
}
|
|
1168
|
+
const page = pages[found.pageIndex];
|
|
1169
|
+
const highlight = {
|
|
1170
|
+
id: `h${++this.highlightSeq}`,
|
|
1171
|
+
quote: textAt(page, found.start, found.end),
|
|
1172
|
+
comment,
|
|
1173
|
+
...(source ? { source } : {}),
|
|
1174
|
+
identity: {
|
|
1175
|
+
generation: snapshot.generation,
|
|
1176
|
+
seq: snapshot.seq,
|
|
1177
|
+
sha256: snapshot.sha256,
|
|
1178
|
+
},
|
|
1179
|
+
seq: snapshot.seq,
|
|
1180
|
+
pageIndex: found.pageIndex,
|
|
1181
|
+
startOffset: found.start,
|
|
1182
|
+
...(occurrence === undefined ? {} : { occurrence }),
|
|
1183
|
+
rects: rectsFor(page, found.start, found.end),
|
|
1184
|
+
stale: false,
|
|
1185
|
+
createdAt: Date.now(),
|
|
1186
|
+
};
|
|
1187
|
+
this.highlights.push(highlight);
|
|
1188
|
+
this.view = {
|
|
1189
|
+
kind: "highlight",
|
|
1190
|
+
id: highlight.id,
|
|
1191
|
+
identity: highlight.identity,
|
|
1192
|
+
};
|
|
1193
|
+
this.viewSeq += 1;
|
|
1194
|
+
this.emit();
|
|
1195
|
+
return { highlight, exact: found.score === 1 };
|
|
966
1196
|
}
|
|
967
|
-
|
|
968
|
-
|
|
969
|
-
|
|
970
|
-
|
|
971
|
-
|
|
972
|
-
|
|
973
|
-
|
|
974
|
-
|
|
975
|
-
|
|
976
|
-
|
|
977
|
-
|
|
978
|
-
|
|
979
|
-
|
|
980
|
-
|
|
981
|
-
|
|
982
|
-
|
|
983
|
-
|
|
984
|
-
|
|
985
|
-
|
|
986
|
-
|
|
987
|
-
|
|
988
|
-
|
|
989
|
-
|
|
990
|
-
|
|
991
|
-
|
|
992
|
-
|
|
993
|
-
|
|
994
|
-
|
|
995
|
-
|
|
996
|
-
|
|
997
|
-
|
|
998
|
-
|
|
999
|
-
|
|
1000
|
-
|
|
1197
|
+
/** After a new snapshot, relocate highlights; unmatched annotations remain visible as stale. */
|
|
1198
|
+
async relocateHighlights(seq) {
|
|
1199
|
+
let pages;
|
|
1200
|
+
try {
|
|
1201
|
+
pages = await this.pagesOf(seq);
|
|
1202
|
+
}
|
|
1203
|
+
catch {
|
|
1204
|
+
return;
|
|
1205
|
+
}
|
|
1206
|
+
if (this.current?.seq !== seq)
|
|
1207
|
+
return;
|
|
1208
|
+
this.highlights = this.highlights.map((highlight) => {
|
|
1209
|
+
const from = highlight.startOffset;
|
|
1210
|
+
const occurrence = highlight.occurrence;
|
|
1211
|
+
const found = this.findText(pages, highlight.quote, highlight.pageIndex, from, occurrence) ??
|
|
1212
|
+
(from === undefined
|
|
1213
|
+
? null
|
|
1214
|
+
: this.findText(pages, highlight.quote, highlight.pageIndex));
|
|
1215
|
+
if (!found)
|
|
1216
|
+
return { ...highlight, stale: true, rects: [] };
|
|
1217
|
+
const page = pages[found.pageIndex];
|
|
1218
|
+
return {
|
|
1219
|
+
...highlight,
|
|
1220
|
+
identity: {
|
|
1221
|
+
generation: this.current.generation,
|
|
1222
|
+
seq,
|
|
1223
|
+
sha256: this.current.sha256,
|
|
1224
|
+
},
|
|
1225
|
+
seq,
|
|
1226
|
+
stale: false,
|
|
1227
|
+
pageIndex: found.pageIndex,
|
|
1228
|
+
startOffset: found.start,
|
|
1229
|
+
...(highlight.occurrence === undefined
|
|
1230
|
+
? {}
|
|
1231
|
+
: { occurrence: highlight.occurrence }),
|
|
1232
|
+
rects: rectsFor(page, found.start, found.end),
|
|
1233
|
+
};
|
|
1234
|
+
});
|
|
1235
|
+
const activeView = this.view;
|
|
1236
|
+
if (activeView?.kind === "highlight") {
|
|
1237
|
+
const current = this.highlights.find((entry) => entry.id === activeView.id);
|
|
1238
|
+
if (current !== undefined) {
|
|
1239
|
+
this.view = { ...activeView, identity: current.identity };
|
|
1240
|
+
}
|
|
1241
|
+
}
|
|
1242
|
+
this.emit();
|
|
1001
1243
|
}
|
|
1002
|
-
|
|
1003
|
-
|
|
1004
|
-
|
|
1005
|
-
|
|
1006
|
-
|
|
1007
|
-
|
|
1008
|
-
|
|
1009
|
-
|
|
1010
|
-
|
|
1011
|
-
|
|
1012
|
-
|
|
1013
|
-
|
|
1014
|
-
seq,
|
|
1015
|
-
stale: false,
|
|
1016
|
-
pageIndex: found.pageIndex,
|
|
1017
|
-
rects: rectsFor(page, found.start, found.end)
|
|
1018
|
-
};
|
|
1019
|
-
});
|
|
1020
|
-
this.emit();
|
|
1021
|
-
}
|
|
1022
|
-
clearHighlights(ids) {
|
|
1023
|
-
const before = this.highlights.length;
|
|
1024
|
-
this.highlights = ids?.length ? this.highlights.filter((entry) => !ids.includes(entry.id)) : [];
|
|
1025
|
-
const view = this.view;
|
|
1026
|
-
if (view?.kind === "highlight" && !this.highlights.some((entry) => entry.id === view.id)) {
|
|
1027
|
-
this.view = null;
|
|
1244
|
+
clearHighlights(ids) {
|
|
1245
|
+
const before = this.highlights.length;
|
|
1246
|
+
this.highlights = ids?.length
|
|
1247
|
+
? this.highlights.filter((entry) => !ids.includes(entry.id))
|
|
1248
|
+
: [];
|
|
1249
|
+
const view = this.view;
|
|
1250
|
+
if (view?.kind === "highlight" &&
|
|
1251
|
+
!this.highlights.some((entry) => entry.id === view.id)) {
|
|
1252
|
+
this.view = null;
|
|
1253
|
+
}
|
|
1254
|
+
this.emit();
|
|
1255
|
+
return before - this.highlights.length;
|
|
1028
1256
|
}
|
|
1029
|
-
|
|
1030
|
-
|
|
1031
|
-
|
|
1032
|
-
|
|
1033
|
-
|
|
1034
|
-
|
|
1035
|
-
|
|
1036
|
-
|
|
1037
|
-
|
|
1038
|
-
|
|
1039
|
-
|
|
1040
|
-
|
|
1041
|
-
|
|
1042
|
-
|
|
1043
|
-
|
|
1044
|
-
|
|
1045
|
-
|
|
1046
|
-
|
|
1047
|
-
|
|
1048
|
-
|
|
1049
|
-
|
|
1050
|
-
|
|
1051
|
-
|
|
1052
|
-
|
|
1257
|
+
// -------------------------------------------------------------------------
|
|
1258
|
+
// Rendered text → source
|
|
1259
|
+
// -------------------------------------------------------------------------
|
|
1260
|
+
/** The project's source files: workspace `.typ` files among typst's reported deps; all candidates when deps are missing. */
|
|
1261
|
+
async sourceFiles(signal) {
|
|
1262
|
+
const deps = ((await this.watcher?.deps()) ?? []).filter((file) => file.endsWith(".typ"));
|
|
1263
|
+
const paths = deps.length
|
|
1264
|
+
? deps
|
|
1265
|
+
: this.candidates.map((path) => resolve(this.workspaceRoot, path));
|
|
1266
|
+
const root = this.realRoot ?? this.workspaceRoot;
|
|
1267
|
+
const files = [];
|
|
1268
|
+
let bytes = 0;
|
|
1269
|
+
for (const absolute of paths) {
|
|
1270
|
+
signal?.throwIfAborted();
|
|
1271
|
+
if (files.length >= SOURCE_FILES_MAX || bytes > SOURCE_BYTES_MAX)
|
|
1272
|
+
break;
|
|
1273
|
+
const real = await realish(absolute);
|
|
1274
|
+
if (!isWithin(root, real))
|
|
1275
|
+
continue;
|
|
1276
|
+
const rel = relative(root, real);
|
|
1277
|
+
const info = await stat(real).catch(() => null);
|
|
1278
|
+
if (!info?.isFile() || info.size > SOURCE_FILE_MAX_BYTES)
|
|
1279
|
+
continue;
|
|
1280
|
+
const text = await readFile(real, "utf8");
|
|
1281
|
+
if (bytes + text.length > SOURCE_BYTES_MAX)
|
|
1282
|
+
break;
|
|
1283
|
+
bytes += text.length;
|
|
1284
|
+
files.push({ path: rel.split(sep).join("/"), text });
|
|
1285
|
+
}
|
|
1286
|
+
return files.sort((a, b) => Number(b.path === this.main) - Number(a.path === this.main));
|
|
1053
1287
|
}
|
|
1054
|
-
|
|
1055
|
-
|
|
1056
|
-
|
|
1057
|
-
|
|
1058
|
-
|
|
1059
|
-
|
|
1060
|
-
return locateInSources(await this.sourceFiles(), text, focus);
|
|
1061
|
-
}
|
|
1062
|
-
/** Common workspace font directories to pass to Typst via `--font-path`. */
|
|
1063
|
-
async fontPaths() {
|
|
1064
|
-
const candidates = [
|
|
1065
|
-
join(this.workspaceRoot, "fonts"),
|
|
1066
|
-
join(this.workspaceRoot, "assets", "fonts")
|
|
1067
|
-
];
|
|
1068
|
-
const resolved = [];
|
|
1069
|
-
for (const dir of candidates) {
|
|
1070
|
-
const s = await stat(dir).catch(() => null);
|
|
1071
|
-
if (s?.isDirectory()) resolved.push(dir);
|
|
1288
|
+
async locateSource(text, focus, signal) {
|
|
1289
|
+
await this.activate();
|
|
1290
|
+
return locateInSources(await this.sourceFiles(signal), text, focus, 3, {
|
|
1291
|
+
...(signal === undefined ? {} : { signal }),
|
|
1292
|
+
maxBytes: SOURCE_BYTES_MAX,
|
|
1293
|
+
});
|
|
1072
1294
|
}
|
|
1073
|
-
|
|
1074
|
-
|
|
1075
|
-
|
|
1076
|
-
|
|
1077
|
-
|
|
1078
|
-
|
|
1079
|
-
|
|
1080
|
-
|
|
1081
|
-
|
|
1082
|
-
|
|
1083
|
-
|
|
1084
|
-
|
|
1085
|
-
|
|
1086
|
-
|
|
1087
|
-
|
|
1088
|
-
|
|
1089
|
-
|
|
1090
|
-
|
|
1091
|
-
|
|
1092
|
-
|
|
1093
|
-
|
|
1094
|
-
|
|
1095
|
-
|
|
1096
|
-
|
|
1097
|
-
|
|
1098
|
-
|
|
1099
|
-
|
|
1100
|
-
} catch (error) {
|
|
1101
|
-
throw new TypstError(
|
|
1102
|
-
error instanceof Error ? error.message : String(error),
|
|
1103
|
-
TYPST_INVALID_ARGUMENT
|
|
1104
|
-
);
|
|
1295
|
+
/**
|
|
1296
|
+
* Font directories passed to Typst via `--font-path`: the workspace's
|
|
1297
|
+
* conventional `fonts/` and `assets/fonts/` first, then the configured
|
|
1298
|
+
* directories. Project fonts therefore win on a family clash, and a
|
|
1299
|
+
* configured directory typst cannot read is left for typst to ignore.
|
|
1300
|
+
* @param configured - font directories from the current settings snapshot.
|
|
1301
|
+
* @returns the ordered `--font-path` directories.
|
|
1302
|
+
*/
|
|
1303
|
+
async fontPaths(configured) {
|
|
1304
|
+
const candidates = [
|
|
1305
|
+
join(this.workspaceRoot, "fonts"),
|
|
1306
|
+
join(this.workspaceRoot, "assets", "fonts"),
|
|
1307
|
+
];
|
|
1308
|
+
const resolved = [];
|
|
1309
|
+
for (const dir of candidates) {
|
|
1310
|
+
const s = await stat(dir).catch(() => null);
|
|
1311
|
+
if (s?.isDirectory())
|
|
1312
|
+
resolved.push(dir);
|
|
1313
|
+
}
|
|
1314
|
+
const seen = new Set(resolved);
|
|
1315
|
+
for (const dir of configured) {
|
|
1316
|
+
if (seen.has(dir))
|
|
1317
|
+
continue;
|
|
1318
|
+
seen.add(dir);
|
|
1319
|
+
resolved.push(dir);
|
|
1320
|
+
}
|
|
1321
|
+
return resolved;
|
|
1105
1322
|
}
|
|
1106
|
-
|
|
1107
|
-
|
|
1108
|
-
|
|
1109
|
-
|
|
1110
|
-
|
|
1323
|
+
// -------------------------------------------------------------------------
|
|
1324
|
+
// One-shot compiles: render images, export
|
|
1325
|
+
// -------------------------------------------------------------------------
|
|
1326
|
+
async oneshot(signal) {
|
|
1327
|
+
this.requireReady();
|
|
1328
|
+
const settings = this.settings();
|
|
1329
|
+
const fontPaths = await this.fontPaths(settings.fontPaths);
|
|
1330
|
+
return {
|
|
1331
|
+
typst: this.toolchain.path,
|
|
1332
|
+
cwd: this.workspaceRoot,
|
|
1333
|
+
root: this.workspaceRoot,
|
|
1334
|
+
fontPaths,
|
|
1335
|
+
packagePath: settings.packagePath || undefined,
|
|
1336
|
+
main: this.main,
|
|
1337
|
+
process: this.process,
|
|
1338
|
+
env: this.env,
|
|
1339
|
+
...(signal === undefined ? {} : { signal }),
|
|
1340
|
+
scratch: this.buildDir ?? (this.buildDir = await this.makeBuildDir()),
|
|
1341
|
+
toFile: (path) => this.displayPath(path),
|
|
1342
|
+
};
|
|
1111
1343
|
}
|
|
1112
|
-
|
|
1113
|
-
|
|
1114
|
-
|
|
1115
|
-
|
|
1116
|
-
|
|
1344
|
+
/** Track one one-shot compile so close/killNow can abort it. */
|
|
1345
|
+
async withOneshot(signal, body) {
|
|
1346
|
+
const controller = new AbortController();
|
|
1347
|
+
const fused = signal === undefined
|
|
1348
|
+
? controller.signal
|
|
1349
|
+
: AbortSignal.any([signal, controller.signal]);
|
|
1350
|
+
this.liveOneshots.add(controller);
|
|
1351
|
+
try {
|
|
1352
|
+
return await body(fused);
|
|
1353
|
+
}
|
|
1354
|
+
finally {
|
|
1355
|
+
this.liveOneshots.delete(controller);
|
|
1356
|
+
}
|
|
1117
1357
|
}
|
|
1118
|
-
|
|
1119
|
-
|
|
1120
|
-
|
|
1121
|
-
|
|
1122
|
-
|
|
1123
|
-
|
|
1124
|
-
|
|
1125
|
-
|
|
1126
|
-
|
|
1127
|
-
|
|
1128
|
-
|
|
1129
|
-
|
|
1130
|
-
|
|
1131
|
-
|
|
1132
|
-
|
|
1358
|
+
async renderPages(spec, ppi, signal) {
|
|
1359
|
+
await this.activate();
|
|
1360
|
+
const mainAtStart = this.main;
|
|
1361
|
+
const generationAtStart = this.generation;
|
|
1362
|
+
const options = await this.oneshot(signal);
|
|
1363
|
+
if (this.main !== mainAtStart || this.generation !== generationAtStart) {
|
|
1364
|
+
throw new TypstError("The main file changed while preparing the render; call typst_render_pages again.", TYPST_MAIN_CHANGED);
|
|
1365
|
+
}
|
|
1366
|
+
const settled = await this.settle(LIMITS.checkTimeoutMs, signal)
|
|
1367
|
+
.then(() => true)
|
|
1368
|
+
.catch(() => false);
|
|
1369
|
+
// A failed settle leaves the last snapshot in place; its page count is
|
|
1370
|
+
// stale, so do not use it to reject a page the new document may have.
|
|
1371
|
+
const total = settled ? this.current?.pages : undefined;
|
|
1372
|
+
let pages;
|
|
1373
|
+
try {
|
|
1374
|
+
pages = parsePages(spec, total ?? 10_000).map((index) => index + 1);
|
|
1375
|
+
}
|
|
1376
|
+
catch (error) {
|
|
1377
|
+
throw new TypstError(error instanceof Error ? error.message : String(error), TYPST_INVALID_ARGUMENT);
|
|
1378
|
+
}
|
|
1379
|
+
if (!pages.length) {
|
|
1380
|
+
throw new TypstError(total ? `The document has ${total} page(s).` : "No pages selected.", TYPST_INVALID_ARGUMENT);
|
|
1381
|
+
}
|
|
1382
|
+
if (pages.length > LIMITS.renderPages) {
|
|
1383
|
+
throw new TypstError(`Render at most ${LIMITS.renderPages} pages at a time.`, TYPST_INVALID_ARGUMENT);
|
|
1384
|
+
}
|
|
1385
|
+
const result = await this.withOneshot(signal, (fused) => renderPages({ ...options, signal: fused }, pages, ppi));
|
|
1386
|
+
const diagnostics = await Promise.all(result.diagnostics
|
|
1387
|
+
.slice(0, LIMITS.diagnostics)
|
|
1388
|
+
.map((entry) => this.withExcerpt(entry)));
|
|
1389
|
+
return { ...result, diagnostics, pages, total };
|
|
1133
1390
|
}
|
|
1134
|
-
|
|
1135
|
-
|
|
1136
|
-
|
|
1137
|
-
|
|
1138
|
-
|
|
1139
|
-
|
|
1140
|
-
|
|
1141
|
-
|
|
1142
|
-
|
|
1143
|
-
|
|
1144
|
-
|
|
1145
|
-
|
|
1146
|
-
|
|
1147
|
-
|
|
1148
|
-
|
|
1149
|
-
|
|
1150
|
-
|
|
1151
|
-
|
|
1152
|
-
|
|
1153
|
-
|
|
1154
|
-
|
|
1155
|
-
|
|
1156
|
-
|
|
1157
|
-
|
|
1158
|
-
|
|
1159
|
-
|
|
1160
|
-
|
|
1161
|
-
|
|
1162
|
-
|
|
1163
|
-
|
|
1164
|
-
|
|
1391
|
+
async exportPdf(path, extra, signal, policy) {
|
|
1392
|
+
await this.activate();
|
|
1393
|
+
const mainAtStart = this.main;
|
|
1394
|
+
const generationAtStart = this.generation;
|
|
1395
|
+
const absolute = await this.insideWorkspace(path);
|
|
1396
|
+
if (extname(absolute).toLowerCase() !== ".pdf") {
|
|
1397
|
+
throw new TypstError("The output path must end in .pdf.", TYPST_INVALID_ARGUMENT);
|
|
1398
|
+
}
|
|
1399
|
+
if (policy !== undefined) {
|
|
1400
|
+
if (policy.mode === "read-only") {
|
|
1401
|
+
throw new TypstError("The session is read-only; exporting a PDF would write to the workspace.", TYPST_SANDBOX_READ_ONLY);
|
|
1402
|
+
}
|
|
1403
|
+
if (policy.mode === "workspace-write") {
|
|
1404
|
+
let roots;
|
|
1405
|
+
try {
|
|
1406
|
+
roots = workspaceWritableRoots(policy);
|
|
1407
|
+
}
|
|
1408
|
+
catch (error) {
|
|
1409
|
+
if (error instanceof SandboxInvalidRootError) {
|
|
1410
|
+
throw new TypstError(error.message, TYPST_SANDBOX_INVALID_ROOT, {
|
|
1411
|
+
cause: error,
|
|
1412
|
+
});
|
|
1413
|
+
}
|
|
1414
|
+
throw error;
|
|
1415
|
+
}
|
|
1416
|
+
if (!roots.some((root) => isWithin(root, absolute))) {
|
|
1417
|
+
throw new TypstError("The output path is outside the session's writable roots.", TYPST_PATH_OUTSIDE_WORKSPACE);
|
|
1418
|
+
}
|
|
1419
|
+
}
|
|
1420
|
+
}
|
|
1421
|
+
const existing = await lstat(absolute).catch(() => null);
|
|
1422
|
+
if (existing?.isSymbolicLink()) {
|
|
1423
|
+
throw new TypstError("The output path is a symbolic link; choose a regular .pdf path.", TYPST_PATH_OUTSIDE_WORKSPACE);
|
|
1424
|
+
}
|
|
1425
|
+
if (existing?.isDirectory()) {
|
|
1426
|
+
throw new TypstError("The output path is a directory.", TYPST_INVALID_ARGUMENT);
|
|
1427
|
+
}
|
|
1428
|
+
const settled = await this.settle(LIMITS.checkTimeoutMs, signal)
|
|
1429
|
+
.then(() => true)
|
|
1430
|
+
.catch(() => false);
|
|
1431
|
+
const total = settled ? this.current?.pages : undefined;
|
|
1432
|
+
if (typeof extra.pages === "string" && extra.pages.trim().length > 0) {
|
|
1433
|
+
let selected;
|
|
1434
|
+
try {
|
|
1435
|
+
selected = parsePages(extra.pages, 10_000);
|
|
1436
|
+
}
|
|
1437
|
+
catch (error) {
|
|
1438
|
+
throw new TypstError(error instanceof Error ? error.message : String(error), TYPST_INVALID_ARGUMENT);
|
|
1439
|
+
}
|
|
1440
|
+
if (selected.length === 0) {
|
|
1441
|
+
throw new TypstError("No pages selected.", TYPST_INVALID_ARGUMENT);
|
|
1442
|
+
}
|
|
1443
|
+
if (total !== undefined && selected.some((page) => page >= total)) {
|
|
1444
|
+
throw new TypstError(`The document has ${total} page(s); the page selection is out of range.`, TYPST_PAGE_OUT_OF_RANGE);
|
|
1445
|
+
}
|
|
1446
|
+
}
|
|
1447
|
+
const options = await this.oneshot(signal);
|
|
1448
|
+
if (this.main !== mainAtStart || this.generation !== generationAtStart) {
|
|
1449
|
+
throw new TypstError("The main file changed while preparing the export; call typst_export_pdf again.", TYPST_MAIN_CHANGED);
|
|
1450
|
+
}
|
|
1451
|
+
await mkdir(dirname(absolute), { recursive: true, mode: 0o700 });
|
|
1452
|
+
const result = await this.withOneshot(signal, (fused) => exportPdf({ ...options, signal: fused }, absolute, extra));
|
|
1453
|
+
const diagnostics = await Promise.all(result.diagnostics
|
|
1454
|
+
.slice(0, LIMITS.diagnostics)
|
|
1455
|
+
.map((entry) => this.withExcerpt(entry)));
|
|
1456
|
+
if (!result.ok)
|
|
1457
|
+
return { ...result, diagnostics, path: this.relativePath(absolute) };
|
|
1458
|
+
const bytes = new Uint8Array(await readFile(absolute));
|
|
1459
|
+
return {
|
|
1460
|
+
...result,
|
|
1461
|
+
diagnostics,
|
|
1462
|
+
path: this.relativePath(absolute),
|
|
1463
|
+
bytes: bytes.length,
|
|
1464
|
+
pages: await pageCount(bytes).catch(() => undefined),
|
|
1465
|
+
};
|
|
1466
|
+
}
|
|
1467
|
+
// -------------------------------------------------------------------------
|
|
1468
|
+
// Paths
|
|
1469
|
+
// -------------------------------------------------------------------------
|
|
1470
|
+
/** Workspace-relative path (/ separated), against the canonical root. */
|
|
1471
|
+
relativePath(absolute) {
|
|
1472
|
+
return relative(this.realRoot ?? this.workspaceRoot, absolute)
|
|
1473
|
+
.split(sep)
|
|
1474
|
+
.join("/");
|
|
1475
|
+
}
|
|
1476
|
+
/** A path as typst printed it (relative to the workspace root, or absolute) → display path. */
|
|
1477
|
+
displayPath(path) {
|
|
1478
|
+
if (!isAbsolute(path))
|
|
1479
|
+
return path.split(sep).join("/");
|
|
1480
|
+
for (const root of [this.workspaceRoot, this.realRoot]) {
|
|
1481
|
+
if (!root)
|
|
1482
|
+
continue;
|
|
1483
|
+
const rel = relative(root, path);
|
|
1484
|
+
if (!rel.startsWith("..") && !isAbsolute(rel))
|
|
1485
|
+
return rel.split(sep).join("/");
|
|
1486
|
+
}
|
|
1487
|
+
return path;
|
|
1165
1488
|
}
|
|
1166
|
-
|
|
1167
|
-
|
|
1168
|
-
|
|
1169
|
-
|
|
1170
|
-
|
|
1171
|
-
|
|
1489
|
+
/** Resolve a path inside the workspace (through symlinks); refuse escapes. */
|
|
1490
|
+
async insideWorkspace(path) {
|
|
1491
|
+
if (!path || path.includes("\0")) {
|
|
1492
|
+
throw new TypstError("Empty path.", TYPST_INVALID_ARGUMENT);
|
|
1493
|
+
}
|
|
1494
|
+
const root = this.realRoot ??
|
|
1495
|
+
(await realpath(this.workspaceRoot).catch(() => this.workspaceRoot));
|
|
1496
|
+
try {
|
|
1497
|
+
return await resolveInside(root, resolve(this.workspaceRoot, path));
|
|
1498
|
+
}
|
|
1499
|
+
catch {
|
|
1500
|
+
throw new TypstError(`${path} is outside the workspace.`, TYPST_PATH_OUTSIDE_WORKSPACE);
|
|
1501
|
+
}
|
|
1172
1502
|
}
|
|
1173
|
-
|
|
1174
|
-
|
|
1175
|
-
|
|
1176
|
-
|
|
1177
|
-
|
|
1178
|
-
|
|
1179
|
-
|
|
1180
|
-
|
|
1181
|
-
|
|
1182
|
-
|
|
1183
|
-
|
|
1184
|
-
|
|
1185
|
-
|
|
1186
|
-
|
|
1187
|
-
|
|
1188
|
-
|
|
1189
|
-
|
|
1503
|
+
/** The erroring line of a workspace file. */
|
|
1504
|
+
async withExcerpt(diagnostic) {
|
|
1505
|
+
const location = diagnostic.location;
|
|
1506
|
+
if (!location || location.file.startsWith("@") || isAbsolute(location.file))
|
|
1507
|
+
return diagnostic;
|
|
1508
|
+
try {
|
|
1509
|
+
const file = resolve(this.workspaceRoot, location.file);
|
|
1510
|
+
const info = await stat(file);
|
|
1511
|
+
let cached = this.excerptCache.get(file);
|
|
1512
|
+
if (cached === undefined || cached.mtimeMs !== info.mtimeMs) {
|
|
1513
|
+
cached = {
|
|
1514
|
+
mtimeMs: info.mtimeMs,
|
|
1515
|
+
lines: (await readFile(file, "utf8")).split("\n"),
|
|
1516
|
+
};
|
|
1517
|
+
this.excerptCache.set(file, cached);
|
|
1518
|
+
}
|
|
1519
|
+
const line = cached.lines[location.line - 1];
|
|
1520
|
+
return line === undefined
|
|
1521
|
+
? diagnostic
|
|
1522
|
+
: { ...diagnostic, excerpt: line.replace(/\s+$/, "").slice(0, 300) };
|
|
1523
|
+
}
|
|
1524
|
+
catch {
|
|
1525
|
+
return diagnostic;
|
|
1526
|
+
}
|
|
1527
|
+
}
|
|
1528
|
+
// -------------------------------------------------------------------------
|
|
1529
|
+
async close() {
|
|
1530
|
+
if (this.closed)
|
|
1531
|
+
return;
|
|
1532
|
+
this.closed = true;
|
|
1533
|
+
this.indexing?.abort();
|
|
1534
|
+
this.setupSubscribers = 0;
|
|
1535
|
+
this.watchSetup(false);
|
|
1536
|
+
for (const oneshot of this.liveOneshots)
|
|
1537
|
+
oneshot.abort();
|
|
1538
|
+
this.liveOneshots.clear();
|
|
1539
|
+
this.wakeWaiters();
|
|
1540
|
+
await this.stopWatcher();
|
|
1541
|
+
this.retiring?.killNow();
|
|
1542
|
+
this.retiring = null;
|
|
1543
|
+
this.snapshots.clear();
|
|
1544
|
+
this.pagesCache.clear();
|
|
1545
|
+
this.excerptCache.clear();
|
|
1546
|
+
this.highlights = [];
|
|
1547
|
+
this.fragments = [];
|
|
1548
|
+
this.current = null;
|
|
1549
|
+
this.view = null;
|
|
1550
|
+
this.diagnostics = [];
|
|
1551
|
+
this.diagnosticsTotal = 0;
|
|
1552
|
+
if (this.buildDir) {
|
|
1553
|
+
await rm(this.buildDir, { recursive: true, force: true }).catch(() => undefined);
|
|
1554
|
+
this.buildDir = null;
|
|
1555
|
+
}
|
|
1556
|
+
this.listeners.clear();
|
|
1190
1557
|
}
|
|
1191
|
-
|
|
1192
|
-
|
|
1193
|
-
|
|
1194
|
-
|
|
1195
|
-
|
|
1196
|
-
|
|
1197
|
-
|
|
1198
|
-
|
|
1199
|
-
|
|
1200
|
-
|
|
1201
|
-
|
|
1202
|
-
|
|
1203
|
-
|
|
1204
|
-
|
|
1205
|
-
|
|
1206
|
-
|
|
1207
|
-
return line === void 0 ? diagnostic : { ...diagnostic, excerpt: line.replace(/\s+$/, "").slice(0, 300) };
|
|
1208
|
-
} catch {
|
|
1209
|
-
return diagnostic;
|
|
1558
|
+
/** Synchronously end the watch (process exit). */
|
|
1559
|
+
killNow() {
|
|
1560
|
+
this.closed = true;
|
|
1561
|
+
this.compileToken++;
|
|
1562
|
+
if (this.restartTimer)
|
|
1563
|
+
clearTimeout(this.restartTimer);
|
|
1564
|
+
this.restartTimer = null;
|
|
1565
|
+
this.indexing?.abort();
|
|
1566
|
+
for (const oneshot of this.liveOneshots)
|
|
1567
|
+
oneshot.abort();
|
|
1568
|
+
this.liveOneshots.clear();
|
|
1569
|
+
this.wakeWaiters();
|
|
1570
|
+
this.retiring?.killNow();
|
|
1571
|
+
this.retiring = null;
|
|
1572
|
+
this.watcher?.killNow();
|
|
1573
|
+
this.watcher = null;
|
|
1210
1574
|
}
|
|
1211
|
-
}
|
|
1212
|
-
// -------------------------------------------------------------------------
|
|
1213
|
-
async close() {
|
|
1214
|
-
this.closed = true;
|
|
1215
|
-
this.indexing?.abort();
|
|
1216
|
-
this.setupSubscribers = 0;
|
|
1217
|
-
this.watchSetup(false);
|
|
1218
|
-
await this.stopWatcher();
|
|
1219
|
-
if (this.buildDir)
|
|
1220
|
-
await rm(this.buildDir, { recursive: true, force: true }).catch(
|
|
1221
|
-
() => void 0
|
|
1222
|
-
);
|
|
1223
|
-
}
|
|
1224
|
-
/** Synchronously end the watch (process exit). */
|
|
1225
|
-
killNow() {
|
|
1226
|
-
this.watcher?.killNow();
|
|
1227
|
-
}
|
|
1228
1575
|
}
|
|
1229
|
-
|
|
1230
|
-
WorkspaceSession
|
|
1231
|
-
};
|
|
1232
|
-
//# sourceMappingURL=session.js.map
|
|
1576
|
+
//# sourceMappingURL=session.js.map
|