@vedivad/typst-web-service 0.15.3 → 0.17.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/dist/index.d.ts CHANGED
@@ -1,540 +1,148 @@
1
- /** LSP Position (0-based line and character). */
2
- interface LspPosition {
3
- line: number;
4
- character: number;
5
- }
6
- /** LSP Range. */
7
- interface LspRange {
8
- start: LspPosition;
9
- end: LspPosition;
10
- }
11
- /** LSP Diagnostic as returned by tinymist. */
12
- interface LspDiagnostic {
13
- range: LspRange;
14
- severity?: number;
15
- message: string;
16
- source?: string;
17
- }
18
- /** LSP MarkupContent (markdown or plaintext). */
19
- interface LspMarkupContent {
20
- kind: "markdown" | "plaintext";
21
- value: string;
22
- }
23
- /** LSP CompletionItem (subset actually populated by tinymist). */
24
- interface LspCompletionItem {
25
- label: string;
26
- kind?: number;
27
- detail?: string;
28
- documentation?: string | LspMarkupContent;
29
- insertText?: string;
30
- /** LSP InsertTextFormat: 1 = PlainText, 2 = Snippet (TextMate syntax). */
31
- insertTextFormat?: number;
32
- filterText?: string;
33
- sortText?: string;
34
- textEdit?: {
35
- range: LspRange;
36
- newText: string;
37
- };
38
- }
39
- /** LSP CompletionList. */
40
- interface LspCompletionList {
41
- isIncomplete: boolean;
42
- items: LspCompletionItem[];
43
- }
44
- /** Response shape for `textDocument/completion`. */
45
- type LspCompletionResponse = LspCompletionList | LspCompletionItem[] | null;
46
- /** LSP Hover contents — legacy and current forms tinymist may emit. */
47
- type LspHoverContents = string | LspMarkupContent | (string | {
48
- language: string;
49
- value: string;
50
- })[];
51
- /** Response shape for `textDocument/hover`. */
52
- interface LspHover {
53
- contents: LspHoverContents;
54
- range?: LspRange;
55
- }
1
+ import { CompileResult, CompletionResponse, Hover, HlSpan } from 'typsten';
2
+ export { CompileResult, Completion, CompletionKind, CompletionResponse, Diagnostic, HlSpan, Hover, HoverKind, Location, PageInfo, Severity } from 'typsten';
56
3
 
57
- interface TypstAnalyzerOptions {
58
- /**
59
- * Explicit Worker instance. When omitted, an inlined blob worker is created automatically.
60
- * Use this for Vite apps:
61
- * `await TypstAnalyzer.create({ worker: new Worker(new URL('typst-web-service/analyzer-worker', import.meta.url), { type: 'module' }) })`
62
- */
63
- worker?: Worker;
64
- /**
65
- * URL to the tinymist WASM binary.
66
- * Required — there is no default CDN URL for tinymist-web.
67
- */
68
- wasmUrl: string;
69
- }
70
- /**
71
- * Manages a tinymist language server in a Web Worker. Provides LSP-based
72
- * completion and hover for Typst documents.
73
- *
74
- * const analyzer = await TypstAnalyzer.create({ wasmUrl: '...' });
75
- */
76
- declare class TypstAnalyzer {
77
- private readonly proxy;
78
- private readonly worker;
79
- private versionCounter;
80
- /**
81
- * Last content pushed to the worker per URI. Presence is the source of
82
- * truth for "is this URI opened on the worker?"; value drives own-RPC dedup.
83
- */
84
- private readonly content;
85
- private constructor();
86
- static create(options: TypstAnalyzerOptions): Promise<TypstAnalyzer>;
87
- didOpen(uri: string, content: string): Promise<void>;
88
- didClose(uri: string): Promise<void>;
89
- /**
90
- * Notify the analyzer that a document has changed. Skips the RPC when the
91
- * content matches what the worker last saw.
92
- */
93
- didChange(uri: string, content: string): Promise<void>;
94
- /**
95
- * Batch document changes. Splits inputs into opens (first-time URIs) and
96
- * changes (already-open URIs) and sends them in a single worker roundtrip.
97
- * Skips unchanged documents; returns without an RPC if nothing is pending.
98
- */
99
- didChangeMany(docs: Record<string, string>): Promise<void>;
100
- /**
101
- * Batch document closes. Filters to currently-open URIs and sends the set
102
- * in a single worker roundtrip.
103
- */
104
- didCloseMany(uris: string[]): Promise<void>;
105
- /**
106
- * Request completion at `position` for `uri`, with `content` as the current
107
- * document state. Bundles the didChange notification with the request in one
108
- * worker roundtrip; degrades to a plain completion request when the worker
109
- * already has this exact content.
110
- */
111
- completion(uri: string, content: string, position: LspPosition): Promise<LspCompletionResponse>;
112
- /**
113
- * Request hover at `position` for `uri`, with `content` as the current
114
- * document state. Bundles the didChange notification with the request in one
115
- * worker roundtrip; degrades to a plain hover request when the worker
116
- * already has this exact content.
117
- */
118
- hover(uri: string, content: string, position: LspPosition): Promise<LspHover | null>;
119
- destroy(): void;
120
- }
4
+ /** UTF-16 string offset (CodeMirror position) -> UTF-8 byte offset (typsten). */
5
+ declare function cmOffsetToByte(text: string, offset: number): number;
6
+ /** UTF-8 byte offset (typsten) -> UTF-16 string offset (CodeMirror position). */
7
+ declare function byteToCmOffset(text: string, byte: number): number;
121
8
 
