@vedivad/typst-web-service 0.8.0 → 0.9.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,3 +1,59 @@
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
+ }
56
+
1
57
  interface TypstAnalyzerOptions {
2
58
  /**
3
59
  * Explicit Worker instance. When omitted, an inlined blob worker is created automatically.
@@ -21,18 +77,24 @@ declare class TypstAnalyzer {
21
77
  private readonly proxy;
22
78
  private readonly worker;
23
79
  private versionCounter;
24
- private openedUris;
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;
25
85
  private constructor();
26
86
  static create(options: TypstAnalyzerOptions): Promise<TypstAnalyzer>;
27
87
  didOpen(uri: string, content: string): Promise<void>;
28
88
  didClose(uri: string): Promise<void>;
29
89
  /**
30
- * Notify the analyzer that a document has changed.
90
+ * Notify the analyzer that a document has changed. Skips the RPC when the
91
+ * content matches what the worker last saw.
31
92
  */
32
93
  didChange(uri: string, content: string): Promise<void>;
33
94
  /**
34
95
  * Batch document changes. Splits inputs into opens (first-time URIs) and
35
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.
36
98
  */
37
99
  didChangeMany(docs: Record<string, string>): Promise<void>;
38
100
  /**
@@ -40,31 +102,62 @@ declare class TypstAnalyzer {
40
102
  * in a single worker roundtrip.
41
103
  */
42
104
  didCloseMany(uris: string[]): Promise<void>;
43
- completion(uri: string, line: number, character: number): Promise<unknown>;
44
- hover(uri: string, line: number, character: number): Promise<unknown>;
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>;
45
119
  destroy(): void;
46
120
  }
47
121
 
48
- /** LSP Diagnostic as returned by tinymist. */
49
- interface LspDiagnostic {
50
- range: {
51
- start: {
52
- line: number;
53
- character: number;
54
- };
55
- end: {
56
- line: number;
57
- character: number;
58
- };
59
- };
60
- severity?: number;
61
- message: string;
62
- source?: string;
63
- }
64
-
65
- declare function normalizeUntitledUri(uri: string): string;
66
- declare function normalizePath(path: string): string;
122
+ /**
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.
141
+ */
142
+ /** `/path/to/file.typ` — leading-slash, forward slashes only. */
143
+ type Path = string;
144
+ /** `untitled:project/path/to/file.typ` — what tinymist's LSP consumes. */
145
+ type AnalyzerUri = string;
146
+ /** Ensure a path starts with a leading slash. Idempotent. */
147
+ 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
+ */
67
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;
68
161
 
69
162
  /** Source range for a diagnostic. All values are 0-indexed. */
