Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(pkg::compiler): expose incremental api #445

Merged
merged 2 commits into from
Jan 3, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
43 changes: 43 additions & 0 deletions packages/compiler/src/incr.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
use std::sync::Arc;

use typst_ts_core::{vector::incr::IncrDocServer, TypstDocument};
use wasm_bindgen::prelude::*;

#[wasm_bindgen]
pub struct IncrServer {
inner: IncrDocServer,
}

impl Default for IncrServer {
fn default() -> Self {
let mut this = Self {
inner: IncrDocServer::default(),
};
this.inner.set_should_attach_debug_info(true);
this
}
}

impl IncrServer {
pub(crate) fn update(&mut self, doc: Arc<TypstDocument>) -> Vec<u8> {
// evicted by compiler
// comemo::evict(30);

self.inner.pack_delta(doc)
}
}

#[wasm_bindgen]
impl IncrServer {
pub fn set_attach_debug_info(&mut self, attach: bool) {
self.inner.set_should_attach_debug_info(attach);
}

pub fn current(&mut self) -> Option<Vec<u8>> {
self.inner.pack_current()
}

pub fn reset(&mut self) {
self.inner = IncrDocServer::default();
}
}
22 changes: 21 additions & 1 deletion packages/compiler/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,10 +18,11 @@ use typst_ts_core::{
};
use wasm_bindgen::prelude::*;

use crate::utils::console_log;
use crate::{incr::IncrServer, utils::console_log};

pub mod builder;

mod incr;
pub(crate) mod utils;

#[wasm_bindgen]
Expand Down Expand Up @@ -311,6 +312,25 @@ impl TypstCompiler {

self.get_artifact(fmt)
}

pub fn create_incr_server(&mut self) -> Result<IncrServer, JsValue> {
Ok(IncrServer::default())
}

pub fn incr_compile(
&mut self,
main_file_path: String,
state: &mut IncrServer,
) -> Result<Vec<u8>, JsValue> {
self.compiler
.set_entry_file(Path::new(&main_file_path).to_owned());

let doc = self
.compiler
.compile(&mut Default::default())
.map_err(|e| format!("{e:?}"))?;
Ok(state.update(doc))
}
}

#[cfg(test)]
Expand Down
86 changes: 81 additions & 5 deletions packages/typst.ts/src/compiler.mts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
// @ts-ignore
import type * as typst from '@myriaddreamin/typst-ts-web-compiler/pkg/wasm-pack-shim.mjs';
import { buildComponent, globalFontPromises } from './init.mjs';
import { FsAccessModel, SemanticTokens, SemanticTokensLegend } from './internal.types.mjs';
import { FsAccessModel, SemanticTokens, SemanticTokensLegend, kObject } from './internal.types.mjs';

import { preloadRemoteFonts, type InitOptions } from './options.init.mjs';
import { LazyWasmModule } from './wasm.mjs';
Expand All @@ -11,10 +11,7 @@ import { LazyWasmModule } from './wasm.mjs';
*/
export type CompileFormat = 'vector' | 'pdf';

/**
* The options for compiling the document.
*/
export interface CompileOptions<F extends CompileFormat = any> {
interface TransientCompileOptions<F extends CompileFormat = any> {
/**
* The path of the main file.
*/
Expand All @@ -28,6 +25,61 @@ export interface CompileOptions<F extends CompileFormat = any> {
format?: F;
}

interface IncrementalCompileOptions {
/**
* The path of the main file.
*/
mainFilePath: string;
/**
* The format of the incrementally exported artifact.
* @default 'vector'
*/
format?: 'vector';
/**
* The incremental server for the document.
*/
incrementalServer: IncrementalServer;
}

/**
* The options for compiling the document.
*/
export type CompileOptions<F extends CompileFormat = any> =
| TransientCompileOptions<F>
| IncrementalCompileOptions;

export class IncrementalServer {
/**
* @internal
*/
[kObject]: typst.IncrServer;

constructor(s: typst.IncrServer) {
this[kObject] = s;
}

/**
* Reset the incremental server to the initial state.
*/
reset(): void {
this[kObject].reset();
}

/**
* Return current result.
*/
current(): Uint8Array | undefined {
return this[kObject].current();
}

/**
* Also attach the debug info to the result.
*/
setAttachDebugInfo(enable: boolean): void {
this[kObject].set_attach_debug_info(enable);
}
}

/**
* The interface of Typst compiler.
*/
Expand Down Expand Up @@ -130,6 +182,17 @@ export interface TypstCompiler {
resultId?: string;
offsetEncoding?: string;
}): Promise<SemanticTokens>;

/**
* experimental
* Run with an incremental server which holds the state of the document in wasm.
*
* @param {function(IncrementalServer): Promise<T>} f - The function to run with the incremental server.
* @returns {Promise<T>} - The result of the function.
*
* Note: the incremental server will be freed after the function is finished.
*/
withIncrementalServer<T>(f: (s: IncrementalServer) => Promise<T>): Promise<T>;
}

const gCompilerModule = new LazyWasmModule(async (bin?: any) => {
Expand Down Expand Up @@ -187,6 +250,12 @@ class TypstCompilerDriver {

compile(options: CompileOptions): Promise<Uint8Array> {
return new Promise<Uint8Array>(resolve => {
if ('incrementalServer' in options) {
resolve(
this.compiler.incr_compile(options.mainFilePath, options.incrementalServer[kObject]),
);
return;
}
resolve(this.compiler.compile(options.mainFilePath, options.format || 'vector'));
});
}
Expand Down Expand Up @@ -222,6 +291,13 @@ class TypstCompilerDriver {
});
}

async withIncrementalServer<T>(f: (s: IncrementalServer) => Promise<T>): Promise<T> {
const srv = new IncrementalServer(this.compiler.create_incr_server());
const res = f(srv);
srv[kObject].free();
return res;
}

async getAst(mainFilePath: string): Promise<string> {
return this.runSyncCodeUntilStable(() => this.compiler.get_ast(mainFilePath));
}
Expand Down