122
9
  /**
123
- * Two addressing schemes live in this codebase. This file is the only place
124
- * that knows how they relate. Keeping the vocabulary and conversions colocated
125
- * means a new contributor can read one file and understand the model.
126
- *
127
- * 1. Path — "/main.typ". Always leading-slash, always forward slashes.
128
- * Used by the compiler VFS, the `TypstProject` public API,
129
- * and the `typstFilePath` facet. Addresses a file within
130
- * the project.
131
- *
132
- * 2. AnalyzerUri — "untitled:project/main.typ". What tinymist's LSP expects.
133
- * Derived from a Path plus the analyzer URI root.
134
- *
135
- * The types below are type aliases, not branded/opaque types. That's
136
- * deliberate: callers can pass string literals where a Path is expected
137
- * without wrapping, and the aliases only serve as self-documenting
138
- * signatures. Ingress points still need to call `normalizePath` to defend
139
- * against un-normalized input — the alias does not imply the string has
140
- * been normalized.
10
+ * Project file paths. `/main.typ` form, leading slash, forward slashes only.
11
+ * `@preview/...` package paths bypass this (they are pushed to the VFS verbatim).
141
12
  */
142
- /** `/path/to/file.typ` leading-slash, forward slashes only. */
13
+ /** `/path/to/file.typ`, leading-slash, forward slashes only. */
143
14
  type Path = string;
144
- /** `untitled:project/path/to/file.typ` — what tinymist's LSP consumes. */
145
- type AnalyzerUri = string;
146
15
  /** Ensure a path starts with a leading slash. Idempotent. */
147
16
  declare function normalizePath(path: string): Path;