70
163
  interface DiagnosticRange {
@@ -90,7 +183,7 @@ interface TypstCompilerOptions {
90
183
  /**
91
184
  * Explicit Worker instance. When omitted, an inlined blob worker is created automatically.
92
185
  * Use this for Vite apps to get proper source maps:
93
- * `await TypstCompiler.create({ worker: new Worker(new URL('typst-web-service/worker', import.meta.url)) })`
186
+ * `await TypstCompiler.create({ worker: new Worker(new URL('typst-web-service/compiler-worker', import.meta.url)) })`
94
187
  */
95
188
  worker?: Worker;
96
189
  /**
@@ -121,32 +214,34 @@ declare class TypstCompiler {
121
214
  private readonly proxy;
122
215
  private readonly worker;
123
216
  private readonly encoder;
124
- /** The most recent vector artifact from a compile, if any. */
125
- lastVector?: Uint8Array;
217
+ /** Last text content pushed per path. Drives own-RPC dedup. Invalidated by binary writes. */
218
+ private readonly content;
126
219
  private constructor();
127
220
  static create(options?: TypstCompilerOptions): Promise<TypstCompiler>;
128
221
  /**
129
- * Compile. Pass a source string (written to the entry path) or a map of
130
- * files to register before compiling; omit to compile whatever is currently
131
- * in the VFS (populated via setText/setBinary/setJson/setMany).
132
- * Defaults to compiling "/main.typ"; override with `entry`.
222
+ * Compile whatever is currently in the VFS (populated via
223
+ * setText/setBinary/setJson/setMany). Defaults to compiling "/main.typ";
224
+ * override with `entry`.
133
225
  */
134
- compile(source?: string | Record<string, string>, entry?: string): Promise<CompileResult>;
226
+ compile(entry?: string): Promise<CompileResult>;
135
227
  /**
136
- * Compile to PDF. Pass a source string (written to the entry path) or a map
137
- * of files to register before compiling; omit to compile whatever is
138
- * currently in the VFS (populated via setText/setBinary/setJson/setMany).
139
- * Defaults to compiling "/main.typ"; override with `entry`.
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`.
140
236
  */
141
- compilePdf(source?: string | Record<string, string>, entry?: string): Promise<Uint8Array>;
142
- /** Add or overwrite a text file in the virtual compiler filesystem. */
143
237
  setText(path: string, source: string): Promise<void>;
144
238
  /** Add or overwrite a JSON file in the virtual compiler filesystem. */
145
239
  setJson(path: string, value: unknown, replacer?: (this: unknown, key: string, value: unknown) => unknown, space?: string | number): Promise<void>;
146
240
  /**
147
241
  * Add or overwrite multiple files in the virtual compiler filesystem in a
148
- * single worker roundtrip. Strings are UTF-8 encoded; Uint8Arrays are passed
149
- * through.
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.
150
245
  */
151
246
  setMany(files: Record<string, string | Uint8Array>): Promise<void>;
152
247
  /** Add or overwrite a binary file in the virtual compiler filesystem. */
@@ -210,11 +305,24 @@ interface TypstProjectOptions {
210
305
  /** Default entry file path. Default: "/main.typ". */
211
306
  entry?: string;
212
307
  /**
213
- * Project root used to build stable analyzer URIs. Default: "/project".
214
- * URIs are formed as `untitled:<root-without-leading-slash><path>` — so
215
- * `/main.typ` becomes `untitled:project/main.typ`.
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.
216
312
  */
217
- rootPath?: string;
313
+ analyzerUriRoot?: string;
314
+ /**
315
+ * Idle time (ms) after the last VFS mutation before an auto-compile fires.
316
+ * Default: 0 — compile fires on the next macrotask. Set higher (e.g. 150) to
317
+ * coalesce rapid edits.
318
+ */
319
+ compileDebounceMs?: number;
320
+ /**
321
+ * Maximum time (ms) between auto-compiles during sustained mutation bursts.
322
+ * Guarantees progress while the user is actively typing. Default: 0 (no
323
+ * throttle — only debounce applies).
324
+ */
325
+ compileThrottleMs?: number;
218
326
  }
219
327
  /**
220
328
  * Coordinates a compiler + analyzer pair for multi-file Typst projects.
@@ -228,62 +336,146 @@ interface TypstProjectOptions {
228
336
  * await project.setMany({ "/main.typ": "...", "/utils.typ": "..." });
229
337
  * const result = await project.compile();
230
338
  */
339
+ type CompileListener = (result: CompileResult) => void;
231
340
  declare class TypstProject {
232
341
  private readonly compiler;
233
342
  private readonly analyzer?;
234
- private readonly rootPath;
235
- private readonly trackedTextPaths;
236
- /** Last content written via setText/setMany, per path. Used to skip redundant writes to compiler + analyzer. */
237
- private readonly lastSyncedContent;
343
+ private readonly analyzerUriRoot;
344
+ /**
345
+ * Tracked text files: path latest content observed. Presence in this map
346
+ * is the source of truth for "is this a tracked text file?"; insertion
347
+ * order drives the `files` getter. Per-sink dedup lives in the compiler and
348
+ * analyzer.
349
+ */
350
+ private readonly contentByPath;
351
+ private readonly compileListeners;
352
+ private readonly scheduler;
353
+ private compileVersion;
354
+ private _lastResult;
238
355
  private _entry;
356
+ private destroyed;
239
357
  constructor(options: TypstProjectOptions);
240
- /** Current entry file path. */
241
- get entry(): string;
358
+ /**
359
+ * Schedule an auto-compile after VFS mutations. Coalesces rapid calls via
360
+ * the configured debounce/throttle. Errors surface through `onCompile`
361
+ * listeners via a synthetic diagnostic; callers awaiting a specific compile
362
+ * should call `compile()` directly.
363
+ */
364
+ private scheduleCompile;
365
+ /** Current entry file path. Assign to change the sticky entry used by subsequent `compile()` calls. */
366
+ get entry(): Path;
367
+ set entry(path: Path);
242
368
  /** Whether an analyzer is attached. */
243
369
  get hasAnalyzer(): boolean;
244
- /** Change the sticky entry file used by subsequent compile() calls. */
245
- setEntry(path: string): void;
370
+ /**
371
+ * Most recent compile result, or `undefined` before the first compile has
372
+ * settled. Useful for lazy-mounted UI that subscribes after boot and needs
373
+ * an initial value.
374
+ */
375
+ get lastResult(): CompileResult | undefined;
376
+ /**
377
+ * Snapshot of tracked text file paths, in insertion order. Updated by
378
+ * `setText`, `setMany`, `remove`, and `clear`. Returns a fresh array — mutate
379
+ * freely without affecting project state.
380
+ */
381
+ get files(): Path[];
382
+ /**
383
+ * Current text content for a tracked file, or `undefined` if the path was
384
+ * never written via `setText`/`setMany` (or was removed). Read-through to the
385
+ * project's sync cache — lets consumers avoid shadowing the VFS themselves.
386
+ */
387
+ getText(path: Path): string | undefined;
246
388
  /**
247
389
  * Add or overwrite a text file. Goes to the compiler's VFS and, when an
248
- * analyzer is attached, to the analyzer as a document change. Redundant
249
- * calls with unchanged content are skipped.
390
+ * analyzer is attached, to the analyzer as a document change. No-op when
391
+ * the tracked path already has this exact content skips both worker RPCs
392
+ * and the auto-scheduled compile.
250
393
  */
251
- setText(path: string, content: string): Promise<void>;
394
+ setText(path: Path, content: string): Promise<void>;
252
395
  /**
253
396
  * Add or overwrite a JSON file. Compiler-only — the analyzer does not track
254
397
  * data files.
255
398
  */
256
- setJson(path: string, value: unknown): Promise<void>;
399
+ setJson(path: Path, value: unknown): Promise<void>;
257
400
  /** Add or overwrite a binary file. Compiler-only. */
258
- setBinary(path: string, content: ArrayBuffer | ArrayBufferView): Promise<void>;
401
+ setBinary(path: Path, content: ArrayBuffer | ArrayBufferView): Promise<void>;
259
402
  /**
260
403
  * Batch set multiple files. Strings route to both compiler and analyzer;
261
- * Uint8Array entries go to the compiler only.
404
+ * Uint8Array entries go to the compiler only. Strings matching the last
405
+ * tracked content for their path are skipped on both sinks. Binary entries
406
+ * always go through (no content cache, so no dedup).
262
407
  */
263
- setMany(files: Record<string, string | Uint8Array>): Promise<void>;
408
+ setMany(files: Record<Path, string | Uint8Array>): Promise<void>;
264
409
  /**
265
410
  * Remove a file. Always removed from the compiler's VFS; also closed on the
266
411
  * analyzer when it was previously tracked as text.
267
412
  */
268
- remove(path: string): Promise<void>;
413
+ remove(path: Path): Promise<void>;
269
414
  /** Clear all files from both compiler VFS and analyzer document set. */
270
415
  clear(): Promise<void>;
271
- /** Compile the current VFS state using the sticky entry. */
416
+ /**
417
+ * Subscribe to compile results. Fires after every `compile()` whose result is
418
+ * still current (stale results from out-of-order concurrent compiles are
419
+ * dropped). If a compile has already settled, the most recent result is
420
+ * delivered synchronously so late-mounted listeners aren't stuck blank until
421
+ * the next compile. Returns an unsubscribe function.
422
+ */
423
+ onCompile(listener: CompileListener): () => void;
424
+ /**
425
+ * Compile the current VFS state using the sticky entry. Errors from the
426
+ * underlying compiler are converted into a synthetic error diagnostic so
427
+ * callers and listeners always receive a `CompileResult`. Listeners are
428
+ * notified only for the most recent compile — results from an earlier call
429
+ * that resolves after a later one are suppressed.
430
+ *
431
+ * VFS mutations (`setText`, `remove`, etc.) auto-schedule a debounced
432
+ * compile; call this directly only when you need an awaitable handle on the
433
+ * result (e.g., to flush before rendering to PDF).
434
+ */
272
435
  compile(): Promise<CompileResult>;
273
436
  /** Compile the current VFS state to PDF using the sticky entry. */
274
437
  compilePdf(): Promise<Uint8Array>;
275
438
  private requireAnalyzer;
276
- /** Request completions at the given position. Throws when no analyzer is attached. */
277
- completion(path: string, line: number, character: number): Promise<unknown>;
278
- /** Request hover info at the given position. Throws when no analyzer is attached. */
279
- hover(path: string, line: number, character: number): Promise<unknown>;
280
- private toUri;
439
+ /**
440
+ * Request completion for `path` at `position`, using `source` as the
441
+ * current document state. One analyzer roundtrip; compiler is not touched —
442
+ * the compile sync path writes to the compiler separately. Throws when no
443
+ * analyzer is attached.
444
+ */
445
+ completion(path: Path, source: string, position: LspPosition): Promise<LspCompletionResponse>;
446
+ /**
447
+ * Request hover for `path` at `position`, using `source` as the current
448
+ * document state. One analyzer roundtrip; compiler is not touched. Throws
449
+ * when no analyzer is attached.
450
+ */
451
+ hover(path: Path, source: string, position: LspPosition): Promise<LspHover | null>;
452
+ /**
453
+ * Tear down the project and the services it owns. Destroys the attached
454
+ * compiler and analyzer, drops all listeners, and clears VFS tracking state.
455
+ * Idempotent — calling twice is a no-op. After destruction, further calls on
456
+ * the project are not supported; construct a new one.
457
+ *
458
+ * If you need to share a compiler or analyzer across projects, destroy them
459
+ * yourself and don't call this method — the project does not provide an
460
+ * ownership toggle.
461
+ */
462
+ destroy(): void;
281
463
  }
282
464
 
283
465
  interface TypstRendererOptions {
284
466
  /** URL to the typst-ts-renderer WASM binary. Defaults to jsDelivr CDN. */
285
467
  wasmUrl?: string;
286
468
  }
469
+ interface RenderedSvgPage {
470
+ /** Zero-based page index within the document. */
471
+ index: number;
472
+ /** Page width in typographic points. */
473
+ width: number;
474
+ /** Page height in typographic points. */
475
+ height: number;
476
+ /** Standalone SVG string for just this page. */
477
+ svg: string;
478
+ }
287
479
  /**
288
480
  * Converts Typst vector artifacts to SVG strings.
289
481
  *
@@ -303,6 +495,15 @@ declare class TypstRenderer {
303
495
  destroy(): Promise<void>;
304
496
  /** Render a Typst vector artifact to an SVG string. */
305
497
  renderSvg(vector: Uint8Array): Promise<string>;
498
+ /**
499
+ * Render a Typst vector artifact into one self-contained SVG string per
500
+ * physical page. The merged SVG is split by `<g class="typst-page">`
501
+ * children; each group's `data-page-width` / `data-page-height` give the
502
+ * page-local viewBox. Shared `<defs>` / `<style>` are duplicated into each
503
+ * page so the output SVGs render independently. Returns an empty array if
504
+ * the document has no page groups.
505
+ */
506
+ renderSvgPages(vector: Uint8Array): Promise<RenderedSvgPage[]>;
306
507
  }
307
508
 
308
- export { type CompileResult, type DiagnosticMessage, type DiagnosticRange, type FormatConfig, type FormatRangeResult, type LspDiagnostic, TypstAnalyzer, type TypstAnalyzerOptions, TypstCompiler, type TypstCompilerOptions, TypstFormatter, TypstProject, type TypstProjectOptions, TypstRenderer, normalizePath, normalizeRoot, normalizeUntitledUri };
509
+ 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 };