148
- /**
149
- * Normalize an analyzer URI root. Ensures leading slash, strips trailing
150
- * slashes. Special-cases "/" → "" so URIs don't end up with a leading
151
- * `untitled://`.
152
- */
153
- declare function normalizeRoot(rootPath: string): string;
154
- /**
155
- * Build the analyzer URI for a given project path. `root` is expected to
156
- * already be normalized (see `normalizeRoot`).
157
- *
158
- * pathToAnalyzerUri("/main.typ", "/project") -> "untitled:project/main.typ"
159
- */
160
- declare function pathToAnalyzerUri(path: Path, root: string): AnalyzerUri;
161
-
162
- /** Source range for a diagnostic. All values are 0-indexed. */
163
- interface DiagnosticRange {
164
- startLine: number;
165
- startCol: number;
166
- endLine: number;
167
- endCol: number;
168
- }
169
- interface DiagnosticMessage {
170
- package: string;
171
- path: string;
172
- severity: "Error" | "Warning" | "Info";
173
- range: DiagnosticRange;
174
- message: string;
175
- }
176
-
177
- interface CompileResult {
178
- diagnostics: DiagnosticMessage[];
179
- /** Vector artifact bytes from the compiler, usable with TypstRenderer for SVG rendering. */
180
- vector?: Uint8Array;
181
- }
182
- interface TypstCompilerOptions {
183
- /**
184
- * Explicit Worker instance. When omitted, an inlined blob worker is created automatically.
185
- * Use this for Vite apps to get proper source maps:
186
- * `await TypstCompiler.create({ worker: new Worker(new URL('typst-web-service/compiler-worker', import.meta.url)) })`
187
- */
188
- worker?: Worker;
189
- /**
190
- * URL to the typst-ts-web-compiler WASM binary.
191
- * Defaults to the matching version on jsDelivr CDN.
192
- * Override with a local asset URL for offline support or faster load:
193
- * `new URL('@myriaddreamin/typst-ts-web-compiler/pkg/typst_ts_web_compiler_bg.wasm', import.meta.url).href`
194
- */
195
- wasmUrl?: string;
196
- /** Font URLs to load into the Typst compiler. Defaults to Roboto from jsDelivr. */
197
- fonts?: string[];
198
- /**
199
- * Enable fetching @preview/ packages from packages.typst.org on demand.
200
- * Default: true.
201
- */
202
- packages?: boolean;
203
- }
204
- /**
205
- * Manages a Typst compiler worker. Create one instance and share it across
206
- * all extensions (linter, autocomplete, preview, etc.).
207
- *
208
- * await TypstCompiler.create() // blob worker, defaults
209
- * await TypstCompiler.create({ wasmUrl: '...' }) // blob worker, custom WASM
210
- * await TypstCompiler.create({ worker: myWorker }) // explicit Worker (Vite)
211
- * await TypstCompiler.create({ worker: myWorker, fonts: [...] }) // explicit Worker + options
212
- */
213
- declare class TypstCompiler {
214
- private readonly proxy;
215
- private readonly worker;
216
- private readonly encoder;
217
- /** Last text content pushed per path. Drives own-RPC dedup. Invalidated by binary writes. */
218
- private readonly content;
219
- private constructor();
220
- static create(options?: TypstCompilerOptions): Promise<TypstCompiler>;
221
- /**
222
- * Compile whatever is currently in the VFS (populated via
223
- * setText/setBinary/setJson/setMany). Defaults to compiling "/main.typ";
224
- * override with `entry`.
225
- */
226
- compile(entry?: string): Promise<CompileResult>;
227
- /**
228
- * Compile to PDF. Operates on whatever is currently in the VFS (populated
229
- * via setText/setBinary/setJson/setMany). Defaults to compiling "/main.typ";
230
- * override with `entry`.
231
- */
232
- compilePdf(entry?: string): Promise<Uint8Array>;
233
- /**
234
- * Add or overwrite a text file in the virtual compiler filesystem. Skips
235
- * the worker RPC when `source` matches the last value pushed for `path`.
236
- */
237
- setText(path: string, source: string): Promise<void>;
238
- /** Add or overwrite a JSON file in the virtual compiler filesystem. */
239
- setJson(path: string, value: unknown, replacer?: (this: unknown, key: string, value: unknown) => unknown, space?: string | number): Promise<void>;
240
- /**
241
- * Add or overwrite multiple files in the virtual compiler filesystem in a
242
- * single worker roundtrip. Strings are UTF-8 encoded; Uint8Arrays are
243
- * passed through. Text entries unchanged since their last push are skipped;
244
- * binary entries always push and invalidate the text cache for their path.
245
- */
246
- setMany(files: Record<string, string | Uint8Array>): Promise<void>;
247
- /** Add or overwrite a binary file in the virtual compiler filesystem. */
248
- setBinary(path: string, content: ArrayBuffer | ArrayBufferView): Promise<void>;
249
- /** Remove a file from the virtual compiler filesystem. */
250
- remove(path: string): Promise<void>;
251
- /** Clear all virtual files from the compiler filesystem. */
252
- clear(): Promise<void>;
253
- destroy(): void;
254
- }
255
17
 
256
- interface FormatConfig {
257
- /** Number of spaces per indentation level. Default: 2 */
258
- tab_spaces?: number;
259
- /** Maximum line width. Default: 80 */
260
- max_width?: number;
261
- /** Maximum consecutive blank lines allowed. */
262
- blank_lines_upper_bound?: number;
263
- /** Collapse consecutive whitespace in markup to a single space. */
264
- collapse_markup_spaces?: boolean;
265
- /** Sort import items alphabetically. */
266
- reorder_import_items?: boolean;
267
- /** Wrap text in markup to fit within max_width. Implies collapse_markup_spaces. */
268
- wrap_text?: boolean;
269
- }
270
- interface FormatRangeResult {
271
- /** Start index (UTF-16) of the actual formatted range. */
272
- start: number;
273
- /** End index (UTF-16) of the actual formatted range. */
274
- end: number;
275
- /** The formatted text for the range. */
276
- text: string;
277
- }
278
- /**
279
- * Typst code formatter powered by typstyle.
280
- *
281
- * Runs on the main thread — typstyle is lightweight and fast.
282
- * The WASM module is loaded lazily on first format call.
283
- * Requires a bundler that supports WASM imports (e.g. Vite, webpack).
284
- *
285
- * const formatter = TypstFormatter.create({ tab_spaces: 2, max_width: 80 });
286
- * const formatted = await formatter.format(source);
287
- */
288
- declare class TypstFormatter {
289
- private config;
290
- private constructor();
291
- static create(config?: FormatConfig): TypstFormatter;
292
- /** Format an entire Typst source string. */
293
- format(source: string): Promise<string>;
294
- /** Format a range within a Typst source string. Indices are UTF-16 code units. */
295
- formatRange(source: string, start: number, end: number): Promise<FormatRangeResult>;
18
+ /** A rendered page: its index, dimensions (in points), and standalone SVG. */
19
+ interface RenderedSvgPage {
20
+ index: number;
21
+ width: number;
22
+ height: number;
23
+ svg: string;
296
24
  }
297
25
 
298
- interface TypstProjectOptions {
299
- compiler: TypstCompiler;
300
- /**
301
- * Optional analyzer. When provided, text file operations also sync with the
302
- * analyzer so completions / hover reflect the current state.
303
- */
304
- analyzer?: TypstAnalyzer;
26
+ interface TypstProjectCreateOptions {
305
27
  /** Default entry file path. Default: "/main.typ". */
306
28
  entry?: string;
307
- /**
308
- * Prefix used to build the `untitled:` URIs handed to the analyzer.
309
- * Default: "/project". A path of `/main.typ` becomes
310
- * `untitled:project/main.typ`. Only affects URI construction — the compiler
311
- * and project VFS use the raw paths unchanged.
312
- */
313
- analyzerUriRoot?: string;
314
- /**
315
- * Scheduling for auto-compiles after VFS mutations. Mutations debounce by
316
- * `debounceMs`; `maxWaitMs` caps how long the debounce can keep deferring
317
- * during sustained edits so the user still sees progress.
318
- */
29
+ /** Auto-compile scheduling after VFS mutations. */
319
30
  autoCompile?: AutoCompileOptions;
320
31
  }
321
32
  interface AutoCompileOptions {
322
- /**
323
- * Idle time (ms) after the last VFS mutation before a compile fires.
324
- * Default: 0 — compile fires on the next macrotask. Set higher (e.g. 150) to
325
- * coalesce rapid edits.
326
- */
33
+ /** Idle time (ms) after the last mutation before a compile fires. Default: 0. */
327
34
  debounceMs?: number;
328
- /**
329
- * Maximum time (ms) the debounce is allowed to defer a compile during
330
- * sustained mutation bursts. Default: 0 (no cap — pure debounce).
331
- */
35
+ /** Max time (ms) the debounce may defer during sustained edits. Default: 0. */
332
36
  maxWaitMs?: number;
333
37
  }
38
+ type CompileListener = (result: CompileResult) => void;
334
39
  /**
335
- * Coordinates a compiler + analyzer pair for multi-file Typst projects.
40
+ * Multi-file Typst project backed by a single typsten wasm worker. Owns the
41
+ * VFS; editors push `setText` edits as the user types; the project mirrors them
42
+ * to the worker, fetches `@preview` packages on demand, and compiles or renders
43
+ * against the current state.
336
44
  *
337
- * Owns the project's virtual filesystem state. Editors push incremental
338
- * `setText` updates as the user types; the project mirrors those edits to
339
- * both the compiler's shadow VFS and the analyzer's open-document set, then
340
- * compiles or services LSP requests against the current state.
341
- *
342
- * const project = new TypstProject({ compiler, analyzer });
343
- * await project.setMany({ "/main.typ": "...", "/utils.typ": "..." });
344
- * const result = await project.compile();
45
+ * const project = await TypstProject.create();
46
+ * await project.setMany({ "/main.typ": "..." });
47
+ * const { pages } = await project.compile();
48
+ * const svg = await project.renderPage(0);
345
49
  */
346
- type CompileListener = (result: CompileResult) => void;
347
50
  declare class TypstProject {
348
- private readonly compiler;
349
- private readonly analyzer?;
350
- private readonly analyzerUriRoot;
51
+ private readonly engine;
52
+ private readonly worker;
351
53
  /**
352
- * Tracked text files: path latest content observed. Presence in this map
353
- * is the source of truth for "is this a tracked text file?"; insertion
354
- * order drives the `files` getter. Per-sink dedup lives in the compiler and
355
- * analyzer.
54
+ * Tracked project files: the text content for a text file, or `null` for a
55
+ * binary one. Drives dedup, `getText`, `files`, and `clear`. (Cached `@preview`
56
+ * package files live only in the worker VFS, never here.)
356
57
  */
357
- private readonly contentByPath;
58
+ private readonly tracked;
358
59
  private readonly compileListeners;
359
60
  private readonly scheduler;
61
+ private readonly packageLoader;
360
62
  private compileVersion;
361
63
  private _lastResult;
362
64
  private _entry;
363
65
  private destroyed;
364
- private invokeListener;
365
- constructor(options: TypstProjectOptions);
66
+ private constructor();
67
+ /** Create a project: spin up the worker, init the wasm, set the entry. */
68
+ static create(options?: TypstProjectCreateOptions): Promise<TypstProject>;
69
+ private scheduleCompile;
366
70
  /**
367
- * Schedule an auto-compile after VFS mutations. Coalesces rapid calls via
368
- * the configured debounce/throttle. Errors surface through `onCompile`
369
- * listeners via a synthetic diagnostic; callers awaiting a specific compile
370
- * should call `compile()` directly.
71
+ * Mirror text into the VFS without scheduling a compile. Returns the in-flight
72
+ * write to await, or `null` if the content is unchanged (deduped to a no-op).
371
73
  */
372
- private scheduleCompile;
373
- /** Current entry file path. Assign to change the sticky entry used by subsequent `compile()` calls. */
74
+ private writeText;
75
+ /** Mirror binary bytes into the VFS (always writes; binaries are not deduped). */
76
+ private writeBinary;
374
77
  get entry(): Path;
375
78
  set entry(path: Path);
376
- /** Whether an analyzer is attached. */
377
- get hasAnalyzer(): boolean;
378
- /**
379
- * Most recent compile result, or `undefined` before the first compile has
380
- * settled. Useful for lazy-mounted UI that subscribes after boot and needs
381
- * an initial value.
382
- */
79
+ /** Most recent compile result, or `undefined` before the first compile. */
383
80
  get lastResult(): CompileResult | undefined;
384
- /**
385
- * Snapshot of tracked text file paths, in insertion order. Updated by
386
- * `setText`, `setMany`, `remove`, and `clear`. Returns a fresh array — mutate
387
- * freely without affecting project state.
388
- */
81
+ /** Tracked text file paths, in insertion order (fresh array). */
389
82
  get files(): Path[];
390
- /**
391
- * Current text content for a tracked file, or `undefined` if the path was
392
- * never written via `setText`/`setMany` (or was removed). Read-through to the
393
- * project's sync cache — lets consumers avoid shadowing the VFS themselves.
394
- */
83
+ /** Current text for a tracked file, or `undefined` (binary or absent). */
395
84
  getText(path: Path): string | undefined;
396
- /**
397
- * Add or overwrite a text file. Goes to the compiler's VFS and, when an
398
- * analyzer is attached, to the analyzer as a document change. No-op when
399
- * the tracked path already has this exact content — skips both worker RPCs
400
- * and the auto-scheduled compile.
401
- */
85
+ /** Add or overwrite a text file. No-op if unchanged. */
402
86
  setText(path: Path, content: string): Promise<void>;
403
- /**
404
- * Add or overwrite a JSON file. The analyzer does not track data files, but
405
- * if `path` was previously tracked as text the analyzer document is closed
406
- * and the text entry retired so the three views stay consistent.
407
- */
408
- setJson(path: Path, value: unknown): Promise<void>;
409
- /**
410
- * Add or overwrite a binary file. If `path` was previously tracked as text,
411
- * the analyzer document is closed and the text entry retired in the same
412
- * call so the compiler / analyzer / project views stay consistent.
413
- */
87
+ /** Add or overwrite a binary file (retires any text tracking for the path). */
414
88
  setBinary(path: Path, content: ArrayBuffer | ArrayBufferView): Promise<void>;
415
- /**
416
- * Batch set multiple files. Strings route to both compiler and analyzer;
417
- * Uint8Array entries go to the compiler only. Strings matching the last
418
- * tracked content for their path are skipped on both sinks. Binary entries
419
- * always go through (no content cache, so no dedup).
420
- */
89
+ /** Batch set files. Strings dedup against tracked content; binaries always write. */
421
90
  setMany(files: Record<Path, string | Uint8Array>): Promise<void>;
422
- /**
423
- * Remove a file. Always removed from the compiler's VFS; also closed on the
424
- * analyzer when it was previously tracked as text.
425
- */
91
+ /** Remove a file from the VFS. */
426
92
  remove(path: Path): Promise<void>;
427
- /** Clear all files from both compiler VFS and analyzer document set. */
93
+ /** Remove all tracked project files (cached `@preview` packages are kept). */
428
94
  clear(): Promise<void>;
429
95
  /**
430
- * Subscribe to compile results. Fires after every `compile()` whose result is
431
- * still current (stale results from out-of-order concurrent compiles are
432
- * dropped). If a compile has already settled, the most recent result is
433
- * delivered synchronously so late-mounted listeners aren't stuck blank until
434
- * the next compile. Returns an unsubscribe function.
96
+ * Register a font (TTF/OTF, or TTC collection bytes) so compilation can use
97
+ * it, then recompile. The engine bundles default body, math, and monospace
98
+ * fonts; use this to add families it does not ship (e.g. CJK or a custom
99
+ * font). Fonts persist for the project's lifetime.
100
+ */
101
+ addFont(bytes: Uint8Array): Promise<void>;
102
+ /**
103
+ * Subscribe to compile results. Late subscribers get `lastResult` synchronously.
104
+ * Returns an unsubscribe function.
435
105
  */
436
106
  onCompile(listener: CompileListener): () => void;
437
107
  /**
438
- * Compile the current VFS state using the sticky entry. Errors from the
439
- * underlying compiler are converted into a synthetic error diagnostic so
440
- * callers and listeners always receive a `CompileResult`. Listeners are
441
- * notified only for the most recent compile — results from an earlier call
442
- * that resolves after a later one are suppressed.
443
- *
444
- * VFS mutations (`setText`, `remove`, etc.) auto-schedule a debounced
445
- * compile; call this directly only when you need an awaitable handle on the
446
- * result (e.g., to flush before rendering to PDF).
108
+ * Compile the current VFS state. Fetches any referenced `@preview` packages
109
+ * first. Errors become a synthetic diagnostic. Listeners fire only for the
110
+ * most recent compile (stale results are dropped).
447
111
  */
448
112
  compile(): Promise<CompileResult>;
449
- /** Compile the current VFS state to PDF using the sticky entry. */
450
- compilePdf(): Promise<Uint8Array>;
451
- private requireAnalyzer;
113
+ /** Render a single page of the last compile to SVG, or `undefined`. */
114
+ renderPage(index: number): Promise<string | undefined>;
452
115
  /**
453
- * Request completion for `path` at `position`, using `source` as the
454
- * current document state. Pure analyzer query neither the compiler VFS
455
- * nor project tracking (`files`/`getText`) is touched. Throws when no
456
- * analyzer is attached.
116
+ * Render pages `[start, end)` as `RenderedSvgPage`s (index + dims + svg),
117
+ * zipping the SVG strings with the page metadata from the last compile.
457
118
  */
458
- completion(path: Path, source: string, position: LspPosition): Promise<LspCompletionResponse>;
119
+ renderedPages(start: number, end: number): Promise<RenderedSvgPage[]>;
459
120
  /**
460
- * Request hover for `path` at `position`, using `source` as the current
461
- * document state. Pure analyzer query neither the compiler VFS nor
462
- * project tracking is touched. Throws when no analyzer is attached.
121
+ * Export the last compile as a PDF, or `undefined` if nothing has compiled
122
+ * yet. The bytes are a fresh `Uint8Array` (copied across the worker boundary).
463
123
  */
464
- hover(path: Path, source: string, position: LspPosition): Promise<LspHover | null>;
124
+ exportPdf(): Promise<Uint8Array | undefined>;
125
+ /** Completions at a CodeMirror `offset` in `path`, using `source` as the live buffer. */
126
+ completion(path: Path, source: string, offset: number, explicit?: boolean): Promise<CompletionResponse | undefined>;
127
+ /** Hover tooltip at a CodeMirror `offset` in `path`, using `source` as the live buffer. */
128
+ hover(path: Path, source: string, offset: number): Promise<Hover | undefined>;
129
+ /** Format `source` (the live buffer for `path`); returns the formatted text or `undefined`. */
130
+ format(path: Path, source: string): Promise<string | undefined>;
465
131
  /**
466
- * Tear down the project and the services it owns. Destroys the attached
467
- * compiler and analyzer, drops all listeners, and clears VFS tracking state.
468
- * Idempotent calling twice is a no-op. After destruction, further calls on
469
- * the project are not supported; construct a new one.
470
- *
471
- * If you need to share a compiler or analyzer across projects, destroy them
472
- * yourself and don't call this method — the project does not provide an
473
- * ownership toggle.
132
+ * Syntax-highlight `source` over the CodeMirror window `[from, to)` (UTF-16
133
+ * offsets; defaults to the whole string). Returns spans whose `from`/`to` are
134
+ * CodeMirror offsets, ready to drive decorations. Stateless: the worker parses
135
+ * `source` directly via typst-syntax, so this neither reads nor mutates the
136
+ * VFS and works for any text (the live buffer, a hover code snippet).
474
137
  */
475
- destroy(): void;
476
- }
477
-
478
- interface TypstRendererOptions {
138
+ highlight(source: string, from?: number, to?: number): Promise<HlSpan[]>;
479
139
  /**
480
- * Explicit Worker instance. When omitted, an inlined blob worker is created
481
- * automatically. Use this for Vite apps to get proper source maps:
482
- * `TypstRenderer.create({ worker: new Worker(new URL('typst-web-service/renderer-worker', import.meta.url)) })`
140
+ * Syntax-highlight `source` to nested `<span class="typ-*">` HTML for a static
141
+ * context (e.g. a hover tooltip). Stateless, like `highlight`.
483
142
  */
484
- worker?: Worker;
485
- /** URL to the typst-ts-renderer WASM binary. Defaults to jsDelivr CDN. */
486
- wasmUrl?: string;
487
- }
488
- interface RenderedSvgPage {
489
- /** Zero-based page index within the document. */
490
- index: number;
491
- /** Page width in typographic points. */
492
- width: number;
493
- /** Page height in typographic points. */
494
- height: number;
495
- /** Standalone SVG string for just this page. */
496
- svg: string;
497
- }
498
- /**
499
- * Converts Typst vector artifacts to SVG strings, off the main thread.
500
- *
501
- * Wraps `@myriaddreamin/typst.ts`'s renderer hosted in a Web Worker — the
502
- * WASM init, vector → SVG conversion, and base64 image-embedding all happen
503
- * off-thread. Returned SVG strings cross via Comlink; page splitting runs on
504
- * the main thread (Workers don't have `DOMParser`).
505
- *
506
- * const renderer = TypstRenderer.create();
507
- * const svg = await renderer.renderSvg(vector);
508
- */
509
- declare class TypstRenderer {
510
- #private;
511
- private constructor();
512
- static create(options?: TypstRendererOptions): TypstRenderer;
513
- /** Terminate the worker. The instance is unusable afterwards. */
143
+ highlightHtml(source: string): Promise<string>;
144
+ /** Tear down the worker and drop all state. Idempotent. */
514
145
  destroy(): void;
515
- /**
516
- * Render a Typst vector artifact to a single merged SVG string.
517
- *
518
- * Ownership of `vector.buffer` transfers to the worker (zero-copy).
519
- * Don't reuse the vector after passing it in — accessing its bytes from
520
- * the main thread after this call is undefined behavior.
521
- *
522
- * Concurrent calls are serialized in the worker: while a render is in
523
- * flight, the most recent `vector` becomes the next render and any
524
- * intermediate calls are dropped. All overlapping callers share one
525
- * returned promise that resolves with the LAST rendered SVG — your
526
- * specific vector may have been superseded.
527
- */
528
- renderSvg(vector: Uint8Array): Promise<string>;
529
- /**
530
- * Render a Typst vector artifact into one self-contained SVG string per
531
- * physical page. The merged SVG is split by `<g class="typst-page">`
532
- * children; each group's `data-page-width` / `data-page-height` give the
533
- * page-local viewBox. Shared `<defs>` / `<style>` are duplicated into each
534
- * page so the output SVGs render independently. Returns an empty array if
535
- * the document has no page groups.
536
- */
537
- renderSvgPages(vector: Uint8Array): Promise<RenderedSvgPage[]>;
538
146
  }
539
147
 
540
- export { type AnalyzerUri, type CompileResult, type DiagnosticMessage, type DiagnosticRange, type FormatConfig, type FormatRangeResult, type LspCompletionItem, type LspCompletionList, type LspCompletionResponse, type LspDiagnostic, type LspHover, type LspHoverContents, type LspMarkupContent, type LspPosition, type LspRange, type Path, type RenderedSvgPage, TypstAnalyzer, type TypstAnalyzerOptions, TypstCompiler, type TypstCompilerOptions, TypstFormatter, TypstProject, type TypstProjectOptions, TypstRenderer, type TypstRendererOptions, normalizePath, normalizeRoot, pathToAnalyzerUri };
148
+ export { type AutoCompileOptions, type CompileListener, type Path, type RenderedSvgPage, TypstProject, type TypstProjectCreateOptions, byteToCmOffset, cmOffsetToByte, normalizePath };