@vedivad/typst-web-service 0.15.3 → 0.15.4
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/compiler-worker.js +23 -24
- package/dist/compiler-worker.js.map +1 -1
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -14,7 +14,7 @@ function createBlobWorker(code) {
|
|
|
14
14
|
return worker;
|
|
15
15
|
}
|
|
16
16
|
function createWorker() {
|
|
17
|
-
return createBlobWorker('"use strict";(()=>{var ne=Object.defineProperty;var vt=(e,t)=>()=>(e&&(t=e(e=0)),t);var re=(e,t)=>{for(var n in t)ne(e,n,{get:t[n],enumerable:!0})};function f(e){N===S.length&&S.push(S.length+1);let t=N;return N=S[t],S[t]=e,t}function gt(e,t){if(!(e instanceof t))throw new Error(`expected instance of ${t.name}`)}function lt(e){let t=typeof e;if(t=="number"||t=="boolean"||e==null)return`${e}`;if(t=="string")return`"${e}"`;if(t=="symbol"){let o=e.description;return o==null?"Symbol":`Symbol(${o})`}if(t=="function"){let o=e.name;return typeof o=="string"&&o.length>0?`Function(${o})`:"Function"}if(Array.isArray(e)){let o=e.length,s="[";o>0&&(s+=lt(e[0]));for(let _=1;_<o;_++)s+=", "+lt(e[_]);return s+="]",s}let n=/\\[object ([^\\]]+)\\]/.exec(toString.call(e)),r;if(n&&n.length>1)r=n[1];else return toString.call(e);if(r=="Object")try{return"Object("+JSON.stringify(e)+")"}catch{return"Object"}return e instanceof Error?`${e.name}: ${e.message}\n${e.stack}`:r}function Ie(e){e<132||(S[e]=N,N=e)}function ke(e,t){e=e>>>0;let n=a(),r=[];for(let o=e;o<e+4*t;o+=4)r.push(g(n.getUint32(o,!0)));return r}function Se(e,t){return e=e>>>0,Fe().subarray(e/4,e/4+t)}function wt(e,t){return e=e>>>0,O().subarray(e/1,e/1+t)}function a(){return(M===null||M.buffer.detached===!0||M.buffer.detached===void 0&&M.buffer!==i.memory.buffer)&&(M=new DataView(i.memory.buffer)),M}function I(e,t){return e=e>>>0,Re(e,t)}function Fe(){return(U===null||U.byteLength===0)&&(U=new Uint32Array(i.memory.buffer)),U}function O(){return(W===null||W.byteLength===0)&&(W=new Uint8Array(i.memory.buffer)),W}function u(e){return S[e]}function T(e,t){try{return e.apply(this,t)}catch(n){i.__wbindgen_export3(f(n))}}function v(e){return e==null}function Ae(e,t,n,r){let o={a:e,b:t,cnt:1,dtor:n},s=(..._)=>{o.cnt++;let c=o.a;o.a=0;try{return r(c,o.b,..._)}finally{o.a=c,s._wbg_cb_unref()}};return s._wbg_cb_unref=()=>{--o.cnt===0&&(o.dtor(o.a,o.b),o.a=0,Ct.unregister(o))},Ct.register(s,o,o),s}function Ut(e,t){let n=t(e.length*1,1)>>>0;return O().set(e,n/1),b=e.length,n}function nt(e,t){let n=t(e.length*4,4)>>>0,r=a();for(let o=0;o<e.length;o++)r.setUint32(n+4*o,f(e[o]),!0);return b=e.length,n}function h(e,t,n){if(n===void 0){let c=q.encode(e),l=t(c.length,1)>>>0;return O().subarray(l,l+c.length).set(c),b=c.length,l}let r=e.length,o=t(r,1)>>>0,s=O(),_=0;for(;_<r;_++){let c=e.charCodeAt(_);if(c>127)break;s[o+_]=c}if(_!==r){_!==0&&(e=e.slice(_)),o=n(o,r,r=_+e.length*3,1)>>>0;let c=O().subarray(o+_,o+r),l=q.encodeInto(e,c);_+=l.written,o=n(o,r,_,1)>>>0}return b=_,o}function g(e){let t=u(e);return Ie(e),t}function Re(e,t){return ft+=t,ft>=Me&&(rt=new TextDecoder("utf-8",{ignoreBOM:!0,fatal:!0}),rt.decode(),ft=t),rt.decode(O().subarray(e,e+t))}function Ee(e,t,n){i.__wasm_bindgen_func_elem_944(e,t,f(n))}function Te(e,t,n,r){i.__wasm_bindgen_func_elem_37348(e,t,f(n),f(r))}function Oe(e){let t=i.get_font_info(f(e));return g(t)}async function Pe(e,t){if(typeof Response=="function"&&e instanceof Response){if(typeof WebAssembly.instantiateStreaming=="function")try{return await WebAssembly.instantiateStreaming(e,t)}catch(r){if(e.ok&&Ce.has(e.type)&&e.headers.get("Content-Type")!=="application/wasm")console.warn("`WebAssembly.instantiateStreaming` failed because your server does not serve Wasm with `application/wasm` MIME type. Falling back to `WebAssembly.instantiate` which is slower. Original error:\\n",r);else throw r}let n=await e.arrayBuffer();return await WebAssembly.instantiate(n,t)}else{let n=await WebAssembly.instantiate(e,t);return n instanceof WebAssembly.Instance?{instance:n,module:e}:n}}function Wt(){let e={};return e.wbg={},e.wbg.__wbg_Error_52673b7de5a0ca89=function(t,n){let r=Error(I(t,n));return f(r)},e.wbg.__wbg_Number_2d1dcfcf4ec51736=function(t){return Number(u(t))},e.wbg.__wbg___wbindgen_bigint_get_as_i64_6e32f5e6aff02e1d=function(t,n){let r=u(n),o=typeof r=="bigint"?r:void 0;a().setBigInt64(t+8,v(o)?BigInt(0):o,!0),a().setInt32(t+0,!v(o),!0)},e.wbg.__wbg___wbindgen_boolean_get_dea25b33882b895b=function(t){let n=u(t),r=typeof n=="boolean"?n:void 0;return v(r)?16777215:r?1:0},e.wbg.__wbg___wbindgen_debug_string_adfb662ae34724b6=function(t,n){let r=lt(u(n)),o=h(r,i.__wbindgen_export,i.__wbindgen_export2),s=b;a().setInt32(t+4,s,!0),a().setInt32(t+0,o,!0)},e.wbg.__wbg___wbindgen_in_0d3e1e8f0c669317=function(t,n){return u(t)in u(n)},e.wbg.__wbg___wbindgen_is_bigint_0e1a2e3f55cfae27=function(t){return typeof u(t)=="bigint"},e.wbg.__wbg___wbindgen_is_function_8d400b8b1af978cd=function(t){return typeof u(t)=="function"},e.wbg.__wbg___wbindgen_is_object_ce774f3490692386=function(t){let n=u(t);return typeof n=="object"&&n!==null},e.wbg.__wbg___wbindgen_is_string_704ef9c8fc131030=function(t){return typeof u(t)=="string"},e.wbg.__wbg___wbindgen_is_undefined_f6b95eab589e0269=function(t){return u(t)===void 0},e.wbg.__wbg___wbindgen_jsval_eq_b6101cc9cef1fe36=function(t,n){return u(t)===u(n)},e.wbg.__wbg___wbindgen_jsval_loose_eq_766057600fdd1b0d=function(t,n){return u(t)==u(n)},e.wbg.__wbg___wbindgen_number_get_9619185a74197f95=function(t,n){let r=u(n),o=typeof r=="number"?r:void 0;a().setFloat64(t+8,v(o)?0:o,!0),a().setInt32(t+0,!v(o),!0)},e.wbg.__wbg___wbindgen_string_get_a2a31e16edf96e42=function(t,n){let r=u(n),o=typeof r=="string"?r:void 0;var s=v(o)?0:h(o,i.__wbindgen_export,i.__wbindgen_export2),_=b;a().setInt32(t+4,_,!0),a().setInt32(t+0,s,!0)},e.wbg.__wbg___wbindgen_throw_dd24417ed36fc46e=function(t,n){throw new Error(I(t,n))},e.wbg.__wbg__wbg_cb_unref_87dfb5aaa0cbcea7=function(t){u(t)._wbg_cb_unref()},e.wbg.__wbg_call_3020136f7a2d6e44=function(){return T(function(t,n,r){let o=u(t).call(u(n),u(r));return f(o)},arguments)},e.wbg.__wbg_call_78f94eb02ec7f9b2=function(){return T(function(t,n,r,o,s){let _=u(t).call(u(n),u(r),u(o),u(s));return f(_)},arguments)},e.wbg.__wbg_call_abb4ff46ce38be40=function(){return T(function(t,n){let r=u(t).call(u(n));return f(r)},arguments)},e.wbg.__wbg_done_62ea16af4ce34b24=function(t){return u(t).done},e.wbg.__wbg_entries_83c79938054e065f=function(t){let n=Object.entries(u(t));return f(n)},e.wbg.__wbg_error_7534b8e9a36f1ab4=function(t,n){let r,o;try{r=t,o=n,console.error(I(t,n))}finally{i.__wbindgen_export4(r,o,1)}},e.wbg.__wbg_error_85faeb8919b11cc6=function(t,n,r){console.error(u(t),u(n),u(r))},e.wbg.__wbg_getTimezoneOffset_45389e26d6f46823=function(t){return u(t).getTimezoneOffset()},e.wbg.__wbg_get_6b7bd52aca3f9671=function(t,n){let r=u(t)[n>>>0];return f(r)},e.wbg.__wbg_get_af9dab7e9603ea93=function(){return T(function(t,n){let r=Reflect.get(u(t),u(n));return f(r)},arguments)},e.wbg.__wbg_get_with_ref_key_1dc361bd10053bfe=function(t,n){let r=u(t)[u(n)];return f(r)},e.wbg.__wbg_info_ce6bcc489c22f6f0=function(t){console.info(u(t))},e.wbg.__wbg_instanceof_ArrayBuffer_f3320d2419cd0355=function(t){let n;try{n=u(t)instanceof ArrayBuffer}catch{n=!1}return n},e.wbg.__wbg_instanceof_Map_084be8da74364158=function(t){let n;try{n=u(t)instanceof Map}catch{n=!1}return n},e.wbg.__wbg_instanceof_Uint8Array_da54ccc9d3e09434=function(t){let n;try{n=u(t)instanceof Uint8Array}catch{n=!1}return n},e.wbg.__wbg_isArray_51fd9e6422c0a395=function(t){return Array.isArray(u(t))},e.wbg.__wbg_isSafeInteger_ae7d3f054d55fa16=function(t){return Number.isSafeInteger(u(t))},e.wbg.__wbg_iterator_27b7c8b35ab3e86b=function(){return f(Symbol.iterator)},e.wbg.__wbg_length_22ac23eaec9d8053=function(t){return u(t).length},e.wbg.__wbg_length_d45040a40c570362=function(t){return u(t).length},e.wbg.__wbg_new_1ba21ce319a06297=function(){let t=new Object;return f(t)},e.wbg.__wbg_new_25f239778d6112b9=function(){let t=new Array;return f(t)},e.wbg.__wbg_new_6421f6084cc5bc5a=function(t){let n=new Uint8Array(u(t));return f(n)},e.wbg.__wbg_new_8a6f238a6ece86ea=function(){let t=new Error;return f(t)},e.wbg.__wbg_new_b2db8aa2650f793a=function(t){let n=new Date(u(t));return f(n)},e.wbg.__wbg_new_df1173567d5ff028=function(t,n){let r=new Error(I(t,n));return f(r)},e.wbg.__wbg_new_ff12d2b041fb48f1=function(t,n){try{var r={a:t,b:n},o=(_,c)=>{let l=r.a;r.a=0;try{return Te(l,r.b,_,c)}finally{r.a=l}};let s=new Promise(o);return f(s)}finally{r.a=r.b=0}},e.wbg.__wbg_new_from_slice_db0691b69e9d3891=function(t,n){let r=new Uint32Array(Se(t,n));return f(r)},e.wbg.__wbg_new_from_slice_f9c22b9153b26992=function(t,n){let r=new Uint8Array(wt(t,n));return f(r)},e.wbg.__wbg_new_no_args_cb138f77cf6151ee=function(t,n){let r=new Function(I(t,n));return f(r)},e.wbg.__wbg_new_with_args_df9e7125ffe55248=function(t,n,r,o){let s=new Function(I(t,n),I(r,o));return f(s)},e.wbg.__wbg_next_138a17bbf04e926c=function(t){let n=u(t).next;return f(n)},e.wbg.__wbg_next_3cfe5c0fe2a4cc53=function(){return T(function(t){let n=u(t).next();return f(n)},arguments)},e.wbg.__wbg_now_69d776cd24f5215b=function(){return Date.now()},e.wbg.__wbg_prototypesetcall_dfe9b766cdc1f1fd=function(t,n,r){Uint8Array.prototype.set.call(wt(t,n),u(r))},e.wbg.__wbg_proxycontext_new=function(t){let n=C.__wrap(t);return f(n)},e.wbg.__wbg_push_7d9be8f38fc13975=function(t,n){return u(t).push(u(n))},e.wbg.__wbg_queueMicrotask_9b549dfce8865860=function(t){let n=u(t).queueMicrotask;return f(n)},e.wbg.__wbg_queueMicrotask_fca69f5bfad613a5=function(t){queueMicrotask(u(t))},e.wbg.__wbg_resolve_fd5bfbaa4ce36e1e=function(t){let n=Promise.resolve(u(t));return f(n)},e.wbg.__wbg_set_3f1d0b984ed272ed=function(t,n,r){u(t)[g(n)]=g(r)},e.wbg.__wbg_set_781438a03c0c3c81=function(){return T(function(t,n,r){return Reflect.set(u(t),u(n),u(r))},arguments)},e.wbg.__wbg_set_7df433eea03a5c14=function(t,n,r){u(t)[n>>>0]=g(r)},e.wbg.__wbg_stack_0ed75d68575b0f3c=function(t,n){let r=u(n).stack,o=h(r,i.__wbindgen_export,i.__wbindgen_export2),s=b;a().setInt32(t+4,s,!0),a().setInt32(t+0,o,!0)},e.wbg.__wbg_static_accessor_GLOBAL_769e6b65d6557335=function(){let t=typeof global>"u"?null:global;return v(t)?0:f(t)},e.wbg.__wbg_static_accessor_GLOBAL_THIS_60cf02db4de8e1c1=function(){let t=typeof globalThis>"u"?null:globalThis;return v(t)?0:f(t)},e.wbg.__wbg_static_accessor_SELF_08f5a74c69739274=function(){let t=typeof self>"u"?null:self;return v(t)?0:f(t)},e.wbg.__wbg_static_accessor_WINDOW_a8924b26aa92d024=function(){let t=typeof window>"u"?null:window;return v(t)?0:f(t)},e.wbg.__wbg_then_4f95312d68691235=function(t,n){let r=u(t).then(u(n));return f(r)},e.wbg.__wbg_typstcompiler_new=function(t){let n=j.__wrap(t);return f(n)},e.wbg.__wbg_typstfontresolver_new=function(t){let n=R.__wrap(t);return f(n)},e.wbg.__wbg_value_57b7b035e117f7ee=function(t){let n=u(t).value;return f(n)},e.wbg.__wbindgen_cast_2241b6af4c4b2941=function(t,n){let r=I(t,n);return f(r)},e.wbg.__wbindgen_cast_3334ea73b4b28ba3=function(t,n){let r=Ae(t,n,i.__wasm_bindgen_func_elem_957,Ee);return f(r)},e.wbg.__wbindgen_cast_4625c577ab2ec9ee=function(t){let n=BigInt.asUintN(64,t);return f(n)},e.wbg.__wbindgen_cast_9ae0607507abb057=function(t){return f(t)},e.wbg.__wbindgen_cast_d6cd19b81560fd6e=function(t){return f(t)},e.wbg.__wbindgen_object_clone_ref=function(t){let n=u(t);return f(n)},e.wbg.__wbindgen_object_drop_ref=function(t){g(t)},e}function Nt(e,t){return i=e.exports,qt.__wbindgen_wasm_module=t,M=null,U=null,W=null,i}function je(e){if(i!==void 0)return i;typeof e<"u"&&(Object.getPrototypeOf(e)===Object.prototype?{module:e}=e:console.warn("using deprecated parameters for `initSync()`; pass a single object instead"));let t=Wt();e instanceof WebAssembly.Module||(e=new WebAssembly.Module(e));let n=new WebAssembly.Instance(e,t);return Nt(n,e)}async function qt(e){if(i!==void 0)return i;typeof e<"u"&&(Object.getPrototypeOf(e)===Object.prototype?{module_or_path:e}=e:console.warn("using deprecated parameters for the initialization function; pass a single object instead")),typeof e>"u"&&(e=$t("typst_ts_web_compiler_bg.wasm",Be.url));let t=Wt();(typeof e=="string"||typeof Request=="function"&&e instanceof Request||typeof URL=="function"&&e instanceof URL)&&(e=fetch(e));let{instance:n,module:r}=await Pe(await e,t);return Nt(n,r)}function pt(e){$t=e}var Be,i,Ct,M,U,W,S,N,rt,Me,ft,q,b,Pt,dt,jt,Bt,Lt,zt,Dt,F,C,P,j,V,R,$,Ce,Vt,$t,ot=vt(()=>{Be={};Ct=typeof FinalizationRegistry>"u"?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry(e=>e.dtor(e.a,e.b));M=null;U=null;W=null;S=new Array(128).fill(void 0);S.push(void 0,null,!0,!1);N=S.length;rt=new TextDecoder("utf-8",{ignoreBOM:!0,fatal:!0});rt.decode();Me=2146435072,ft=0;q=new TextEncoder;"encodeInto"in q||(q.encodeInto=function(e,t){let n=q.encode(e);return t.set(n),{read:e.length,written:n.length}});b=0;Pt=typeof FinalizationRegistry>"u"?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry(e=>i.__wbg_incrserver_free(e>>>0,1)),dt=typeof FinalizationRegistry>"u"?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry(e=>i.__wbg_proxycontext_free(e>>>0,1)),jt=typeof FinalizationRegistry>"u"?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry(e=>i.__wbg_typstcompileworld_free(e>>>0,1)),Bt=typeof FinalizationRegistry>"u"?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry(e=>i.__wbg_typstcompiler_free(e>>>0,1)),Lt=typeof FinalizationRegistry>"u"?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry(e=>i.__wbg_typstcompilerbuilder_free(e>>>0,1)),zt=typeof FinalizationRegistry>"u"?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry(e=>i.__wbg_typstfontresolver_free(e>>>0,1)),Dt=typeof FinalizationRegistry>"u"?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry(e=>i.__wbg_typstfontresolverbuilder_free(e>>>0,1)),F=class e{static __wrap(t){t=t>>>0;let n=Object.create(e.prototype);return n.__wbg_ptr=t,Pt.register(n,n.__wbg_ptr,n),n}__destroy_into_raw(){let t=this.__wbg_ptr;return this.__wbg_ptr=0,Pt.unregister(this),t}free(){let t=this.__destroy_into_raw();i.__wbg_incrserver_free(t,0)}set_attach_debug_info(t){i.incrserver_set_attach_debug_info(this.__wbg_ptr,t)}current(){try{let r=i.__wbindgen_add_to_stack_pointer(-16);i.incrserver_current(r,this.__wbg_ptr);var t=a().getInt32(r+0,!0),n=a().getInt32(r+4,!0);let o;return t!==0&&(o=wt(t,n).slice(),i.__wbindgen_export4(t,n*1,1)),o}finally{i.__wbindgen_add_to_stack_pointer(16)}}reset(){i.incrserver_reset(this.__wbg_ptr)}};Symbol.dispose&&(F.prototype[Symbol.dispose]=F.prototype.free);C=class e{static __wrap(t){t=t>>>0;let n=Object.create(e.prototype);return n.__wbg_ptr=t,dt.register(n,n.__wbg_ptr,n),n}__destroy_into_raw(){let t=this.__wbg_ptr;return this.__wbg_ptr=0,dt.unregister(this),t}free(){let t=this.__destroy_into_raw();i.__wbg_proxycontext_free(t,0)}constructor(t){let n=i.proxycontext_new(f(t));return this.__wbg_ptr=n>>>0,dt.register(this,this.__wbg_ptr,this),this}get context(){let t=i.proxycontext_context(this.__wbg_ptr);return g(t)}untar(t,n){try{let s=i.__wbindgen_add_to_stack_pointer(-16),_=Ut(t,i.__wbindgen_export),c=b;i.proxycontext_untar(s,this.__wbg_ptr,_,c,f(n));var r=a().getInt32(s+0,!0),o=a().getInt32(s+4,!0);if(o)throw g(r)}finally{i.__wbindgen_add_to_stack_pointer(16)}}};Symbol.dispose&&(C.prototype[Symbol.dispose]=C.prototype.free);P=class e{static __wrap(t){t=t>>>0;let n=Object.create(e.prototype);return n.__wbg_ptr=t,jt.register(n,n.__wbg_ptr,n),n}__destroy_into_raw(){let t=this.__wbg_ptr;return this.__wbg_ptr=0,jt.unregister(this),t}free(){let t=this.__destroy_into_raw();i.__wbg_typstcompileworld_free(t,0)}compile(t,n){try{let _=i.__wbindgen_add_to_stack_pointer(-16);i.typstcompileworld_compile(_,this.__wbg_ptr,t,n);var r=a().getInt32(_+0,!0),o=a().getInt32(_+4,!0),s=a().getInt32(_+8,!0);if(s)throw g(o);return g(r)}finally{i.__wbindgen_add_to_stack_pointer(16)}}title(t){try{let _=i.__wbindgen_add_to_stack_pointer(-16);i.typstcompileworld_title(_,this.__wbg_ptr,t);var n=a().getInt32(_+0,!0),r=a().getInt32(_+4,!0),o=a().getInt32(_+8,!0),s=a().getInt32(_+12,!0);if(s)throw g(o);let c;return n!==0&&(c=I(n,r).slice(),i.__wbindgen_export4(n,r*1,1)),c}finally{i.__wbindgen_add_to_stack_pointer(16)}}get_artifact(t,n){try{let _=i.__wbindgen_add_to_stack_pointer(-16);i.typstcompileworld_get_artifact(_,this.__wbg_ptr,t,n);var r=a().getInt32(_+0,!0),o=a().getInt32(_+4,!0),s=a().getInt32(_+8,!0);if(s)throw g(o);return g(r)}finally{i.__wbindgen_add_to_stack_pointer(16)}}query(t,n,r){let o,s;try{let k=i.__wbindgen_add_to_stack_pointer(-16),L=h(n,i.__wbindgen_export,i.__wbindgen_export2),z=b;var _=v(r)?0:h(r,i.__wbindgen_export,i.__wbindgen_export2),c=b;i.typstcompileworld_query(k,this.__wbg_ptr,t,L,z,_,c);var l=a().getInt32(k+0,!0),d=a().getInt32(k+4,!0),w=a().getInt32(k+8,!0),y=a().getInt32(k+12,!0),p=l,m=d;if(y)throw p=0,m=0,g(w);return o=p,s=m,I(p,m)}finally{i.__wbindgen_add_to_stack_pointer(16),i.__wbindgen_export4(o,s,1)}}incr_compile(t,n){try{let _=i.__wbindgen_add_to_stack_pointer(-16);gt(t,F),i.typstcompileworld_incr_compile(_,this.__wbg_ptr,t.__wbg_ptr,n);var r=a().getInt32(_+0,!0),o=a().getInt32(_+4,!0),s=a().getInt32(_+8,!0);if(s)throw g(o);return g(r)}finally{i.__wbindgen_add_to_stack_pointer(16)}}};Symbol.dispose&&(P.prototype[Symbol.dispose]=P.prototype.free);j=class e{static __wrap(t){t=t>>>0;let n=Object.create(e.prototype);return n.__wbg_ptr=t,Bt.register(n,n.__wbg_ptr,n),n}__destroy_into_raw(){let t=this.__wbg_ptr;return this.__wbg_ptr=0,Bt.unregister(this),t}free(){let t=this.__destroy_into_raw();i.__wbg_typstcompiler_free(t,0)}reset(){try{let r=i.__wbindgen_add_to_stack_pointer(-16);i.typstcompiler_reset(r,this.__wbg_ptr);var t=a().getInt32(r+0,!0),n=a().getInt32(r+4,!0);if(n)throw g(t)}finally{i.__wbindgen_add_to_stack_pointer(16)}}set_fonts(t){try{let o=i.__wbindgen_add_to_stack_pointer(-16);gt(t,R),i.typstcompiler_set_fonts(o,this.__wbg_ptr,t.__wbg_ptr);var n=a().getInt32(o+0,!0),r=a().getInt32(o+4,!0);if(r)throw g(n)}finally{i.__wbindgen_add_to_stack_pointer(16)}}set_inputs(t){try{let o=i.__wbindgen_add_to_stack_pointer(-16);i.typstcompiler_set_inputs(o,this.__wbg_ptr,f(t));var n=a().getInt32(o+0,!0),r=a().getInt32(o+4,!0);if(r)throw g(n)}finally{i.__wbindgen_add_to_stack_pointer(16)}}add_source(t,n){let r=h(t,i.__wbindgen_export,i.__wbindgen_export2),o=b,s=h(n,i.__wbindgen_export,i.__wbindgen_export2),_=b;return i.typstcompiler_add_source(this.__wbg_ptr,r,o,s,_)!==0}map_shadow(t,n){let r=h(t,i.__wbindgen_export,i.__wbindgen_export2),o=b,s=Ut(n,i.__wbindgen_export),_=b;return i.typstcompiler_map_shadow(this.__wbg_ptr,r,o,s,_)!==0}unmap_shadow(t){let n=h(t,i.__wbindgen_export,i.__wbindgen_export2),r=b;return i.typstcompiler_unmap_shadow(this.__wbg_ptr,n,r)!==0}reset_shadow(){i.typstcompiler_reset_shadow(this.__wbg_ptr)}get_loaded_fonts(){try{let o=i.__wbindgen_add_to_stack_pointer(-16);i.typstcompiler_get_loaded_fonts(o,this.__wbg_ptr);var t=a().getInt32(o+0,!0),n=a().getInt32(o+4,!0),r=ke(t,n).slice();return i.__wbindgen_export4(t,n*4,4),r}finally{i.__wbindgen_add_to_stack_pointer(16)}}get_ast(t){let n,r;try{let w=i.__wbindgen_add_to_stack_pointer(-16),y=h(t,i.__wbindgen_export,i.__wbindgen_export2),p=b;i.typstcompiler_get_ast(w,this.__wbg_ptr,y,p);var o=a().getInt32(w+0,!0),s=a().getInt32(w+4,!0),_=a().getInt32(w+8,!0),c=a().getInt32(w+12,!0),l=o,d=s;if(c)throw l=0,d=0,g(_);return n=l,r=d,I(l,d)}finally{i.__wbindgen_add_to_stack_pointer(16),i.__wbindgen_export4(n,r,1)}}get_semantic_token_legend(){try{let o=i.__wbindgen_add_to_stack_pointer(-16);i.typstcompiler_get_semantic_token_legend(o,this.__wbg_ptr);var t=a().getInt32(o+0,!0),n=a().getInt32(o+4,!0),r=a().getInt32(o+8,!0);if(r)throw g(n);return g(t)}finally{i.__wbindgen_add_to_stack_pointer(16)}}get_semantic_tokens(t,n,r){try{let y=i.__wbindgen_add_to_stack_pointer(-16),p=h(t,i.__wbindgen_export,i.__wbindgen_export2),m=b;var o=v(n)?0:h(n,i.__wbindgen_export,i.__wbindgen_export2),s=b,_=v(r)?0:h(r,i.__wbindgen_export,i.__wbindgen_export2),c=b;i.typstcompiler_get_semantic_tokens(y,this.__wbg_ptr,p,m,o,s,_,c);var l=a().getInt32(y+0,!0),d=a().getInt32(y+4,!0),w=a().getInt32(y+8,!0);if(w)throw g(d);return g(l)}finally{i.__wbindgen_add_to_stack_pointer(16)}}snapshot(t,n,r){try{let m=i.__wbindgen_add_to_stack_pointer(-16);var o=v(t)?0:h(t,i.__wbindgen_export,i.__wbindgen_export2),s=b,_=v(n)?0:h(n,i.__wbindgen_export,i.__wbindgen_export2),c=b,l=v(r)?0:nt(r,i.__wbindgen_export),d=b;i.typstcompiler_snapshot(m,this.__wbg_ptr,o,s,_,c,l,d);var w=a().getInt32(m+0,!0),y=a().getInt32(m+4,!0),p=a().getInt32(m+8,!0);if(p)throw g(y);return P.__wrap(w)}finally{i.__wbindgen_add_to_stack_pointer(16)}}get_artifact(t,n){try{let _=i.__wbindgen_add_to_stack_pointer(-16),c=h(t,i.__wbindgen_export,i.__wbindgen_export2),l=b;i.typstcompiler_get_artifact(_,this.__wbg_ptr,c,l,n);var r=a().getInt32(_+0,!0),o=a().getInt32(_+4,!0),s=a().getInt32(_+8,!0);if(s)throw g(o);return g(r)}finally{i.__wbindgen_add_to_stack_pointer(16)}}compile(t,n,r,o){try{let p=i.__wbindgen_add_to_stack_pointer(-16);var s=v(t)?0:h(t,i.__wbindgen_export,i.__wbindgen_export2),_=b,c=v(n)?0:nt(n,i.__wbindgen_export),l=b;let m=h(r,i.__wbindgen_export,i.__wbindgen_export2),k=b;i.typstcompiler_compile(p,this.__wbg_ptr,s,_,c,l,m,k,o);var d=a().getInt32(p+0,!0),w=a().getInt32(p+4,!0),y=a().getInt32(p+8,!0);if(y)throw g(w);return g(d)}finally{i.__wbindgen_add_to_stack_pointer(16)}}query(t,n,r,o){let s,_;try{let D=i.__wbindgen_add_to_stack_pointer(-16),Qt=h(t,i.__wbindgen_export,i.__wbindgen_export2),Zt=b;var c=v(n)?0:nt(n,i.__wbindgen_export),l=b;let te=h(r,i.__wbindgen_export,i.__wbindgen_export2),ee=b;var d=v(o)?0:h(o,i.__wbindgen_export,i.__wbindgen_export2),w=b;i.typstcompiler_query(D,this.__wbg_ptr,Qt,Zt,c,l,te,ee,d,w);var y=a().getInt32(D+0,!0),p=a().getInt32(D+4,!0),m=a().getInt32(D+8,!0),k=a().getInt32(D+12,!0),L=y,z=p;if(k)throw L=0,z=0,g(m);return s=L,_=z,I(L,z)}finally{i.__wbindgen_add_to_stack_pointer(16),i.__wbindgen_export4(s,_,1)}}create_incr_server(){try{let o=i.__wbindgen_add_to_stack_pointer(-16);i.typstcompiler_create_incr_server(o,this.__wbg_ptr);var t=a().getInt32(o+0,!0),n=a().getInt32(o+4,!0),r=a().getInt32(o+8,!0);if(r)throw g(n);return F.__wrap(t)}finally{i.__wbindgen_add_to_stack_pointer(16)}}incr_compile(t,n,r,o){try{let w=i.__wbindgen_add_to_stack_pointer(-16),y=h(t,i.__wbindgen_export,i.__wbindgen_export2),p=b;var s=v(n)?0:nt(n,i.__wbindgen_export),_=b;gt(r,F),i.typstcompiler_incr_compile(w,this.__wbg_ptr,y,p,s,_,r.__wbg_ptr,o);var c=a().getInt32(w+0,!0),l=a().getInt32(w+4,!0),d=a().getInt32(w+8,!0);if(d)throw g(l);return g(c)}finally{i.__wbindgen_add_to_stack_pointer(16)}}};Symbol.dispose&&(j.prototype[Symbol.dispose]=j.prototype.free);V=class{__destroy_into_raw(){let t=this.__wbg_ptr;return this.__wbg_ptr=0,Lt.unregister(this),t}free(){let t=this.__destroy_into_raw();i.__wbg_typstcompilerbuilder_free(t,0)}constructor(){try{let o=i.__wbindgen_add_to_stack_pointer(-16);i.typstcompilerbuilder_new(o);var t=a().getInt32(o+0,!0),n=a().getInt32(o+4,!0),r=a().getInt32(o+8,!0);if(r)throw g(n);return this.__wbg_ptr=t>>>0,Lt.register(this,this.__wbg_ptr,this),this}finally{i.__wbindgen_add_to_stack_pointer(16)}}set_dummy_access_model(){try{let r=i.__wbindgen_add_to_stack_pointer(-16);i.typstcompilerbuilder_set_dummy_access_model(r,this.__wbg_ptr);var t=a().getInt32(r+0,!0),n=a().getInt32(r+4,!0);if(n)throw g(t)}finally{i.__wbindgen_add_to_stack_pointer(16)}}set_access_model(t,n,r,o,s){let _=i.typstcompilerbuilder_set_access_model(this.__wbg_ptr,f(t),f(n),f(r),f(o),f(s));return g(_)}set_package_registry(t,n){let r=i.typstcompilerbuilder_set_package_registry(this.__wbg_ptr,f(t),f(n));return g(r)}add_raw_font(t){let n=i.typstcompilerbuilder_add_raw_font(this.__wbg_ptr,f(t));return g(n)}add_lazy_font(t,n){let r=i.typstcompilerbuilder_add_lazy_font(this.__wbg_ptr,f(t),f(n));return g(r)}build(){let t=this.__destroy_into_raw(),n=i.typstcompilerbuilder_build(t);return g(n)}};Symbol.dispose&&(V.prototype[Symbol.dispose]=V.prototype.free);R=class e{static __wrap(t){t=t>>>0;let n=Object.create(e.prototype);return n.__wbg_ptr=t,zt.register(n,n.__wbg_ptr,n),n}__destroy_into_raw(){let t=this.__wbg_ptr;return this.__wbg_ptr=0,zt.unregister(this),t}free(){let t=this.__destroy_into_raw();i.__wbg_typstfontresolver_free(t,0)}};Symbol.dispose&&(R.prototype[Symbol.dispose]=R.prototype.free);$=class{__destroy_into_raw(){let t=this.__wbg_ptr;return this.__wbg_ptr=0,Dt.unregister(this),t}free(){let t=this.__destroy_into_raw();i.__wbg_typstfontresolverbuilder_free(t,0)}constructor(){try{let o=i.__wbindgen_add_to_stack_pointer(-16);i.typstfontresolverbuilder_new(o);var t=a().getInt32(o+0,!0),n=a().getInt32(o+4,!0),r=a().getInt32(o+8,!0);if(r)throw g(n);return this.__wbg_ptr=t>>>0,Dt.register(this,this.__wbg_ptr,this),this}finally{i.__wbindgen_add_to_stack_pointer(16)}}get_font_info(t){try{let s=i.__wbindgen_add_to_stack_pointer(-16);i.typstfontresolverbuilder_get_font_info(s,this.__wbg_ptr,f(t));var n=a().getInt32(s+0,!0),r=a().getInt32(s+4,!0),o=a().getInt32(s+8,!0);if(o)throw g(r);return g(n)}finally{i.__wbindgen_add_to_stack_pointer(16)}}add_raw_font(t){try{let o=i.__wbindgen_add_to_stack_pointer(-16);i.typstfontresolverbuilder_add_raw_font(o,this.__wbg_ptr,f(t));var n=a().getInt32(o+0,!0),r=a().getInt32(o+4,!0);if(r)throw g(n)}finally{i.__wbindgen_add_to_stack_pointer(16)}}add_lazy_font(t,n){try{let s=i.__wbindgen_add_to_stack_pointer(-16);i.typstfontresolverbuilder_add_lazy_font(s,this.__wbg_ptr,f(t),f(n));var r=a().getInt32(s+0,!0),o=a().getInt32(s+4,!0);if(o)throw g(r)}finally{i.__wbindgen_add_to_stack_pointer(16)}}build(){let t=this.__destroy_into_raw(),n=i.typstfontresolverbuilder_build(t);return g(n)}};Symbol.dispose&&($.prototype[Symbol.dispose]=$.prototype.free);Ce=new Set(["basic","cors","default"]);Vt=qt,$t=async function(e,t){throw new Error("Cannot import wasm module without importer: "+e+" "+t)}});var Jt={};re(Jt,{IncrServer:()=>F,ProxyContext:()=>C,TypstCompileWorld:()=>P,TypstCompiler:()=>j,TypstCompilerBuilder:()=>V,TypstFontResolver:()=>R,TypstFontResolverBuilder:()=>$,default:()=>Le,get_font_info:()=>Oe,initSync:()=>je,setImportWasmModule:()=>pt});var Le,ze,De,Ht=vt(()=>{ot();ot();ot();Le=Vt,ze=async function(e,t){let n=new Function("m","return import(m)"),{readFileSync:r}=await n("fs"),o=new URL(e,t);return await r(o).buffer},De=typeof process<"u"&&process.versions!=null&&process.versions.node!=null;De&&pt(ze)});var It=Symbol("Comlink.proxy"),oe=Symbol("Comlink.endpoint"),ie=Symbol("Comlink.releaseProxy"),at=Symbol("Comlink.finalizer"),G=Symbol("Comlink.thrown"),kt=e=>typeof e=="object"&&e!==null||typeof e=="function",se={canHandle:e=>kt(e)&&e[It],serialize(e){let{port1:t,port2:n}=new MessageChannel;return Q(e,t),[n,[n]]},deserialize(e){return e.start(),ue(e)}},_e={canHandle:e=>kt(e)&&G in e,serialize({value:e}){let t;return e instanceof Error?t={isError:!0,value:{message:e.message,name:e.name,stack:e.stack}}:t={isError:!1,value:e},[t,[]]},deserialize(e){throw e.isError?Object.assign(new Error(e.value.message),e.value):e.value}},St=new Map([["proxy",se],["throw",_e]]);function ae(e,t){for(let n of e)if(t===n||n==="*"||n instanceof RegExp&&n.test(t))return!0;return!1}function Q(e,t=globalThis,n=["*"]){t.addEventListener("message",function r(o){if(!o||!o.data)return;if(!ae(n,o.origin)){console.warn(`Invalid origin \'${o.origin}\' for comlink proxy`);return}let{id:s,type:_,path:c}=Object.assign({path:[]},o.data),l=(o.data.argumentList||[]).map(A),d;try{let w=c.slice(0,-1).reduce((p,m)=>p[m],e),y=c.reduce((p,m)=>p[m],e);switch(_){case"GET":d=y;break;case"SET":w[c.slice(-1)[0]]=A(o.data.value),d=!0;break;case"APPLY":d=y.apply(w,l);break;case"CONSTRUCT":{let p=new y(...l);d=le(p)}break;case"ENDPOINT":{let{port1:p,port2:m}=new MessageChannel;Q(e,m),d=Z(p,[p])}break;case"RELEASE":d=void 0;break;default:return}}catch(w){d={value:w,[G]:0}}Promise.resolve(d).catch(w=>({value:w,[G]:0})).then(w=>{let[y,p]=K(w);t.postMessage(Object.assign(Object.assign({},y),{id:s}),p),_==="RELEASE"&&(t.removeEventListener("message",r),Ft(t),at in e&&typeof e[at]=="function"&&e[at]())}).catch(w=>{let[y,p]=K({value:new TypeError("Unserializable return value"),[G]:0});t.postMessage(Object.assign(Object.assign({},y),{id:s}),p)})}),t.start&&t.start()}function ce(e){return e.constructor.name==="MessagePort"}function Ft(e){ce(e)&&e.close()}function ue(e,t){let n=new Map;return e.addEventListener("message",function(o){let{data:s}=o;if(!s||!s.id)return;let _=n.get(s.id);if(_)try{_(s)}finally{n.delete(s.id)}}),ct(e,n,[],t)}function H(e){if(e)throw new Error("Proxy has been released and is not useable")}function At(e){return E(e,new Map,{type:"RELEASE"}).then(()=>{Ft(e)})}var X=new WeakMap,Y="FinalizationRegistry"in globalThis&&new FinalizationRegistry(e=>{let t=(X.get(e)||0)-1;X.set(e,t),t===0&&At(e)});function fe(e,t){let n=(X.get(t)||0)+1;X.set(t,n),Y&&Y.register(e,t,e)}function de(e){Y&&Y.unregister(e)}function ct(e,t,n=[],r=function(){}){let o=!1,s=new Proxy(r,{get(_,c){if(H(o),c===ie)return()=>{de(s),At(e),t.clear(),o=!0};if(c==="then"){if(n.length===0)return{then:()=>s};let l=E(e,t,{type:"GET",path:n.map(d=>d.toString())}).then(A);return l.then.bind(l)}return ct(e,t,[...n,c])},set(_,c,l){H(o);let[d,w]=K(l);return E(e,t,{type:"SET",path:[...n,c].map(y=>y.toString()),value:d},w).then(A)},apply(_,c,l){H(o);let d=n[n.length-1];if(d===oe)return E(e,t,{type:"ENDPOINT"}).then(A);if(d==="bind")return ct(e,t,n.slice(0,-1));let[w,y]=xt(l);return E(e,t,{type:"APPLY",path:n.map(p=>p.toString()),argumentList:w},y).then(A)},construct(_,c){H(o);let[l,d]=xt(c);return E(e,t,{type:"CONSTRUCT",path:n.map(w=>w.toString()),argumentList:l},d).then(A)}});return fe(s,e),s}function ge(e){return Array.prototype.concat.apply([],e)}function xt(e){let t=e.map(K);return[t.map(n=>n[0]),ge(t.map(n=>n[1]))]}var Mt=new WeakMap;function Z(e,t){return Mt.set(e,t),e}function le(e){return Object.assign(e,{[It]:!0})}function K(e){for(let[t,n]of St)if(n.canHandle(e)){let[r,o]=n.serialize(e);return[{type:"HANDLER",name:t,value:r},o]}return[{type:"RAW",value:e},Mt.get(e)||[]]}function A(e){switch(e.type){case"HANDLER":return St.get(e.name).deserialize(e.value);case"RAW":return e.value}}function E(e,t,n,r){return new Promise(o=>{let s=we();t.set(s,o),e.start&&e.start(),e.postMessage(Object.assign({id:s},n),r)})}function we(){return new Array(4).fill(0).map(()=>Math.floor(Math.random()*Number.MAX_SAFE_INTEGER).toString(16)).join("-")}var ut=class{loadedFonts=new Set;fetcher=fetch;setFetcher(t){this.fetcher=t}async loadFonts(t,n){let r=new Function("m","return import(m)"),o=this.fetcher||=await(async function(){let{fetchBuilder:c,FileSystemCache:l}=await r("node-fetch-cache"),d=new l({cacheDirectory:".cache/typst/fonts"}),w=c.withCache(d);return function(y,p){let m=setTimeout(()=>{console.warn("font fetching is stucking:",y)},15e3);return w(y,p).finally(()=>{clearTimeout(m)})}})(),s=n.filter(c=>c instanceof Uint8Array||typeof c=="object"&&"info"in c?!0:this.loadedFonts.has(c)?!1:(this.loadedFonts.add(c),!0)),_=await Promise.all(s.map(async c=>{if(c instanceof Uint8Array){await t.add_raw_font(c);return}if(typeof c=="object"&&"info"in c){await t.add_lazy_font(c,"blob"in c?c.blob:be(c));return}return new Uint8Array(await(await o(c)).arrayBuffer())}));for(let c of _)c&&await t.add_raw_font(c)}async build(t,n,r){let o={ref:this,builder:n,hooks:r};for(let s of t?.beforeBuild??[])await s(void 0,o);return r.latelyBuild&&r.latelyBuild(o),await n.build()}};async function Rt(e,t,n,r){return await t.init(e?.getModule?.()),await new ut().build(e,new n,r)}function be(e){return()=>{let t=new XMLHttpRequest;return t.overrideMimeType("text/plain; charset=x-user-defined"),t.open("GET",e.url,!1),t.send(null),t.status===200&&(t.response instanceof String||typeof t.response=="string")?Uint8Array.from(t.response,n=>n.charCodeAt(0)):new Uint8Array}}var x=Symbol.for("reflexo-obj");var Et;(function(e){e[e.PIXEL_PER_PT=3]="PIXEL_PER_PT"})(Et||(Et={}));var ye=["DejaVuSansMono-Bold.ttf","DejaVuSansMono-BoldOblique.ttf","DejaVuSansMono-Oblique.ttf","DejaVuSansMono.ttf","LibertinusSerif-Bold.otf","LibertinusSerif-BoldItalic.otf","LibertinusSerif-Italic.otf","LibertinusSerif-Regular.otf","LibertinusSerif-Semibold.otf","LibertinusSerif-SemiboldItalic.otf","NewCM10-Bold.otf","NewCM10-BoldItalic.otf","NewCM10-Italic.otf","NewCM10-Regular.otf","NewCMMath-Bold.otf","NewCMMath-Book.otf","NewCMMath-Regular.otf"],me=["InriaSerif-Bold.ttf","InriaSerif-BoldItalic.ttf","InriaSerif-Italic.ttf","InriaSerif-Regular.ttf","Roboto-Regular.ttf","NotoSerifCJKsc-Regular.otf"],he=["TwitterColorEmoji.ttf","NotoColorEmoji-Regular-COLR.subset.ttf"];function ve(e){let t=[];if(e&&e?.assets!==!1&&e?.assets?.length&&e?.assets?.length>0){let n={text:"https://cdn.jsdelivr.net/gh/typst/typst-assets@v0.13.1/files/fonts/",_:"https://cdn.jsdelivr.net/gh/typst/typst-dev-assets@v0.13.1/files/fonts/"},r=e.assetUrlPrefix??n;typeof r=="string"?r={_:r}:r={...n,...r};for(let s of Object.keys(r)){let _=r[s];_[_.length-1]!=="/"&&(r[s]=_+"/")}let o=(s,_)=>_.map(c=>(r[s]||r._)+c);for(let s of e.assets)switch(s){case"text":t.push(...o(s,ye));break;case"cjk":t.push(...o(s,me));break;case"emoji":t.push(...o(s,he));break}}return t}function tt(e,t){let n=ve(t),r=async(o,{ref:s,builder:_})=>{t?.fetcher&&s.setFetcher(t.fetcher),await s.loadFonts(_,[...e,...n])};return r._preloadRemoteFontOptions=t,r._kind="fontLoader",r}function Tt(e){return async(t,{builder:n})=>new Promise(r=>{n.set_package_registry(e,function(o){return e.resolve(o,this)}),r()})}function Ot(e){return async(t,n)=>{if(n.alreadySetAccessModel)throw new Error(`already set some assess model before: ${n.alreadySetAccessModel.constructor?.name}(${n.alreadySetAccessModel})`);return n.alreadySetAccessModel=e,new Promise(r=>{n.builder.set_access_model(e,o=>{let s=e.getMTime(o);return s?s.getTime():0},o=>e.isFile(o)||!1,o=>e.getRealPath(o)||o,o=>e.readAll(o)),r()})}}var xe=e=>{let t=!1,n;return()=>t?n:(t=!0,n=e())},et=class{wasmBin;initOnce;constructor(t){if(typeof t!="function")throw new Error("initFn is not a function");this.initOnce=xe(async()=>{await t(this.wasmBin)})}async init(t){this.wasmBin=t,await this.initOnce()}};var J;(function(e){e[e.vector=0]="vector",e[e.pdf=1]="pdf",e[e._dummy=2]="_dummy"})(J||(J={}));var bt=class{[x];constructor(t){this[x]=t}reset(){this[x].reset()}current(){return this[x].current()}setAttachDebugInfo(t){this[x].set_attach_debug_info(t)}},Gt;Gt||(Gt={});var yt=class{[x];constructor(t){this[x]=t}compile(t){return this[x].compile(0,B(t?.diagnostics))}compileHtml(t){return this[x].compile(1,B(t?.diagnostics))}async query(t){return JSON.parse(this[x].query(0,t.selector,t.field))}title(){return this[x].title(0)}vector(t){return this[x].get_artifact(0,B(t?.diagnostics))||{}}pdf(t){return this[x].get_artifact(1,B(t?.diagnostics))||{}}},Ue=e=>new et(async t=>await e.default(t));function mt(){return new it}var it=class e{compiler;compilerJs;static defaultAssets=["text"];constructor(){}async init(t){this.compilerJs=await(t?.getWrapper?.()||Promise.resolve().then(()=>(Ht(),Jt)));let n=this.compilerJs.TypstCompilerBuilder,r={...t||{}},o=r.beforeBuild??=[],s=o.some(d=>d._preloadRemoteFontOptions!==void 0),_=o.some(d=>d._preloadRemoteFontOptions?.assets!==void 0),c=o.some(d=>d._preloadRemoteFontOptions?.assets===!1);if((!s||!_&&!c)&&o.push(tt([],{assets:e.defaultAssets})),!o.some(d=>d._kind==="fontLoader"))throw new Error("TypstCompiler: no font loader found, please use font loaders, e.g. loadFonts or preloadSystemFonts");this.compiler=await Rt(t,Ue(this.compilerJs),n,{})}setFonts(t){this.compiler.set_fonts(t)}compile(t){return new Promise(n=>{let r=this.compiler.snapshot(t.root,t.mainFilePath,Xt(t.inputs));if("incrementalServer"in t){n(r.incr_compile(t.incrementalServer[x],B(t.diagnostics)));return}n(r.get_artifact(t.format||J.vector,B(t.diagnostics)))})}async runWithWorld(t,n){let r=this.compiler.snapshot(t.root,t.mainFilePath,Xt(t.inputs)),o=await n(new yt(r));return r.free(),o}query(t){return this.runWithWorld(t,async n=>JSON.parse(await n.query(t)))}getSemanticTokenLegend(){return new Promise(t=>{t(this.compiler.get_semantic_token_legend())})}getSemanticTokens(t){return new Promise(n=>{this.compiler.reset(),n(this.compiler.get_semantic_tokens(t.offsetEncoding||"utf-16",t.mainFilePath,t.resultId))})}async withIncrementalServer(t){let n=new bt(this.compiler.create_incr_server());try{return await t(n)}finally{n[x].free()}}async getAst(t){return this.compiler.get_ast(t)}async reset(){await new Promise(t=>{this.compiler.reset(),t(void 0)})}addSource(t,n){if(arguments.length>2)throw new Error("use of addSource(path, source, isMain) is deprecated, please use addSource(path, source) instead");this.compiler.add_source(t,n)}mapShadow(t,n){this.compiler.map_shadow(t,n)}unmapShadow(t){this.compiler.unmap_shadow(t)}resetShadow(){this.compiler.reset_shadow()}renderPageToCanvas(){throw new Error("Please use the api TypstRenderer.renderToCanvas in v0.4.0")}};mt._impl=it;function Xt(e){return e?Object.entries(e):void 0}function B(e){switch(e){case"none":return 1;case"unix":return 2;default:return 3}}var st=class{mTimes=new Map;mData=new Map;constructor(){}reset(){this.mTimes.clear(),this.mData.clear()}insertFile(t,n,r){this.mTimes.set(t,r),this.mData.set(t,n)}removeFile(t){this.mTimes.delete(t),this.mData.delete(t)}getMTime(t){if(t.startsWith("/@memory/")&&this.mTimes.has(t))return this.mTimes.get(t)}isFile(){return!0}getRealPath(t){return t}readAll(t){if(t.startsWith("/@memory/")&&this.mData.has(t))return this.mData.get(t)}};var _t=class{am;cache=new Map;constructor(t){this.am=t}resolvePath(t){return`https://packages.typst.org/preview/${t.name}-${t.version}.tar.gz`}pullPackageData(t){let n=new XMLHttpRequest;if(n.overrideMimeType("text/plain; charset=x-user-defined"),n.open("GET",this.resolvePath(t),!1),n.send(null),n.status===200&&(n.response instanceof String||typeof n.response=="string"))return Uint8Array.from(n.response,r=>r.charCodeAt(0))}resolve(t,n){if(t.namespace!=="preview")return;let r=this.resolvePath(t);if(this.cache.has(r))return this.cache.get(r)();let o=this.pullPackageData(t);if(!o)return;let s=`/@memory/fetch/packages/${t.namespace}/${t.name}/${t.version}`,_=[];n.untar(o,(l,d,w)=>{_.push([s+"/"+l,d,new Date(w)])});let c=()=>{for(let[l,d,w]of _)this.am.insertFile(l,d,w);return s};return this.cache.set(r,c),c()}};function Yt(e){return[...e].sort((t,n)=>t.path.localeCompare(n.path)||t.range.startLine-n.range.startLine||t.range.startCol-n.range.startCol||t.range.endLine-n.range.endLine||t.range.endCol-n.range.endCol||t.message.localeCompare(n.message))}var Kt="/main.typ",ht=class{#e=null;#n=new st;#r;constructor(){this.#r=new _t(this.#n)}#t(){if(!this.#e)throw new Error("Compiler not initialized");return this.#e}async init(t,n,r){this.#e=mt(),await this.#e.init({getModule:()=>t,beforeBuild:[tt(n),...r?[Ot(this.#n),Tt(this.#r)]:[]]})}async compile(t){let n=await this.#t().compile({mainFilePath:t??Kt,diagnostics:"full"}),r=Yt((n.diagnostics??[]).flatMap(s=>{let _=s.range.match(/(\\d+):(\\d+)-(\\d+):(\\d+)/);return _?[{...s,severity:s.severity,range:{startLine:+_[1],startCol:+_[2],endLine:+_[3],endCol:+_[4]}}]:(console.warn(`[typst-web-service] Skipping diagnostic with unrecognized range format: ${JSON.stringify(s.range)}`),[])})),o=n.result??void 0;return o?Z({diagnostics:r,vector:o},[o.buffer]):{diagnostics:r}}async compilePdf(t){let n=await this.#t().compile({mainFilePath:t??Kt,format:J.pdf,diagnostics:"none"});if(!n.result)throw new Error("Compilation produced no output");return Z(n.result,[n.result.buffer])}mapShadow(t,n){this.#t().mapShadow(t,n)}mapShadowMany(t){let n=this.#t();for(let[r,o]of Object.entries(t))n.mapShadow(r,o)}unmapShadow(t){this.#t().unmapShadow(t)}resetShadow(){this.#t().resetShadow()}destroy(){this.#e=null}};Q(new ht);})();\n/*! Bundled license information:\n\ncomlink/dist/esm/comlink.mjs:\n (**\n * @license\n * Copyright 2019 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n *)\n*/\n');
|
|
17
|
+
return createBlobWorker('"use strict";(()=>{var ne=Object.defineProperty;var vt=(e,t)=>()=>(e&&(t=e(e=0)),t);var re=(e,t)=>{for(var n in t)ne(e,n,{get:t[n],enumerable:!0})};function f(e){N===S.length&&S.push(S.length+1);let t=N;return N=S[t],S[t]=e,t}function gt(e,t){if(!(e instanceof t))throw new Error(`expected instance of ${t.name}`)}function lt(e){let t=typeof e;if(t=="number"||t=="boolean"||e==null)return`${e}`;if(t=="string")return`"${e}"`;if(t=="symbol"){let o=e.description;return o==null?"Symbol":`Symbol(${o})`}if(t=="function"){let o=e.name;return typeof o=="string"&&o.length>0?`Function(${o})`:"Function"}if(Array.isArray(e)){let o=e.length,s="[";o>0&&(s+=lt(e[0]));for(let _=1;_<o;_++)s+=", "+lt(e[_]);return s+="]",s}let n=/\\[object ([^\\]]+)\\]/.exec(toString.call(e)),r;if(n&&n.length>1)r=n[1];else return toString.call(e);if(r=="Object")try{return"Object("+JSON.stringify(e)+")"}catch{return"Object"}return e instanceof Error?`${e.name}: ${e.message}\n${e.stack}`:r}function Ie(e){e<132||(S[e]=N,N=e)}function ke(e,t){e=e>>>0;let n=a(),r=[];for(let o=e;o<e+4*t;o+=4)r.push(l(n.getUint32(o,!0)));return r}function Se(e,t){return e=e>>>0,Fe().subarray(e/4,e/4+t)}function wt(e,t){return e=e>>>0,C().subarray(e/1,e/1+t)}function a(){return(R===null||R.buffer.detached===!0||R.buffer.detached===void 0&&R.buffer!==i.memory.buffer)&&(R=new DataView(i.memory.buffer)),R}function I(e,t){return e=e>>>0,Me(e,t)}function Fe(){return(U===null||U.byteLength===0)&&(U=new Uint32Array(i.memory.buffer)),U}function C(){return(W===null||W.byteLength===0)&&(W=new Uint8Array(i.memory.buffer)),W}function u(e){return S[e]}function T(e,t){try{return e.apply(this,t)}catch(n){i.__wbindgen_export3(f(n))}}function v(e){return e==null}function Ae(e,t,n,r){let o={a:e,b:t,cnt:1,dtor:n},s=(..._)=>{o.cnt++;let c=o.a;o.a=0;try{return r(c,o.b,..._)}finally{o.a=c,s._wbg_cb_unref()}};return s._wbg_cb_unref=()=>{--o.cnt===0&&(o.dtor(o.a,o.b),o.a=0,Ot.unregister(o))},Ot.register(s,o,o),s}function Ut(e,t){let n=t(e.length*1,1)>>>0;return C().set(e,n/1),b=e.length,n}function nt(e,t){let n=t(e.length*4,4)>>>0,r=a();for(let o=0;o<e.length;o++)r.setUint32(n+4*o,f(e[o]),!0);return b=e.length,n}function h(e,t,n){if(n===void 0){let c=q.encode(e),d=t(c.length,1)>>>0;return C().subarray(d,d+c.length).set(c),b=c.length,d}let r=e.length,o=t(r,1)>>>0,s=C(),_=0;for(;_<r;_++){let c=e.charCodeAt(_);if(c>127)break;s[o+_]=c}if(_!==r){_!==0&&(e=e.slice(_)),o=n(o,r,r=_+e.length*3,1)>>>0;let c=C().subarray(o+_,o+r),d=q.encodeInto(e,c);_+=d.written,o=n(o,r,_,1)>>>0}return b=_,o}function l(e){let t=u(e);return Ie(e),t}function Me(e,t){return ft+=t,ft>=Re&&(rt=new TextDecoder("utf-8",{ignoreBOM:!0,fatal:!0}),rt.decode(),ft=t),rt.decode(C().subarray(e,e+t))}function Ee(e,t,n){i.__wasm_bindgen_func_elem_944(e,t,f(n))}function Te(e,t,n,r){i.__wasm_bindgen_func_elem_37348(e,t,f(n),f(r))}function Ce(e){let t=i.get_font_info(f(e));return l(t)}async function Pe(e,t){if(typeof Response=="function"&&e instanceof Response){if(typeof WebAssembly.instantiateStreaming=="function")try{return await WebAssembly.instantiateStreaming(e,t)}catch(r){if(e.ok&&Oe.has(e.type)&&e.headers.get("Content-Type")!=="application/wasm")console.warn("`WebAssembly.instantiateStreaming` failed because your server does not serve Wasm with `application/wasm` MIME type. Falling back to `WebAssembly.instantiate` which is slower. Original error:\\n",r);else throw r}let n=await e.arrayBuffer();return await WebAssembly.instantiate(n,t)}else{let n=await WebAssembly.instantiate(e,t);return n instanceof WebAssembly.Instance?{instance:n,module:e}:n}}function Wt(){let e={};return e.wbg={},e.wbg.__wbg_Error_52673b7de5a0ca89=function(t,n){let r=Error(I(t,n));return f(r)},e.wbg.__wbg_Number_2d1dcfcf4ec51736=function(t){return Number(u(t))},e.wbg.__wbg___wbindgen_bigint_get_as_i64_6e32f5e6aff02e1d=function(t,n){let r=u(n),o=typeof r=="bigint"?r:void 0;a().setBigInt64(t+8,v(o)?BigInt(0):o,!0),a().setInt32(t+0,!v(o),!0)},e.wbg.__wbg___wbindgen_boolean_get_dea25b33882b895b=function(t){let n=u(t),r=typeof n=="boolean"?n:void 0;return v(r)?16777215:r?1:0},e.wbg.__wbg___wbindgen_debug_string_adfb662ae34724b6=function(t,n){let r=lt(u(n)),o=h(r,i.__wbindgen_export,i.__wbindgen_export2),s=b;a().setInt32(t+4,s,!0),a().setInt32(t+0,o,!0)},e.wbg.__wbg___wbindgen_in_0d3e1e8f0c669317=function(t,n){return u(t)in u(n)},e.wbg.__wbg___wbindgen_is_bigint_0e1a2e3f55cfae27=function(t){return typeof u(t)=="bigint"},e.wbg.__wbg___wbindgen_is_function_8d400b8b1af978cd=function(t){return typeof u(t)=="function"},e.wbg.__wbg___wbindgen_is_object_ce774f3490692386=function(t){let n=u(t);return typeof n=="object"&&n!==null},e.wbg.__wbg___wbindgen_is_string_704ef9c8fc131030=function(t){return typeof u(t)=="string"},e.wbg.__wbg___wbindgen_is_undefined_f6b95eab589e0269=function(t){return u(t)===void 0},e.wbg.__wbg___wbindgen_jsval_eq_b6101cc9cef1fe36=function(t,n){return u(t)===u(n)},e.wbg.__wbg___wbindgen_jsval_loose_eq_766057600fdd1b0d=function(t,n){return u(t)==u(n)},e.wbg.__wbg___wbindgen_number_get_9619185a74197f95=function(t,n){let r=u(n),o=typeof r=="number"?r:void 0;a().setFloat64(t+8,v(o)?0:o,!0),a().setInt32(t+0,!v(o),!0)},e.wbg.__wbg___wbindgen_string_get_a2a31e16edf96e42=function(t,n){let r=u(n),o=typeof r=="string"?r:void 0;var s=v(o)?0:h(o,i.__wbindgen_export,i.__wbindgen_export2),_=b;a().setInt32(t+4,_,!0),a().setInt32(t+0,s,!0)},e.wbg.__wbg___wbindgen_throw_dd24417ed36fc46e=function(t,n){throw new Error(I(t,n))},e.wbg.__wbg__wbg_cb_unref_87dfb5aaa0cbcea7=function(t){u(t)._wbg_cb_unref()},e.wbg.__wbg_call_3020136f7a2d6e44=function(){return T(function(t,n,r){let o=u(t).call(u(n),u(r));return f(o)},arguments)},e.wbg.__wbg_call_78f94eb02ec7f9b2=function(){return T(function(t,n,r,o,s){let _=u(t).call(u(n),u(r),u(o),u(s));return f(_)},arguments)},e.wbg.__wbg_call_abb4ff46ce38be40=function(){return T(function(t,n){let r=u(t).call(u(n));return f(r)},arguments)},e.wbg.__wbg_done_62ea16af4ce34b24=function(t){return u(t).done},e.wbg.__wbg_entries_83c79938054e065f=function(t){let n=Object.entries(u(t));return f(n)},e.wbg.__wbg_error_7534b8e9a36f1ab4=function(t,n){let r,o;try{r=t,o=n,console.error(I(t,n))}finally{i.__wbindgen_export4(r,o,1)}},e.wbg.__wbg_error_85faeb8919b11cc6=function(t,n,r){console.error(u(t),u(n),u(r))},e.wbg.__wbg_getTimezoneOffset_45389e26d6f46823=function(t){return u(t).getTimezoneOffset()},e.wbg.__wbg_get_6b7bd52aca3f9671=function(t,n){let r=u(t)[n>>>0];return f(r)},e.wbg.__wbg_get_af9dab7e9603ea93=function(){return T(function(t,n){let r=Reflect.get(u(t),u(n));return f(r)},arguments)},e.wbg.__wbg_get_with_ref_key_1dc361bd10053bfe=function(t,n){let r=u(t)[u(n)];return f(r)},e.wbg.__wbg_info_ce6bcc489c22f6f0=function(t){console.info(u(t))},e.wbg.__wbg_instanceof_ArrayBuffer_f3320d2419cd0355=function(t){let n;try{n=u(t)instanceof ArrayBuffer}catch{n=!1}return n},e.wbg.__wbg_instanceof_Map_084be8da74364158=function(t){let n;try{n=u(t)instanceof Map}catch{n=!1}return n},e.wbg.__wbg_instanceof_Uint8Array_da54ccc9d3e09434=function(t){let n;try{n=u(t)instanceof Uint8Array}catch{n=!1}return n},e.wbg.__wbg_isArray_51fd9e6422c0a395=function(t){return Array.isArray(u(t))},e.wbg.__wbg_isSafeInteger_ae7d3f054d55fa16=function(t){return Number.isSafeInteger(u(t))},e.wbg.__wbg_iterator_27b7c8b35ab3e86b=function(){return f(Symbol.iterator)},e.wbg.__wbg_length_22ac23eaec9d8053=function(t){return u(t).length},e.wbg.__wbg_length_d45040a40c570362=function(t){return u(t).length},e.wbg.__wbg_new_1ba21ce319a06297=function(){let t=new Object;return f(t)},e.wbg.__wbg_new_25f239778d6112b9=function(){let t=new Array;return f(t)},e.wbg.__wbg_new_6421f6084cc5bc5a=function(t){let n=new Uint8Array(u(t));return f(n)},e.wbg.__wbg_new_8a6f238a6ece86ea=function(){let t=new Error;return f(t)},e.wbg.__wbg_new_b2db8aa2650f793a=function(t){let n=new Date(u(t));return f(n)},e.wbg.__wbg_new_df1173567d5ff028=function(t,n){let r=new Error(I(t,n));return f(r)},e.wbg.__wbg_new_ff12d2b041fb48f1=function(t,n){try{var r={a:t,b:n},o=(_,c)=>{let d=r.a;r.a=0;try{return Te(d,r.b,_,c)}finally{r.a=d}};let s=new Promise(o);return f(s)}finally{r.a=r.b=0}},e.wbg.__wbg_new_from_slice_db0691b69e9d3891=function(t,n){let r=new Uint32Array(Se(t,n));return f(r)},e.wbg.__wbg_new_from_slice_f9c22b9153b26992=function(t,n){let r=new Uint8Array(wt(t,n));return f(r)},e.wbg.__wbg_new_no_args_cb138f77cf6151ee=function(t,n){let r=new Function(I(t,n));return f(r)},e.wbg.__wbg_new_with_args_df9e7125ffe55248=function(t,n,r,o){let s=new Function(I(t,n),I(r,o));return f(s)},e.wbg.__wbg_next_138a17bbf04e926c=function(t){let n=u(t).next;return f(n)},e.wbg.__wbg_next_3cfe5c0fe2a4cc53=function(){return T(function(t){let n=u(t).next();return f(n)},arguments)},e.wbg.__wbg_now_69d776cd24f5215b=function(){return Date.now()},e.wbg.__wbg_prototypesetcall_dfe9b766cdc1f1fd=function(t,n,r){Uint8Array.prototype.set.call(wt(t,n),u(r))},e.wbg.__wbg_proxycontext_new=function(t){let n=O.__wrap(t);return f(n)},e.wbg.__wbg_push_7d9be8f38fc13975=function(t,n){return u(t).push(u(n))},e.wbg.__wbg_queueMicrotask_9b549dfce8865860=function(t){let n=u(t).queueMicrotask;return f(n)},e.wbg.__wbg_queueMicrotask_fca69f5bfad613a5=function(t){queueMicrotask(u(t))},e.wbg.__wbg_resolve_fd5bfbaa4ce36e1e=function(t){let n=Promise.resolve(u(t));return f(n)},e.wbg.__wbg_set_3f1d0b984ed272ed=function(t,n,r){u(t)[l(n)]=l(r)},e.wbg.__wbg_set_781438a03c0c3c81=function(){return T(function(t,n,r){return Reflect.set(u(t),u(n),u(r))},arguments)},e.wbg.__wbg_set_7df433eea03a5c14=function(t,n,r){u(t)[n>>>0]=l(r)},e.wbg.__wbg_stack_0ed75d68575b0f3c=function(t,n){let r=u(n).stack,o=h(r,i.__wbindgen_export,i.__wbindgen_export2),s=b;a().setInt32(t+4,s,!0),a().setInt32(t+0,o,!0)},e.wbg.__wbg_static_accessor_GLOBAL_769e6b65d6557335=function(){let t=typeof global>"u"?null:global;return v(t)?0:f(t)},e.wbg.__wbg_static_accessor_GLOBAL_THIS_60cf02db4de8e1c1=function(){let t=typeof globalThis>"u"?null:globalThis;return v(t)?0:f(t)},e.wbg.__wbg_static_accessor_SELF_08f5a74c69739274=function(){let t=typeof self>"u"?null:self;return v(t)?0:f(t)},e.wbg.__wbg_static_accessor_WINDOW_a8924b26aa92d024=function(){let t=typeof window>"u"?null:window;return v(t)?0:f(t)},e.wbg.__wbg_then_4f95312d68691235=function(t,n){let r=u(t).then(u(n));return f(r)},e.wbg.__wbg_typstcompiler_new=function(t){let n=j.__wrap(t);return f(n)},e.wbg.__wbg_typstfontresolver_new=function(t){let n=M.__wrap(t);return f(n)},e.wbg.__wbg_value_57b7b035e117f7ee=function(t){let n=u(t).value;return f(n)},e.wbg.__wbindgen_cast_2241b6af4c4b2941=function(t,n){let r=I(t,n);return f(r)},e.wbg.__wbindgen_cast_3334ea73b4b28ba3=function(t,n){let r=Ae(t,n,i.__wasm_bindgen_func_elem_957,Ee);return f(r)},e.wbg.__wbindgen_cast_4625c577ab2ec9ee=function(t){let n=BigInt.asUintN(64,t);return f(n)},e.wbg.__wbindgen_cast_9ae0607507abb057=function(t){return f(t)},e.wbg.__wbindgen_cast_d6cd19b81560fd6e=function(t){return f(t)},e.wbg.__wbindgen_object_clone_ref=function(t){let n=u(t);return f(n)},e.wbg.__wbindgen_object_drop_ref=function(t){l(t)},e}function Nt(e,t){return i=e.exports,qt.__wbindgen_wasm_module=t,R=null,U=null,W=null,i}function je(e){if(i!==void 0)return i;typeof e<"u"&&(Object.getPrototypeOf(e)===Object.prototype?{module:e}=e:console.warn("using deprecated parameters for `initSync()`; pass a single object instead"));let t=Wt();e instanceof WebAssembly.Module||(e=new WebAssembly.Module(e));let n=new WebAssembly.Instance(e,t);return Nt(n,e)}async function qt(e){if(i!==void 0)return i;typeof e<"u"&&(Object.getPrototypeOf(e)===Object.prototype?{module_or_path:e}=e:console.warn("using deprecated parameters for the initialization function; pass a single object instead")),typeof e>"u"&&(e=$t("typst_ts_web_compiler_bg.wasm",Le.url));let t=Wt();(typeof e=="string"||typeof Request=="function"&&e instanceof Request||typeof URL=="function"&&e instanceof URL)&&(e=fetch(e));let{instance:n,module:r}=await Pe(await e,t);return Nt(n,r)}function pt(e){$t=e}var Le,i,Ot,R,U,W,S,N,rt,Re,ft,q,b,Pt,dt,jt,Lt,Bt,Dt,zt,F,O,P,j,V,M,$,Oe,Vt,$t,ot=vt(()=>{Le={};Ot=typeof FinalizationRegistry>"u"?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry(e=>e.dtor(e.a,e.b));R=null;U=null;W=null;S=new Array(128).fill(void 0);S.push(void 0,null,!0,!1);N=S.length;rt=new TextDecoder("utf-8",{ignoreBOM:!0,fatal:!0});rt.decode();Re=2146435072,ft=0;q=new TextEncoder;"encodeInto"in q||(q.encodeInto=function(e,t){let n=q.encode(e);return t.set(n),{read:e.length,written:n.length}});b=0;Pt=typeof FinalizationRegistry>"u"?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry(e=>i.__wbg_incrserver_free(e>>>0,1)),dt=typeof FinalizationRegistry>"u"?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry(e=>i.__wbg_proxycontext_free(e>>>0,1)),jt=typeof FinalizationRegistry>"u"?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry(e=>i.__wbg_typstcompileworld_free(e>>>0,1)),Lt=typeof FinalizationRegistry>"u"?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry(e=>i.__wbg_typstcompiler_free(e>>>0,1)),Bt=typeof FinalizationRegistry>"u"?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry(e=>i.__wbg_typstcompilerbuilder_free(e>>>0,1)),Dt=typeof FinalizationRegistry>"u"?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry(e=>i.__wbg_typstfontresolver_free(e>>>0,1)),zt=typeof FinalizationRegistry>"u"?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry(e=>i.__wbg_typstfontresolverbuilder_free(e>>>0,1)),F=class e{static __wrap(t){t=t>>>0;let n=Object.create(e.prototype);return n.__wbg_ptr=t,Pt.register(n,n.__wbg_ptr,n),n}__destroy_into_raw(){let t=this.__wbg_ptr;return this.__wbg_ptr=0,Pt.unregister(this),t}free(){let t=this.__destroy_into_raw();i.__wbg_incrserver_free(t,0)}set_attach_debug_info(t){i.incrserver_set_attach_debug_info(this.__wbg_ptr,t)}current(){try{let r=i.__wbindgen_add_to_stack_pointer(-16);i.incrserver_current(r,this.__wbg_ptr);var t=a().getInt32(r+0,!0),n=a().getInt32(r+4,!0);let o;return t!==0&&(o=wt(t,n).slice(),i.__wbindgen_export4(t,n*1,1)),o}finally{i.__wbindgen_add_to_stack_pointer(16)}}reset(){i.incrserver_reset(this.__wbg_ptr)}};Symbol.dispose&&(F.prototype[Symbol.dispose]=F.prototype.free);O=class e{static __wrap(t){t=t>>>0;let n=Object.create(e.prototype);return n.__wbg_ptr=t,dt.register(n,n.__wbg_ptr,n),n}__destroy_into_raw(){let t=this.__wbg_ptr;return this.__wbg_ptr=0,dt.unregister(this),t}free(){let t=this.__destroy_into_raw();i.__wbg_proxycontext_free(t,0)}constructor(t){let n=i.proxycontext_new(f(t));return this.__wbg_ptr=n>>>0,dt.register(this,this.__wbg_ptr,this),this}get context(){let t=i.proxycontext_context(this.__wbg_ptr);return l(t)}untar(t,n){try{let s=i.__wbindgen_add_to_stack_pointer(-16),_=Ut(t,i.__wbindgen_export),c=b;i.proxycontext_untar(s,this.__wbg_ptr,_,c,f(n));var r=a().getInt32(s+0,!0),o=a().getInt32(s+4,!0);if(o)throw l(r)}finally{i.__wbindgen_add_to_stack_pointer(16)}}};Symbol.dispose&&(O.prototype[Symbol.dispose]=O.prototype.free);P=class e{static __wrap(t){t=t>>>0;let n=Object.create(e.prototype);return n.__wbg_ptr=t,jt.register(n,n.__wbg_ptr,n),n}__destroy_into_raw(){let t=this.__wbg_ptr;return this.__wbg_ptr=0,jt.unregister(this),t}free(){let t=this.__destroy_into_raw();i.__wbg_typstcompileworld_free(t,0)}compile(t,n){try{let _=i.__wbindgen_add_to_stack_pointer(-16);i.typstcompileworld_compile(_,this.__wbg_ptr,t,n);var r=a().getInt32(_+0,!0),o=a().getInt32(_+4,!0),s=a().getInt32(_+8,!0);if(s)throw l(o);return l(r)}finally{i.__wbindgen_add_to_stack_pointer(16)}}title(t){try{let _=i.__wbindgen_add_to_stack_pointer(-16);i.typstcompileworld_title(_,this.__wbg_ptr,t);var n=a().getInt32(_+0,!0),r=a().getInt32(_+4,!0),o=a().getInt32(_+8,!0),s=a().getInt32(_+12,!0);if(s)throw l(o);let c;return n!==0&&(c=I(n,r).slice(),i.__wbindgen_export4(n,r*1,1)),c}finally{i.__wbindgen_add_to_stack_pointer(16)}}get_artifact(t,n){try{let _=i.__wbindgen_add_to_stack_pointer(-16);i.typstcompileworld_get_artifact(_,this.__wbg_ptr,t,n);var r=a().getInt32(_+0,!0),o=a().getInt32(_+4,!0),s=a().getInt32(_+8,!0);if(s)throw l(o);return l(r)}finally{i.__wbindgen_add_to_stack_pointer(16)}}query(t,n,r){let o,s;try{let k=i.__wbindgen_add_to_stack_pointer(-16),B=h(n,i.__wbindgen_export,i.__wbindgen_export2),D=b;var _=v(r)?0:h(r,i.__wbindgen_export,i.__wbindgen_export2),c=b;i.typstcompileworld_query(k,this.__wbg_ptr,t,B,D,_,c);var d=a().getInt32(k+0,!0),g=a().getInt32(k+4,!0),w=a().getInt32(k+8,!0),y=a().getInt32(k+12,!0),p=d,m=g;if(y)throw p=0,m=0,l(w);return o=p,s=m,I(p,m)}finally{i.__wbindgen_add_to_stack_pointer(16),i.__wbindgen_export4(o,s,1)}}incr_compile(t,n){try{let _=i.__wbindgen_add_to_stack_pointer(-16);gt(t,F),i.typstcompileworld_incr_compile(_,this.__wbg_ptr,t.__wbg_ptr,n);var r=a().getInt32(_+0,!0),o=a().getInt32(_+4,!0),s=a().getInt32(_+8,!0);if(s)throw l(o);return l(r)}finally{i.__wbindgen_add_to_stack_pointer(16)}}};Symbol.dispose&&(P.prototype[Symbol.dispose]=P.prototype.free);j=class e{static __wrap(t){t=t>>>0;let n=Object.create(e.prototype);return n.__wbg_ptr=t,Lt.register(n,n.__wbg_ptr,n),n}__destroy_into_raw(){let t=this.__wbg_ptr;return this.__wbg_ptr=0,Lt.unregister(this),t}free(){let t=this.__destroy_into_raw();i.__wbg_typstcompiler_free(t,0)}reset(){try{let r=i.__wbindgen_add_to_stack_pointer(-16);i.typstcompiler_reset(r,this.__wbg_ptr);var t=a().getInt32(r+0,!0),n=a().getInt32(r+4,!0);if(n)throw l(t)}finally{i.__wbindgen_add_to_stack_pointer(16)}}set_fonts(t){try{let o=i.__wbindgen_add_to_stack_pointer(-16);gt(t,M),i.typstcompiler_set_fonts(o,this.__wbg_ptr,t.__wbg_ptr);var n=a().getInt32(o+0,!0),r=a().getInt32(o+4,!0);if(r)throw l(n)}finally{i.__wbindgen_add_to_stack_pointer(16)}}set_inputs(t){try{let o=i.__wbindgen_add_to_stack_pointer(-16);i.typstcompiler_set_inputs(o,this.__wbg_ptr,f(t));var n=a().getInt32(o+0,!0),r=a().getInt32(o+4,!0);if(r)throw l(n)}finally{i.__wbindgen_add_to_stack_pointer(16)}}add_source(t,n){let r=h(t,i.__wbindgen_export,i.__wbindgen_export2),o=b,s=h(n,i.__wbindgen_export,i.__wbindgen_export2),_=b;return i.typstcompiler_add_source(this.__wbg_ptr,r,o,s,_)!==0}map_shadow(t,n){let r=h(t,i.__wbindgen_export,i.__wbindgen_export2),o=b,s=Ut(n,i.__wbindgen_export),_=b;return i.typstcompiler_map_shadow(this.__wbg_ptr,r,o,s,_)!==0}unmap_shadow(t){let n=h(t,i.__wbindgen_export,i.__wbindgen_export2),r=b;return i.typstcompiler_unmap_shadow(this.__wbg_ptr,n,r)!==0}reset_shadow(){i.typstcompiler_reset_shadow(this.__wbg_ptr)}get_loaded_fonts(){try{let o=i.__wbindgen_add_to_stack_pointer(-16);i.typstcompiler_get_loaded_fonts(o,this.__wbg_ptr);var t=a().getInt32(o+0,!0),n=a().getInt32(o+4,!0),r=ke(t,n).slice();return i.__wbindgen_export4(t,n*4,4),r}finally{i.__wbindgen_add_to_stack_pointer(16)}}get_ast(t){let n,r;try{let w=i.__wbindgen_add_to_stack_pointer(-16),y=h(t,i.__wbindgen_export,i.__wbindgen_export2),p=b;i.typstcompiler_get_ast(w,this.__wbg_ptr,y,p);var o=a().getInt32(w+0,!0),s=a().getInt32(w+4,!0),_=a().getInt32(w+8,!0),c=a().getInt32(w+12,!0),d=o,g=s;if(c)throw d=0,g=0,l(_);return n=d,r=g,I(d,g)}finally{i.__wbindgen_add_to_stack_pointer(16),i.__wbindgen_export4(n,r,1)}}get_semantic_token_legend(){try{let o=i.__wbindgen_add_to_stack_pointer(-16);i.typstcompiler_get_semantic_token_legend(o,this.__wbg_ptr);var t=a().getInt32(o+0,!0),n=a().getInt32(o+4,!0),r=a().getInt32(o+8,!0);if(r)throw l(n);return l(t)}finally{i.__wbindgen_add_to_stack_pointer(16)}}get_semantic_tokens(t,n,r){try{let y=i.__wbindgen_add_to_stack_pointer(-16),p=h(t,i.__wbindgen_export,i.__wbindgen_export2),m=b;var o=v(n)?0:h(n,i.__wbindgen_export,i.__wbindgen_export2),s=b,_=v(r)?0:h(r,i.__wbindgen_export,i.__wbindgen_export2),c=b;i.typstcompiler_get_semantic_tokens(y,this.__wbg_ptr,p,m,o,s,_,c);var d=a().getInt32(y+0,!0),g=a().getInt32(y+4,!0),w=a().getInt32(y+8,!0);if(w)throw l(g);return l(d)}finally{i.__wbindgen_add_to_stack_pointer(16)}}snapshot(t,n,r){try{let m=i.__wbindgen_add_to_stack_pointer(-16);var o=v(t)?0:h(t,i.__wbindgen_export,i.__wbindgen_export2),s=b,_=v(n)?0:h(n,i.__wbindgen_export,i.__wbindgen_export2),c=b,d=v(r)?0:nt(r,i.__wbindgen_export),g=b;i.typstcompiler_snapshot(m,this.__wbg_ptr,o,s,_,c,d,g);var w=a().getInt32(m+0,!0),y=a().getInt32(m+4,!0),p=a().getInt32(m+8,!0);if(p)throw l(y);return P.__wrap(w)}finally{i.__wbindgen_add_to_stack_pointer(16)}}get_artifact(t,n){try{let _=i.__wbindgen_add_to_stack_pointer(-16),c=h(t,i.__wbindgen_export,i.__wbindgen_export2),d=b;i.typstcompiler_get_artifact(_,this.__wbg_ptr,c,d,n);var r=a().getInt32(_+0,!0),o=a().getInt32(_+4,!0),s=a().getInt32(_+8,!0);if(s)throw l(o);return l(r)}finally{i.__wbindgen_add_to_stack_pointer(16)}}compile(t,n,r,o){try{let p=i.__wbindgen_add_to_stack_pointer(-16);var s=v(t)?0:h(t,i.__wbindgen_export,i.__wbindgen_export2),_=b,c=v(n)?0:nt(n,i.__wbindgen_export),d=b;let m=h(r,i.__wbindgen_export,i.__wbindgen_export2),k=b;i.typstcompiler_compile(p,this.__wbg_ptr,s,_,c,d,m,k,o);var g=a().getInt32(p+0,!0),w=a().getInt32(p+4,!0),y=a().getInt32(p+8,!0);if(y)throw l(w);return l(g)}finally{i.__wbindgen_add_to_stack_pointer(16)}}query(t,n,r,o){let s,_;try{let z=i.__wbindgen_add_to_stack_pointer(-16),Qt=h(t,i.__wbindgen_export,i.__wbindgen_export2),Zt=b;var c=v(n)?0:nt(n,i.__wbindgen_export),d=b;let te=h(r,i.__wbindgen_export,i.__wbindgen_export2),ee=b;var g=v(o)?0:h(o,i.__wbindgen_export,i.__wbindgen_export2),w=b;i.typstcompiler_query(z,this.__wbg_ptr,Qt,Zt,c,d,te,ee,g,w);var y=a().getInt32(z+0,!0),p=a().getInt32(z+4,!0),m=a().getInt32(z+8,!0),k=a().getInt32(z+12,!0),B=y,D=p;if(k)throw B=0,D=0,l(m);return s=B,_=D,I(B,D)}finally{i.__wbindgen_add_to_stack_pointer(16),i.__wbindgen_export4(s,_,1)}}create_incr_server(){try{let o=i.__wbindgen_add_to_stack_pointer(-16);i.typstcompiler_create_incr_server(o,this.__wbg_ptr);var t=a().getInt32(o+0,!0),n=a().getInt32(o+4,!0),r=a().getInt32(o+8,!0);if(r)throw l(n);return F.__wrap(t)}finally{i.__wbindgen_add_to_stack_pointer(16)}}incr_compile(t,n,r,o){try{let w=i.__wbindgen_add_to_stack_pointer(-16),y=h(t,i.__wbindgen_export,i.__wbindgen_export2),p=b;var s=v(n)?0:nt(n,i.__wbindgen_export),_=b;gt(r,F),i.typstcompiler_incr_compile(w,this.__wbg_ptr,y,p,s,_,r.__wbg_ptr,o);var c=a().getInt32(w+0,!0),d=a().getInt32(w+4,!0),g=a().getInt32(w+8,!0);if(g)throw l(d);return l(c)}finally{i.__wbindgen_add_to_stack_pointer(16)}}};Symbol.dispose&&(j.prototype[Symbol.dispose]=j.prototype.free);V=class{__destroy_into_raw(){let t=this.__wbg_ptr;return this.__wbg_ptr=0,Bt.unregister(this),t}free(){let t=this.__destroy_into_raw();i.__wbg_typstcompilerbuilder_free(t,0)}constructor(){try{let o=i.__wbindgen_add_to_stack_pointer(-16);i.typstcompilerbuilder_new(o);var t=a().getInt32(o+0,!0),n=a().getInt32(o+4,!0),r=a().getInt32(o+8,!0);if(r)throw l(n);return this.__wbg_ptr=t>>>0,Bt.register(this,this.__wbg_ptr,this),this}finally{i.__wbindgen_add_to_stack_pointer(16)}}set_dummy_access_model(){try{let r=i.__wbindgen_add_to_stack_pointer(-16);i.typstcompilerbuilder_set_dummy_access_model(r,this.__wbg_ptr);var t=a().getInt32(r+0,!0),n=a().getInt32(r+4,!0);if(n)throw l(t)}finally{i.__wbindgen_add_to_stack_pointer(16)}}set_access_model(t,n,r,o,s){let _=i.typstcompilerbuilder_set_access_model(this.__wbg_ptr,f(t),f(n),f(r),f(o),f(s));return l(_)}set_package_registry(t,n){let r=i.typstcompilerbuilder_set_package_registry(this.__wbg_ptr,f(t),f(n));return l(r)}add_raw_font(t){let n=i.typstcompilerbuilder_add_raw_font(this.__wbg_ptr,f(t));return l(n)}add_lazy_font(t,n){let r=i.typstcompilerbuilder_add_lazy_font(this.__wbg_ptr,f(t),f(n));return l(r)}build(){let t=this.__destroy_into_raw(),n=i.typstcompilerbuilder_build(t);return l(n)}};Symbol.dispose&&(V.prototype[Symbol.dispose]=V.prototype.free);M=class e{static __wrap(t){t=t>>>0;let n=Object.create(e.prototype);return n.__wbg_ptr=t,Dt.register(n,n.__wbg_ptr,n),n}__destroy_into_raw(){let t=this.__wbg_ptr;return this.__wbg_ptr=0,Dt.unregister(this),t}free(){let t=this.__destroy_into_raw();i.__wbg_typstfontresolver_free(t,0)}};Symbol.dispose&&(M.prototype[Symbol.dispose]=M.prototype.free);$=class{__destroy_into_raw(){let t=this.__wbg_ptr;return this.__wbg_ptr=0,zt.unregister(this),t}free(){let t=this.__destroy_into_raw();i.__wbg_typstfontresolverbuilder_free(t,0)}constructor(){try{let o=i.__wbindgen_add_to_stack_pointer(-16);i.typstfontresolverbuilder_new(o);var t=a().getInt32(o+0,!0),n=a().getInt32(o+4,!0),r=a().getInt32(o+8,!0);if(r)throw l(n);return this.__wbg_ptr=t>>>0,zt.register(this,this.__wbg_ptr,this),this}finally{i.__wbindgen_add_to_stack_pointer(16)}}get_font_info(t){try{let s=i.__wbindgen_add_to_stack_pointer(-16);i.typstfontresolverbuilder_get_font_info(s,this.__wbg_ptr,f(t));var n=a().getInt32(s+0,!0),r=a().getInt32(s+4,!0),o=a().getInt32(s+8,!0);if(o)throw l(r);return l(n)}finally{i.__wbindgen_add_to_stack_pointer(16)}}add_raw_font(t){try{let o=i.__wbindgen_add_to_stack_pointer(-16);i.typstfontresolverbuilder_add_raw_font(o,this.__wbg_ptr,f(t));var n=a().getInt32(o+0,!0),r=a().getInt32(o+4,!0);if(r)throw l(n)}finally{i.__wbindgen_add_to_stack_pointer(16)}}add_lazy_font(t,n){try{let s=i.__wbindgen_add_to_stack_pointer(-16);i.typstfontresolverbuilder_add_lazy_font(s,this.__wbg_ptr,f(t),f(n));var r=a().getInt32(s+0,!0),o=a().getInt32(s+4,!0);if(o)throw l(r)}finally{i.__wbindgen_add_to_stack_pointer(16)}}build(){let t=this.__destroy_into_raw(),n=i.typstfontresolverbuilder_build(t);return l(n)}};Symbol.dispose&&($.prototype[Symbol.dispose]=$.prototype.free);Oe=new Set(["basic","cors","default"]);Vt=qt,$t=async function(e,t){throw new Error("Cannot import wasm module without importer: "+e+" "+t)}});var Jt={};re(Jt,{IncrServer:()=>F,ProxyContext:()=>O,TypstCompileWorld:()=>P,TypstCompiler:()=>j,TypstCompilerBuilder:()=>V,TypstFontResolver:()=>M,TypstFontResolverBuilder:()=>$,default:()=>Be,get_font_info:()=>Ce,initSync:()=>je,setImportWasmModule:()=>pt});var Be,De,ze,Ht=vt(()=>{ot();ot();ot();Be=Vt,De=async function(e,t){let n=new Function("m","return import(m)"),{readFileSync:r}=await n("fs"),o=new URL(e,t);return await r(o).buffer},ze=typeof process<"u"&&process.versions!=null&&process.versions.node!=null;ze&&pt(De)});var It=Symbol("Comlink.proxy"),oe=Symbol("Comlink.endpoint"),ie=Symbol("Comlink.releaseProxy"),at=Symbol("Comlink.finalizer"),G=Symbol("Comlink.thrown"),kt=e=>typeof e=="object"&&e!==null||typeof e=="function",se={canHandle:e=>kt(e)&&e[It],serialize(e){let{port1:t,port2:n}=new MessageChannel;return Q(e,t),[n,[n]]},deserialize(e){return e.start(),ue(e)}},_e={canHandle:e=>kt(e)&&G in e,serialize({value:e}){let t;return e instanceof Error?t={isError:!0,value:{message:e.message,name:e.name,stack:e.stack}}:t={isError:!1,value:e},[t,[]]},deserialize(e){throw e.isError?Object.assign(new Error(e.value.message),e.value):e.value}},St=new Map([["proxy",se],["throw",_e]]);function ae(e,t){for(let n of e)if(t===n||n==="*"||n instanceof RegExp&&n.test(t))return!0;return!1}function Q(e,t=globalThis,n=["*"]){t.addEventListener("message",function r(o){if(!o||!o.data)return;if(!ae(n,o.origin)){console.warn(`Invalid origin \'${o.origin}\' for comlink proxy`);return}let{id:s,type:_,path:c}=Object.assign({path:[]},o.data),d=(o.data.argumentList||[]).map(A),g;try{let w=c.slice(0,-1).reduce((p,m)=>p[m],e),y=c.reduce((p,m)=>p[m],e);switch(_){case"GET":g=y;break;case"SET":w[c.slice(-1)[0]]=A(o.data.value),g=!0;break;case"APPLY":g=y.apply(w,d);break;case"CONSTRUCT":{let p=new y(...d);g=le(p)}break;case"ENDPOINT":{let{port1:p,port2:m}=new MessageChannel;Q(e,m),g=Z(p,[p])}break;case"RELEASE":g=void 0;break;default:return}}catch(w){g={value:w,[G]:0}}Promise.resolve(g).catch(w=>({value:w,[G]:0})).then(w=>{let[y,p]=K(w);t.postMessage(Object.assign(Object.assign({},y),{id:s}),p),_==="RELEASE"&&(t.removeEventListener("message",r),Ft(t),at in e&&typeof e[at]=="function"&&e[at]())}).catch(w=>{let[y,p]=K({value:new TypeError("Unserializable return value"),[G]:0});t.postMessage(Object.assign(Object.assign({},y),{id:s}),p)})}),t.start&&t.start()}function ce(e){return e.constructor.name==="MessagePort"}function Ft(e){ce(e)&&e.close()}function ue(e,t){let n=new Map;return e.addEventListener("message",function(o){let{data:s}=o;if(!s||!s.id)return;let _=n.get(s.id);if(_)try{_(s)}finally{n.delete(s.id)}}),ct(e,n,[],t)}function H(e){if(e)throw new Error("Proxy has been released and is not useable")}function At(e){return E(e,new Map,{type:"RELEASE"}).then(()=>{Ft(e)})}var X=new WeakMap,Y="FinalizationRegistry"in globalThis&&new FinalizationRegistry(e=>{let t=(X.get(e)||0)-1;X.set(e,t),t===0&&At(e)});function fe(e,t){let n=(X.get(t)||0)+1;X.set(t,n),Y&&Y.register(e,t,e)}function de(e){Y&&Y.unregister(e)}function ct(e,t,n=[],r=function(){}){let o=!1,s=new Proxy(r,{get(_,c){if(H(o),c===ie)return()=>{de(s),At(e),t.clear(),o=!0};if(c==="then"){if(n.length===0)return{then:()=>s};let d=E(e,t,{type:"GET",path:n.map(g=>g.toString())}).then(A);return d.then.bind(d)}return ct(e,t,[...n,c])},set(_,c,d){H(o);let[g,w]=K(d);return E(e,t,{type:"SET",path:[...n,c].map(y=>y.toString()),value:g},w).then(A)},apply(_,c,d){H(o);let g=n[n.length-1];if(g===oe)return E(e,t,{type:"ENDPOINT"}).then(A);if(g==="bind")return ct(e,t,n.slice(0,-1));let[w,y]=xt(d);return E(e,t,{type:"APPLY",path:n.map(p=>p.toString()),argumentList:w},y).then(A)},construct(_,c){H(o);let[d,g]=xt(c);return E(e,t,{type:"CONSTRUCT",path:n.map(w=>w.toString()),argumentList:d},g).then(A)}});return fe(s,e),s}function ge(e){return Array.prototype.concat.apply([],e)}function xt(e){let t=e.map(K);return[t.map(n=>n[0]),ge(t.map(n=>n[1]))]}var Rt=new WeakMap;function Z(e,t){return Rt.set(e,t),e}function le(e){return Object.assign(e,{[It]:!0})}function K(e){for(let[t,n]of St)if(n.canHandle(e)){let[r,o]=n.serialize(e);return[{type:"HANDLER",name:t,value:r},o]}return[{type:"RAW",value:e},Rt.get(e)||[]]}function A(e){switch(e.type){case"HANDLER":return St.get(e.name).deserialize(e.value);case"RAW":return e.value}}function E(e,t,n,r){return new Promise(o=>{let s=we();t.set(s,o),e.start&&e.start(),e.postMessage(Object.assign({id:s},n),r)})}function we(){return new Array(4).fill(0).map(()=>Math.floor(Math.random()*Number.MAX_SAFE_INTEGER).toString(16)).join("-")}var ut=class{loadedFonts=new Set;fetcher=fetch;setFetcher(t){this.fetcher=t}async loadFonts(t,n){let r=new Function("m","return import(m)"),o=this.fetcher||=await(async function(){let{fetchBuilder:c,FileSystemCache:d}=await r("node-fetch-cache"),g=new d({cacheDirectory:".cache/typst/fonts"}),w=c.withCache(g);return function(y,p){let m=setTimeout(()=>{console.warn("font fetching is stucking:",y)},15e3);return w(y,p).finally(()=>{clearTimeout(m)})}})(),s=n.filter(c=>c instanceof Uint8Array||typeof c=="object"&&"info"in c?!0:this.loadedFonts.has(c)?!1:(this.loadedFonts.add(c),!0)),_=await Promise.all(s.map(async c=>{if(c instanceof Uint8Array){await t.add_raw_font(c);return}if(typeof c=="object"&&"info"in c){await t.add_lazy_font(c,"blob"in c?c.blob:be(c));return}return new Uint8Array(await(await o(c)).arrayBuffer())}));for(let c of _)c&&await t.add_raw_font(c)}async build(t,n,r){let o={ref:this,builder:n,hooks:r};for(let s of t?.beforeBuild??[])await s(void 0,o);return r.latelyBuild&&r.latelyBuild(o),await n.build()}};async function Mt(e,t,n,r){return await t.init(e?.getModule?.()),await new ut().build(e,new n,r)}function be(e){return()=>{let t=new XMLHttpRequest;return t.overrideMimeType("text/plain; charset=x-user-defined"),t.open("GET",e.url,!1),t.send(null),t.status===200&&(t.response instanceof String||typeof t.response=="string")?Uint8Array.from(t.response,n=>n.charCodeAt(0)):new Uint8Array}}var x=Symbol.for("reflexo-obj");var Et;(function(e){e[e.PIXEL_PER_PT=3]="PIXEL_PER_PT"})(Et||(Et={}));var ye=["DejaVuSansMono-Bold.ttf","DejaVuSansMono-BoldOblique.ttf","DejaVuSansMono-Oblique.ttf","DejaVuSansMono.ttf","LibertinusSerif-Bold.otf","LibertinusSerif-BoldItalic.otf","LibertinusSerif-Italic.otf","LibertinusSerif-Regular.otf","LibertinusSerif-Semibold.otf","LibertinusSerif-SemiboldItalic.otf","NewCM10-Bold.otf","NewCM10-BoldItalic.otf","NewCM10-Italic.otf","NewCM10-Regular.otf","NewCMMath-Bold.otf","NewCMMath-Book.otf","NewCMMath-Regular.otf"],me=["InriaSerif-Bold.ttf","InriaSerif-BoldItalic.ttf","InriaSerif-Italic.ttf","InriaSerif-Regular.ttf","Roboto-Regular.ttf","NotoSerifCJKsc-Regular.otf"],he=["TwitterColorEmoji.ttf","NotoColorEmoji-Regular-COLR.subset.ttf"];function ve(e){let t=[];if(e&&e?.assets!==!1&&e?.assets?.length&&e?.assets?.length>0){let n={text:"https://cdn.jsdelivr.net/gh/typst/typst-assets@v0.13.1/files/fonts/",_:"https://cdn.jsdelivr.net/gh/typst/typst-dev-assets@v0.13.1/files/fonts/"},r=e.assetUrlPrefix??n;typeof r=="string"?r={_:r}:r={...n,...r};for(let s of Object.keys(r)){let _=r[s];_[_.length-1]!=="/"&&(r[s]=_+"/")}let o=(s,_)=>_.map(c=>(r[s]||r._)+c);for(let s of e.assets)switch(s){case"text":t.push(...o(s,ye));break;case"cjk":t.push(...o(s,me));break;case"emoji":t.push(...o(s,he));break}}return t}function tt(e,t){let n=ve(t),r=async(o,{ref:s,builder:_})=>{t?.fetcher&&s.setFetcher(t.fetcher),await s.loadFonts(_,[...e,...n])};return r._preloadRemoteFontOptions=t,r._kind="fontLoader",r}function Tt(e){return async(t,{builder:n})=>new Promise(r=>{n.set_package_registry(e,function(o){return e.resolve(o,this)}),r()})}function Ct(e){return async(t,n)=>{if(n.alreadySetAccessModel)throw new Error(`already set some assess model before: ${n.alreadySetAccessModel.constructor?.name}(${n.alreadySetAccessModel})`);return n.alreadySetAccessModel=e,new Promise(r=>{n.builder.set_access_model(e,o=>{let s=e.getMTime(o);return s?s.getTime():0},o=>e.isFile(o)||!1,o=>e.getRealPath(o)||o,o=>e.readAll(o)),r()})}}var xe=e=>{let t=!1,n;return()=>t?n:(t=!0,n=e())},et=class{wasmBin;initOnce;constructor(t){if(typeof t!="function")throw new Error("initFn is not a function");this.initOnce=xe(async()=>{await t(this.wasmBin)})}async init(t){this.wasmBin=t,await this.initOnce()}};var J;(function(e){e[e.vector=0]="vector",e[e.pdf=1]="pdf",e[e._dummy=2]="_dummy"})(J||(J={}));var bt=class{[x];constructor(t){this[x]=t}reset(){this[x].reset()}current(){return this[x].current()}setAttachDebugInfo(t){this[x].set_attach_debug_info(t)}},Gt;Gt||(Gt={});var yt=class{[x];constructor(t){this[x]=t}compile(t){return this[x].compile(0,L(t?.diagnostics))}compileHtml(t){return this[x].compile(1,L(t?.diagnostics))}async query(t){return JSON.parse(this[x].query(0,t.selector,t.field))}title(){return this[x].title(0)}vector(t){return this[x].get_artifact(0,L(t?.diagnostics))||{}}pdf(t){return this[x].get_artifact(1,L(t?.diagnostics))||{}}},Ue=e=>new et(async t=>await e.default(t));function mt(){return new it}var it=class e{compiler;compilerJs;static defaultAssets=["text"];constructor(){}async init(t){this.compilerJs=await(t?.getWrapper?.()||Promise.resolve().then(()=>(Ht(),Jt)));let n=this.compilerJs.TypstCompilerBuilder,r={...t||{}},o=r.beforeBuild??=[],s=o.some(g=>g._preloadRemoteFontOptions!==void 0),_=o.some(g=>g._preloadRemoteFontOptions?.assets!==void 0),c=o.some(g=>g._preloadRemoteFontOptions?.assets===!1);if((!s||!_&&!c)&&o.push(tt([],{assets:e.defaultAssets})),!o.some(g=>g._kind==="fontLoader"))throw new Error("TypstCompiler: no font loader found, please use font loaders, e.g. loadFonts or preloadSystemFonts");this.compiler=await Mt(t,Ue(this.compilerJs),n,{})}setFonts(t){this.compiler.set_fonts(t)}compile(t){return new Promise(n=>{let r=this.compiler.snapshot(t.root,t.mainFilePath,Xt(t.inputs));if("incrementalServer"in t){n(r.incr_compile(t.incrementalServer[x],L(t.diagnostics)));return}n(r.get_artifact(t.format||J.vector,L(t.diagnostics)))})}async runWithWorld(t,n){let r=this.compiler.snapshot(t.root,t.mainFilePath,Xt(t.inputs)),o=await n(new yt(r));return r.free(),o}query(t){return this.runWithWorld(t,async n=>JSON.parse(await n.query(t)))}getSemanticTokenLegend(){return new Promise(t=>{t(this.compiler.get_semantic_token_legend())})}getSemanticTokens(t){return new Promise(n=>{this.compiler.reset(),n(this.compiler.get_semantic_tokens(t.offsetEncoding||"utf-16",t.mainFilePath,t.resultId))})}async withIncrementalServer(t){let n=new bt(this.compiler.create_incr_server());try{return await t(n)}finally{n[x].free()}}async getAst(t){return this.compiler.get_ast(t)}async reset(){await new Promise(t=>{this.compiler.reset(),t(void 0)})}addSource(t,n){if(arguments.length>2)throw new Error("use of addSource(path, source, isMain) is deprecated, please use addSource(path, source) instead");this.compiler.add_source(t,n)}mapShadow(t,n){this.compiler.map_shadow(t,n)}unmapShadow(t){this.compiler.unmap_shadow(t)}resetShadow(){this.compiler.reset_shadow()}renderPageToCanvas(){throw new Error("Please use the api TypstRenderer.renderToCanvas in v0.4.0")}};mt._impl=it;function Xt(e){return e?Object.entries(e):void 0}function L(e){switch(e){case"none":return 1;case"unix":return 2;default:return 3}}var st=class{mTimes=new Map;mData=new Map;constructor(){}reset(){this.mTimes.clear(),this.mData.clear()}insertFile(t,n,r){this.mTimes.set(t,r),this.mData.set(t,n)}removeFile(t){this.mTimes.delete(t),this.mData.delete(t)}getMTime(t){if(t.startsWith("/@memory/")&&this.mTimes.has(t))return this.mTimes.get(t)}isFile(){return!0}getRealPath(t){return t}readAll(t){if(t.startsWith("/@memory/")&&this.mData.has(t))return this.mData.get(t)}};var _t=class{am;cache=new Map;constructor(t){this.am=t}resolvePath(t){return`https://packages.typst.org/preview/${t.name}-${t.version}.tar.gz`}pullPackageData(t){let n=new XMLHttpRequest;if(n.overrideMimeType("text/plain; charset=x-user-defined"),n.open("GET",this.resolvePath(t),!1),n.send(null),n.status===200&&(n.response instanceof String||typeof n.response=="string"))return Uint8Array.from(n.response,r=>r.charCodeAt(0))}resolve(t,n){if(t.namespace!=="preview")return;let r=this.resolvePath(t);if(this.cache.has(r))return this.cache.get(r)();let o=this.pullPackageData(t);if(!o)return;let s=`/@memory/fetch/packages/${t.namespace}/${t.name}/${t.version}`,_=[];n.untar(o,(d,g,w)=>{_.push([s+"/"+d,g,new Date(w)])});let c=()=>{for(let[d,g,w]of _)this.am.insertFile(d,g,w);return s};return this.cache.set(r,c),c()}};function Yt(e){return[...e].sort((t,n)=>t.path.localeCompare(n.path)||t.range.startLine-n.range.startLine||t.range.startCol-n.range.startCol||t.range.endLine-n.range.endLine||t.range.endCol-n.range.endCol||t.message.localeCompare(n.message))}var Kt="/main.typ",ht=class{#e=null;#n=new st;#r;constructor(){this.#r=new _t(this.#n)}#t(){if(!this.#e)throw new Error("Compiler not initialized");return this.#e}async init(t,n,r){this.#e=mt(),await this.#e.init({getModule:()=>t,beforeBuild:[tt(n),...r?[Ct(this.#n),Tt(this.#r)]:[]]})}async compile(t){let{rawDiagnostics:n,vector:r}=await this.#t().runWithWorld({mainFilePath:t??Kt},async s=>{let _=await s.vector({diagnostics:"full"});if(!("result"in _))return{rawDiagnostics:_.diagnostics,vector:void 0};let c=[];try{c=(await s.compile({diagnostics:"full"})).diagnostics}catch(d){console.error("[typst-web-service] compile() threw after vector():",d)}return{rawDiagnostics:c,vector:_.result}}),o=Yt(n.map(s=>{let _=s.range.match(/(\\d+):(\\d+)-(\\d+):(\\d+)/);return{...s,severity:s.severity,range:_?{startLine:+_[1],startCol:+_[2],endLine:+_[3],endCol:+_[4]}:{startLine:0,startCol:0,endLine:0,endCol:0}}}));return r?Z({diagnostics:o,vector:r},[r.buffer]):{diagnostics:o}}async compilePdf(t){let n=await this.#t().compile({mainFilePath:t??Kt,format:J.pdf,diagnostics:"none"});if(!n.result)throw new Error("Compilation produced no output");return Z(n.result,[n.result.buffer])}mapShadow(t,n){this.#t().mapShadow(t,n)}mapShadowMany(t){let n=this.#t();for(let[r,o]of Object.entries(t))n.mapShadow(r,o)}unmapShadow(t){this.#t().unmapShadow(t)}resetShadow(){this.#t().resetShadow()}destroy(){this.#e=null}};Q(new ht);})();\n/*! Bundled license information:\n\ncomlink/dist/esm/comlink.mjs:\n (**\n * @license\n * Copyright 2019 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n *)\n*/\n');
|
|
18
18
|
}
|
|
19
19
|
function createAnalyzerWorker() {
|
|
20
20
|
return createBlobWorker('"use strict";(()=>{var $=Symbol("Comlink.proxy"),se=Symbol("Comlink.endpoint"),_e=Symbol("Comlink.releaseProxy"),W=Symbol("Comlink.finalizer"),L=Symbol("Comlink.thrown"),G=t=>typeof t=="object"&&t!==null||typeof t=="function",ce={canHandle:t=>G(t)&&t[$],serialize(t){let{port1:e,port2:n}=new MessageChannel;return z(t,e),[n,[n]]},deserialize(t){return t.start(),ge(t)}},ae={canHandle:t=>G(t)&&L in t,serialize({value:t}){let e;return t instanceof Error?e={isError:!0,value:{message:t.message,name:t.name,stack:t.stack}}:e={isError:!1,value:t},[e,[]]},deserialize(t){throw t.isError?Object.assign(new Error(t.value.message),t.value):t.value}},Y=new Map([["proxy",ce],["throw",ae]]);function fe(t,e){for(let n of t)if(e===n||n==="*"||n instanceof RegExp&&n.test(e))return!0;return!1}function z(t,e=globalThis,n=["*"]){e.addEventListener("message",function r(i){if(!i||!i.data)return;if(!fe(n,i.origin)){console.warn(`Invalid origin \'${i.origin}\' for comlink proxy`);return}let{id:s,type:_,path:c}=Object.assign({path:[]},i.data),a=(i.data.argumentList||[]).map(p),f;try{let u=c.slice(0,-1).reduce((g,A)=>g[A],t),d=c.reduce((g,A)=>g[A],t);switch(_){case"GET":f=d;break;case"SET":u[c.slice(-1)[0]]=p(i.data.value),f=!0;break;case"APPLY":f=d.apply(u,a);break;case"CONSTRUCT":{let g=new d(...a);f=ye(g)}break;case"ENDPOINT":{let{port1:g,port2:A}=new MessageChannel;z(t,A),f=we(g,[g])}break;case"RELEASE":f=void 0;break;default:return}}catch(u){f={value:u,[L]:0}}Promise.resolve(f).catch(u=>({value:u,[L]:0})).then(u=>{let[d,g]=D(u);e.postMessage(Object.assign(Object.assign({},d),{id:s}),g),_==="RELEASE"&&(e.removeEventListener("message",r),X(e),W in t&&typeof t[W]=="function"&&t[W]())}).catch(u=>{let[d,g]=D({value:new TypeError("Unserializable return value"),[L]:0});e.postMessage(Object.assign(Object.assign({},d),{id:s}),g)})}),e.start&&e.start()}function ue(t){return t.constructor.name==="MessagePort"}function X(t){ue(t)&&t.close()}function ge(t,e){let n=new Map;return t.addEventListener("message",function(i){let{data:s}=i;if(!s||!s.id)return;let _=n.get(s.id);if(_)try{_(s)}finally{n.delete(s.id)}}),N(t,n,[],e)}function k(t){if(t)throw new Error("Proxy has been released and is not useable")}function J(t){return h(t,new Map,{type:"RELEASE"}).then(()=>{X(t)})}var F=new WeakMap,C="FinalizationRegistry"in globalThis&&new FinalizationRegistry(t=>{let e=(F.get(t)||0)-1;F.set(t,e),e===0&&J(t)});function be(t,e){let n=(F.get(e)||0)+1;F.set(e,n),C&&C.register(t,e,t)}function le(t){C&&C.unregister(t)}function N(t,e,n=[],r=function(){}){let i=!1,s=new Proxy(r,{get(_,c){if(k(i),c===_e)return()=>{le(s),J(t),e.clear(),i=!0};if(c==="then"){if(n.length===0)return{then:()=>s};let a=h(t,e,{type:"GET",path:n.map(f=>f.toString())}).then(p);return a.then.bind(a)}return N(t,e,[...n,c])},set(_,c,a){k(i);let[f,u]=D(a);return h(t,e,{type:"SET",path:[...n,c].map(d=>d.toString()),value:f},u).then(p)},apply(_,c,a){k(i);let f=n[n.length-1];if(f===se)return h(t,e,{type:"ENDPOINT"}).then(p);if(f==="bind")return N(t,e,n.slice(0,-1));let[u,d]=V(a);return h(t,e,{type:"APPLY",path:n.map(g=>g.toString()),argumentList:u},d).then(p)},construct(_,c){k(i);let[a,f]=V(c);return h(t,e,{type:"CONSTRUCT",path:n.map(u=>u.toString()),argumentList:a},f).then(p)}});return be(s,t),s}function de(t){return Array.prototype.concat.apply([],t)}function V(t){let e=t.map(D);return[e.map(n=>n[0]),de(e.map(n=>n[1]))]}var K=new WeakMap;function we(t,e){return K.set(t,e),t}function ye(t){return Object.assign(t,{[$]:!0})}function D(t){for(let[e,n]of Y)if(n.canHandle(t)){let[r,i]=n.serialize(t);return[{type:"HANDLER",name:e,value:r},i]}return[{type:"RAW",value:t},K.get(t)||[]]}function p(t){switch(t.type){case"HANDLER":return Y.get(t.name).deserialize(t.value);case"RAW":return t.value}}function h(t,e,n,r){return new Promise(i=>{let s=pe();e.set(s,i),t.start&&t.start(),t.postMessage(Object.assign({id:s},n),r)})}function pe(){return new Array(4).fill(0).map(()=>Math.floor(Math.random()*Number.MAX_SAFE_INTEGER).toString(16)).join("-")}var Te={},o;function R(t){let e=o.__externref_table_alloc();return o.__wbindgen_externrefs.set(e,t),e}var Q=typeof FinalizationRegistry>"u"?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry(t=>t.dtor(t.a,t.b));function H(t){let e=typeof t;if(e=="number"||e=="boolean"||t==null)return`${t}`;if(e=="string")return`"${t}"`;if(e=="symbol"){let i=t.description;return i==null?"Symbol":`Symbol(${i})`}if(e=="function"){let i=t.name;return typeof i=="string"&&i.length>0?`Function(${i})`:"Function"}if(Array.isArray(t)){let i=t.length,s="[";i>0&&(s+=H(t[0]));for(let _=1;_<i;_++)s+=", "+H(t[_]);return s+="]",s}let n=/\\[object ([^\\]]+)\\]/.exec(toString.call(t)),r;if(n&&n.length>1)r=n[1];else return toString.call(t);if(r=="Object")try{return"Object("+JSON.stringify(t)+")"}catch{return"Object"}return t instanceof Error?`${t.name}: ${t.message}\n${t.stack}`:r}function Z(t,e){return t=t>>>0,E().subarray(t/1,t/1+e)}var m=null;function l(){return(m===null||m.buffer.detached===!0||m.buffer.detached===void 0&&m.buffer!==o.memory.buffer)&&(m=new DataView(o.memory.buffer)),m}function b(t,e){return t=t>>>0,Ee(t,e)}var O=null;function E(){return(O===null||O.byteLength===0)&&(O=new Uint8Array(o.memory.buffer)),O}function x(t,e){try{return t.apply(this,e)}catch(n){let r=R(n);o.__wbindgen_exn_store(r)}}function w(t){return t==null}function he(t,e,n,r){let i={a:t,b:e,cnt:1,dtor:n},s=(..._)=>{i.cnt++;let c=i.a;i.a=0;try{return r(c,i.b,..._)}finally{i.a=c,s._wbg_cb_unref()}};return s._wbg_cb_unref=()=>{--i.cnt===0&&(i.dtor(i.a,i.b),i.a=0,Q.unregister(i))},Q.register(s,i,i),s}function xe(t,e){let n=e(t.length*1,1)>>>0;return E().set(t,n/1),y=t.length,n}function v(t,e,n){if(n===void 0){let c=M.encode(t),a=e(c.length,1)>>>0;return E().subarray(a,a+c.length).set(c),y=c.length,a}let r=t.length,i=e(r,1)>>>0,s=E(),_=0;for(;_<r;_++){let c=t.charCodeAt(_);if(c>127)break;s[i+_]=c}if(_!==r){_!==0&&(t=t.slice(_)),i=n(i,r,r=_+t.length*3,1)>>>0;let c=E().subarray(i+_,i+r),a=M.encodeInto(t,c);_+=a.written,i=n(i,r,_,1)>>>0}return y=_,i}function re(t){let e=o.__wbindgen_externrefs.get(t);return o.__externref_table_dealloc(t),e}var I=new TextDecoder("utf-8",{ignoreBOM:!0,fatal:!0});I.decode();var ve=2146435072,U=0;function Ee(t,e){return U+=e,U>=ve&&(I=new TextDecoder("utf-8",{ignoreBOM:!0,fatal:!0}),I.decode(),U=e),I.decode(E().subarray(t,t+e))}var M=new TextEncoder;"encodeInto"in M||(M.encodeInto=function(t,e){let n=M.encode(t);return e.set(n),{read:t.length,written:n.length}});var y=0;function Se(t,e,n){o.wasm_bindgen__convert__closures_____invoke__h4b569589ab16bc8b(t,e,n)}function Ae(t,e,n,r){o.wasm_bindgen__convert__closures_____invoke__h298f91ca76697d7d(t,e,n,r)}var ee=typeof FinalizationRegistry>"u"?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry(t=>o.__wbg_individuallanguages_free(t>>>0,1)),te=typeof FinalizationRegistry>"u"?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry(t=>o.__wbg_languagecode_free(t>>>0,1)),q=typeof FinalizationRegistry>"u"?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry(t=>o.__wbg_proxycontext_free(t>>>0,1)),ne=typeof FinalizationRegistry>"u"?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry(t=>o.__wbg_tinymistlanguageserver_free(t>>>0,1)),P=class t{static __wrap(e){e=e>>>0;let n=Object.create(t.prototype);return n.__wbg_ptr=e,ee.register(n,n.__wbg_ptr,n),n}__destroy_into_raw(){let e=this.__wbg_ptr;return this.__wbg_ptr=0,ee.unregister(this),e}free(){let e=this.__destroy_into_raw();o.__wbg_individuallanguages_free(e,0)}get name(){let e,n;try{let r=o.individuallanguages_name(this.__wbg_ptr);return e=r[0],n=r[1],b(r[0],r[1])}finally{o.__wbindgen_free(e,n,1)}}get code(){let e,n;try{let r=o.individuallanguages_code(this.__wbg_ptr);return e=r[0],n=r[1],b(r[0],r[1])}finally{o.__wbindgen_free(e,n,1)}}};Symbol.dispose&&(P.prototype[Symbol.dispose]=P.prototype.free);var j=class t{static __wrap(e){e=e>>>0;let n=Object.create(t.prototype);return n.__wbg_ptr=e,te.register(n,n.__wbg_ptr,n),n}__destroy_into_raw(){let e=this.__wbg_ptr;return this.__wbg_ptr=0,te.unregister(this),e}free(){let e=this.__destroy_into_raw();o.__wbg_languagecode_free(e,0)}get name(){let e,n;try{let r=o.languagecode_name(this.__wbg_ptr);return e=r[0],n=r[1],b(r[0],r[1])}finally{o.__wbindgen_free(e,n,1)}}get code(){let e,n;try{let r=o.languagecode_code(this.__wbg_ptr);return e=r[0],n=r[1],b(r[0],r[1])}finally{o.__wbindgen_free(e,n,1)}}get code_2t(){let e,n;try{let r=o.languagecode_code_2t(this.__wbg_ptr);return e=r[0],n=r[1],b(r[0],r[1])}finally{o.__wbindgen_free(e,n,1)}}get code_2b(){let e,n;try{let r=o.languagecode_code_2b(this.__wbg_ptr);return e=r[0],n=r[1],b(r[0],r[1])}finally{o.__wbindgen_free(e,n,1)}}get code_3(){let e,n;try{let r=o.languagecode_code_3(this.__wbg_ptr);return e=r[0],n=r[1],b(r[0],r[1])}finally{o.__wbindgen_free(e,n,1)}}get individual_languages(){return o.languagecode_individual_languages(this.__wbg_ptr)}};Symbol.dispose&&(j.prototype[Symbol.dispose]=j.prototype.free);var T=class t{static __wrap(e){e=e>>>0;let n=Object.create(t.prototype);return n.__wbg_ptr=e,q.register(n,n.__wbg_ptr,n),n}__destroy_into_raw(){let e=this.__wbg_ptr;return this.__wbg_ptr=0,q.unregister(this),e}free(){let e=this.__destroy_into_raw();o.__wbg_proxycontext_free(e,0)}constructor(e){let n=o.proxycontext_new(e);return this.__wbg_ptr=n>>>0,q.register(this,this.__wbg_ptr,this),this}get context(){return o.proxycontext_context(this.__wbg_ptr)}untar(e,n){let r=xe(e,o.__wbindgen_malloc),i=y,s=o.proxycontext_untar(this.__wbg_ptr,r,i,n);if(s[1])throw re(s[0])}};Symbol.dispose&&(T.prototype[Symbol.dispose]=T.prototype.free);var S=class{__destroy_into_raw(){let e=this.__wbg_ptr;return this.__wbg_ptr=0,ne.unregister(this),e}free(){let e=this.__destroy_into_raw();o.__wbg_tinymistlanguageserver_free(e,0)}constructor(e){let n=o.tinymistlanguageserver_new(e);if(n[2])throw re(n[1]);return this.__wbg_ptr=n[0]>>>0,ne.register(this,this.__wbg_ptr,this),this}on_event(e){o.tinymistlanguageserver_on_event(this.__wbg_ptr,e)}on_request(e,n){let r=v(e,o.__wbindgen_malloc,o.__wbindgen_realloc),i=y;return o.tinymistlanguageserver_on_request(this.__wbg_ptr,r,i,n)}on_notification(e,n){let r=v(e,o.__wbindgen_malloc,o.__wbindgen_realloc),i=y;o.tinymistlanguageserver_on_notification(this.__wbg_ptr,r,i,n)}on_response(e){o.tinymistlanguageserver_on_response(this.__wbg_ptr,e)}static version(){let e,n;try{let r=o.tinymistlanguageserver_version();return e=r[0],n=r[1],b(r[0],r[1])}finally{o.__wbindgen_free(e,n,1)}}};Symbol.dispose&&(S.prototype[Symbol.dispose]=S.prototype.free);var Re=new Set(["basic","cors","default"]);async function Oe(t,e){if(typeof Response=="function"&&t instanceof Response){if(typeof WebAssembly.instantiateStreaming=="function")try{return await WebAssembly.instantiateStreaming(t,e)}catch(r){if(t.ok&&Re.has(t.type)&&t.headers.get("Content-Type")!=="application/wasm")console.warn("`WebAssembly.instantiateStreaming` failed because your server does not serve Wasm with `application/wasm` MIME type. Falling back to `WebAssembly.instantiate` which is slower. Original error:\\n",r);else throw r}let n=await t.arrayBuffer();return await WebAssembly.instantiate(n,e)}else{let n=await WebAssembly.instantiate(t,e);return n instanceof WebAssembly.Instance?{instance:n,module:t}:n}}function Me(){let t={};return t.wbg={},t.wbg.__wbg_Error_52673b7de5a0ca89=function(e,n){return Error(b(e,n))},t.wbg.__wbg_Number_2d1dcfcf4ec51736=function(e){return Number(e)},t.wbg.__wbg_String_8f0eb39a4a4c2f66=function(e,n){let r=String(n),i=v(r,o.__wbindgen_malloc,o.__wbindgen_realloc),s=y;l().setInt32(e+4,s,!0),l().setInt32(e+0,i,!0)},t.wbg.__wbg___wbindgen_bigint_get_as_i64_6e32f5e6aff02e1d=function(e,n){let r=n,i=typeof r=="bigint"?r:void 0;l().setBigInt64(e+8,w(i)?BigInt(0):i,!0),l().setInt32(e+0,!w(i),!0)},t.wbg.__wbg___wbindgen_boolean_get_dea25b33882b895b=function(e){let n=e,r=typeof n=="boolean"?n:void 0;return w(r)?16777215:r?1:0},t.wbg.__wbg___wbindgen_debug_string_adfb662ae34724b6=function(e,n){let r=H(n),i=v(r,o.__wbindgen_malloc,o.__wbindgen_realloc),s=y;l().setInt32(e+4,s,!0),l().setInt32(e+0,i,!0)},t.wbg.__wbg___wbindgen_in_0d3e1e8f0c669317=function(e,n){return e in n},t.wbg.__wbg___wbindgen_is_bigint_0e1a2e3f55cfae27=function(e){return typeof e=="bigint"},t.wbg.__wbg___wbindgen_is_function_8d400b8b1af978cd=function(e){return typeof e=="function"},t.wbg.__wbg___wbindgen_is_object_ce774f3490692386=function(e){let n=e;return typeof n=="object"&&n!==null},t.wbg.__wbg___wbindgen_is_string_704ef9c8fc131030=function(e){return typeof e=="string"},t.wbg.__wbg___wbindgen_is_undefined_f6b95eab589e0269=function(e){return e===void 0},t.wbg.__wbg___wbindgen_jsval_eq_b6101cc9cef1fe36=function(e,n){return e===n},t.wbg.__wbg___wbindgen_jsval_loose_eq_766057600fdd1b0d=function(e,n){return e==n},t.wbg.__wbg___wbindgen_number_get_9619185a74197f95=function(e,n){let r=n,i=typeof r=="number"?r:void 0;l().setFloat64(e+8,w(i)?0:i,!0),l().setInt32(e+0,!w(i),!0)},t.wbg.__wbg___wbindgen_string_get_a2a31e16edf96e42=function(e,n){let r=n,i=typeof r=="string"?r:void 0;var s=w(i)?0:v(i,o.__wbindgen_malloc,o.__wbindgen_realloc),_=y;l().setInt32(e+4,_,!0),l().setInt32(e+0,s,!0)},t.wbg.__wbg___wbindgen_throw_dd24417ed36fc46e=function(e,n){throw new Error(b(e,n))},t.wbg.__wbg__wbg_cb_unref_87dfb5aaa0cbcea7=function(e){e._wbg_cb_unref()},t.wbg.__wbg_call_3020136f7a2d6e44=function(){return x(function(e,n,r){return e.call(n,r)},arguments)},t.wbg.__wbg_call_78f94eb02ec7f9b2=function(){return x(function(e,n,r,i,s){return e.call(n,r,i,s)},arguments)},t.wbg.__wbg_call_abb4ff46ce38be40=function(){return x(function(e,n){return e.call(n)},arguments)},t.wbg.__wbg_done_62ea16af4ce34b24=function(e){return e.done},t.wbg.__wbg_entries_83c79938054e065f=function(e){return Object.entries(e)},t.wbg.__wbg_error_7534b8e9a36f1ab4=function(e,n){let r,i;try{r=e,i=n,console.error(b(e,n))}finally{o.__wbindgen_free(r,i,1)}},t.wbg.__wbg_getTimezoneOffset_45389e26d6f46823=function(e){return e.getTimezoneOffset()},t.wbg.__wbg_get_6b7bd52aca3f9671=function(e,n){return e[n>>>0]},t.wbg.__wbg_get_af9dab7e9603ea93=function(){return x(function(e,n){return Reflect.get(e,n)},arguments)},t.wbg.__wbg_get_with_ref_key_1dc361bd10053bfe=function(e,n){return e[n]},t.wbg.__wbg_individuallanguages_new=function(e){return P.__wrap(e)},t.wbg.__wbg_instanceof_ArrayBuffer_f3320d2419cd0355=function(e){let n;try{n=e instanceof ArrayBuffer}catch{n=!1}return n},t.wbg.__wbg_instanceof_Map_084be8da74364158=function(e){let n;try{n=e instanceof Map}catch{n=!1}return n},t.wbg.__wbg_instanceof_Uint8Array_da54ccc9d3e09434=function(e){let n;try{n=e instanceof Uint8Array}catch{n=!1}return n},t.wbg.__wbg_isArray_51fd9e6422c0a395=function(e){return Array.isArray(e)},t.wbg.__wbg_isSafeInteger_ae7d3f054d55fa16=function(e){return Number.isSafeInteger(e)},t.wbg.__wbg_iterator_27b7c8b35ab3e86b=function(){return Symbol.iterator},t.wbg.__wbg_length_22ac23eaec9d8053=function(e){return e.length},t.wbg.__wbg_length_d45040a40c570362=function(e){return e.length},t.wbg.__wbg_new_1ba21ce319a06297=function(){return new Object},t.wbg.__wbg_new_25f239778d6112b9=function(){return new Array},t.wbg.__wbg_new_6421f6084cc5bc5a=function(e){return new Uint8Array(e)},t.wbg.__wbg_new_8a6f238a6ece86ea=function(){return new Error},t.wbg.__wbg_new_b2db8aa2650f793a=function(e){return new Date(e)},t.wbg.__wbg_new_b546ae120718850e=function(){return new Map},t.wbg.__wbg_new_ff12d2b041fb48f1=function(e,n){try{var r={a:e,b:n},i=(_,c)=>{let a=r.a;r.a=0;try{return Ae(a,r.b,_,c)}finally{r.a=a}};return new Promise(i)}finally{r.a=r.b=0}},t.wbg.__wbg_new_from_slice_f9c22b9153b26992=function(e,n){return new Uint8Array(Z(e,n))},t.wbg.__wbg_new_no_args_cb138f77cf6151ee=function(e,n){return new Function(b(e,n))},t.wbg.__wbg_next_138a17bbf04e926c=function(e){return e.next},t.wbg.__wbg_next_3cfe5c0fe2a4cc53=function(){return x(function(e){return e.next()},arguments)},t.wbg.__wbg_now_2c95c9de01293173=function(e){return e.now()},t.wbg.__wbg_now_69d776cd24f5215b=function(){return Date.now()},t.wbg.__wbg_performance_7a3ffd0b17f663ad=function(e){return e.performance},t.wbg.__wbg_prototypesetcall_dfe9b766cdc1f1fd=function(e,n,r){Uint8Array.prototype.set.call(Z(e,n),r)},t.wbg.__wbg_proxycontext_new=function(e){return T.__wrap(e)},t.wbg.__wbg_push_7d9be8f38fc13975=function(e,n){return e.push(n)},t.wbg.__wbg_queueMicrotask_9b549dfce8865860=function(e){return e.queueMicrotask},t.wbg.__wbg_queueMicrotask_fca69f5bfad613a5=function(e){queueMicrotask(e)},t.wbg.__wbg_resolve_fd5bfbaa4ce36e1e=function(e){return Promise.resolve(e)},t.wbg.__wbg_set_3f1d0b984ed272ed=function(e,n,r){e[n]=r},t.wbg.__wbg_set_781438a03c0c3c81=function(){return x(function(e,n,r){return Reflect.set(e,n,r)},arguments)},t.wbg.__wbg_set_7df433eea03a5c14=function(e,n,r){e[n>>>0]=r},t.wbg.__wbg_set_efaaf145b9377369=function(e,n,r){return e.set(n,r)},t.wbg.__wbg_stack_0ed75d68575b0f3c=function(e,n){let r=n.stack,i=v(r,o.__wbindgen_malloc,o.__wbindgen_realloc),s=y;l().setInt32(e+4,s,!0),l().setInt32(e+0,i,!0)},t.wbg.__wbg_static_accessor_GLOBAL_769e6b65d6557335=function(){let e=typeof global>"u"?null:global;return w(e)?0:R(e)},t.wbg.__wbg_static_accessor_GLOBAL_THIS_60cf02db4de8e1c1=function(){let e=typeof globalThis>"u"?null:globalThis;return w(e)?0:R(e)},t.wbg.__wbg_static_accessor_SELF_08f5a74c69739274=function(){let e=typeof self>"u"?null:self;return w(e)?0:R(e)},t.wbg.__wbg_static_accessor_WINDOW_a8924b26aa92d024=function(){let e=typeof window>"u"?null:window;return w(e)?0:R(e)},t.wbg.__wbg_then_4f95312d68691235=function(e,n){return e.then(n)},t.wbg.__wbg_value_57b7b035e117f7ee=function(e){return e.value},t.wbg.__wbindgen_cast_2241b6af4c4b2941=function(e,n){return b(e,n)},t.wbg.__wbindgen_cast_4625c577ab2ec9ee=function(e){return BigInt.asUintN(64,e)},t.wbg.__wbindgen_cast_9ae0607507abb057=function(e){return e},t.wbg.__wbindgen_cast_b5bc9a99b1b9b782=function(e,n){return he(e,n,o.wasm_bindgen__closure__destroy__h21ca932816a58917,Se)},t.wbg.__wbindgen_cast_d6cd19b81560fd6e=function(e){return e},t.wbg.__wbindgen_init_externref_table=function(){let e=o.__wbindgen_externrefs,n=e.grow(4);e.set(0,void 0),e.set(n+0,void 0),e.set(n+1,null),e.set(n+2,!0),e.set(n+3,!1)},t}function Pe(t,e){return o=t.exports,ie.__wbindgen_wasm_module=e,m=null,O=null,o.__wbindgen_start(),o}async function ie(t){if(o!==void 0)return o;typeof t<"u"&&(Object.getPrototypeOf(t)===Object.prototype?{module_or_path:t}=t:console.warn("using deprecated parameters for the initialization function; pass a single object instead")),typeof t>"u"&&(t=new URL("tinymist_bg.wasm",Te.url));let e=Me();(typeof t=="string"||typeof Request=="function"&&t instanceof Request||typeof URL=="function"&&t instanceof URL)&&(t=fetch(t));let{instance:n,module:r}=await Oe(await t,e);return Pe(n,r)}var oe=ie;var B=class{#e=null;#o=[];#n(){if(!this.#e)throw new Error("Analyzer not initialized");return this.#e}#r(e,n){this.#n().on_notification("textDocument/didOpen",{textDocument:{uri:e,languageId:"typst",version:1,text:n}})}#s(e){this.#n().on_notification("textDocument/didClose",{textDocument:{uri:e}})}#i(e,n,r){this.#n().on_notification("textDocument/didChange",{textDocument:{uri:e,version:n},contentChanges:[{text:r}]})}#t(){if(this.#e)for(;this.#o.length>0;)for(let e of this.#o.splice(0))this.#e.on_event(e)}async init(e){await oe({module_or_path:e}),this.#e=new S({sendEvent:r=>{this.#o.push(r)},sendRequest:({id:r})=>{this.#e.on_response({id:r,result:null})},sendNotification:()=>{},resolveFn:()=>{}});let n=this.#e.on_request("initialize",{capabilities:{textDocument:{completion:{completionItem:{snippetSupport:!0}},hover:{contentFormat:["markdown","plaintext"]}}},rootUri:"file:///"});n&&typeof n=="object"&&"then"in n&&await n,this.#t(),this.#e.on_notification("initialized",{}),this.#t()}async didOpen(e,n){this.#r(e,n),this.#t()}async didClose(e){this.#s(e),this.#t()}async didChange(e,n,r){this.#i(e,n,r),this.#t()}async didChangeMany(e,n){this.#n();for(let{uri:r,content:i}of e)this.#r(r,i);for(let{uri:r,version:i,content:s}of n)this.#i(r,i,s);this.#t()}async didCloseMany(e){this.#n();for(let n of e)this.#s(n);this.#t()}async completion(e,n){let r=await this.#n().on_request("textDocument/completion",{textDocument:{uri:e},position:n});return this.#t(),r??null}async hover(e,n){let r=await this.#n().on_request("textDocument/hover",{textDocument:{uri:e},position:n});return this.#t(),r??null}async completionWithDoc(e,n,r,i,s){return s==="open"?this.#r(e,r):this.#i(e,n,r),this.completion(e,i)}async hoverWithDoc(e,n,r,i,s){return s==="open"?this.#r(e,r):this.#i(e,n,r),this.hover(e,i)}destroy(){this.#e?.free(),this.#e=null}};z(new B);})();\n/*! Bundled license information:\n\ncomlink/dist/esm/comlink.mjs:\n (**\n * @license\n * Copyright 2019 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n *)\n*/\n');
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/analyzer.ts","../src/rpc.ts","../src/identifiers.ts","../src/compiler.ts","../src/formatter.ts","../src/compile-scheduler.ts","../src/project.ts","../src/renderer.ts"],"sourcesContent":["import * as Comlink from \"comlink\";\nimport type {\n LspCompletionResponse,\n LspHover,\n LspPosition,\n} from \"./analyzer-types.js\";\nimport type { AnalyzerWorker } from \"./analyzer-worker.js\";\nimport { createAnalyzerWorker } from \"./rpc.js\";\n\nexport interface TypstAnalyzerOptions {\n /**\n * Explicit Worker instance. When omitted, an inlined blob worker is created automatically.\n * Use this for Vite apps:\n * `await TypstAnalyzer.create({ worker: new Worker(new URL('typst-web-service/analyzer-worker', import.meta.url), { type: 'module' }) })`\n */\n worker?: Worker;\n /**\n * URL to the tinymist WASM binary.\n * Required — there is no default CDN URL for tinymist-web.\n */\n wasmUrl: string;\n}\n\n/**\n * Manages a tinymist language server in a Web Worker. Provides LSP-based\n * completion and hover for Typst documents.\n *\n * const analyzer = await TypstAnalyzer.create({ wasmUrl: '...' });\n */\nexport class TypstAnalyzer {\n private readonly proxy: Comlink.Remote<AnalyzerWorker>;\n private readonly worker: Worker;\n private versionCounter = 0;\n /**\n * Last content pushed to the worker per URI. Presence is the source of\n * truth for \"is this URI opened on the worker?\"; value drives own-RPC dedup.\n */\n private readonly content = new Map<string, string>();\n\n private constructor(worker: Worker, proxy: Comlink.Remote<AnalyzerWorker>) {\n this.worker = worker;\n this.proxy = proxy;\n }\n\n static async create(options: TypstAnalyzerOptions): Promise<TypstAnalyzer> {\n const worker = options.worker ?? createAnalyzerWorker();\n const proxy = Comlink.wrap<AnalyzerWorker>(worker);\n const absoluteWasmUrl = new URL(options.wasmUrl, globalThis.location?.href)\n .href;\n\n const analyzer = new TypstAnalyzer(worker, proxy);\n\n await proxy.init(absoluteWasmUrl);\n\n return analyzer;\n }\n\n async didOpen(uri: string, content: string): Promise<void> {\n await this.proxy.didOpen(uri, content);\n this.content.set(uri, content);\n }\n\n async didClose(uri: string): Promise<void> {\n if (!this.content.has(uri)) return;\n await this.proxy.didClose(uri);\n this.content.delete(uri);\n }\n\n /**\n * Notify the analyzer that a document has changed. Skips the RPC when the\n * content matches what the worker last saw.\n */\n async didChange(uri: string, content: string): Promise<void> {\n if (!this.content.has(uri)) {\n await this.didOpen(uri, content);\n return;\n }\n if (this.content.get(uri) === content) return;\n const version = ++this.versionCounter;\n await this.proxy.didChange(uri, version, content);\n this.content.set(uri, content);\n }\n\n /**\n * Batch document changes. Splits inputs into opens (first-time URIs) and\n * changes (already-open URIs) and sends them in a single worker roundtrip.\n * Skips unchanged documents; returns without an RPC if nothing is pending.\n */\n async didChangeMany(docs: Record<string, string>): Promise<void> {\n const opens: Array<{ uri: string; content: string }> = [];\n const changes: Array<{ uri: string; version: number; content: string }> =\n [];\n const updates: Array<[string, string]> = [];\n for (const [uri, content] of Object.entries(docs)) {\n if (!this.content.has(uri)) {\n opens.push({ uri, content });\n updates.push([uri, content]);\n } else if (this.content.get(uri) !== content) {\n changes.push({ uri, version: ++this.versionCounter, content });\n updates.push([uri, content]);\n }\n }\n if (opens.length === 0 && changes.length === 0) return;\n await this.proxy.didChangeMany(opens, changes);\n for (const [uri, content] of updates) this.content.set(uri, content);\n }\n\n /**\n * Batch document closes. Filters to currently-open URIs and sends the set\n * in a single worker roundtrip.\n */\n async didCloseMany(uris: string[]): Promise<void> {\n const toClose: string[] = [];\n for (const uri of uris) {\n if (this.content.has(uri)) toClose.push(uri);\n }\n if (toClose.length === 0) return;\n await this.proxy.didCloseMany(toClose);\n for (const uri of toClose) this.content.delete(uri);\n }\n\n /**\n * Request completion at `position` for `uri`, with `content` as the current\n * document state. Bundles the didChange notification with the request in one\n * worker roundtrip; degrades to a plain completion request when the worker\n * already has this exact content.\n */\n async completion(\n uri: string,\n content: string,\n position: LspPosition,\n ): Promise<LspCompletionResponse> {\n if (this.content.get(uri) === content) {\n return this.proxy.completion(uri, position);\n }\n const isOpen = this.content.has(uri);\n const version = ++this.versionCounter;\n const result = await this.proxy.completionWithDoc(\n uri,\n version,\n content,\n position,\n isOpen ? \"change\" : \"open\",\n );\n this.content.set(uri, content);\n return result;\n }\n\n /**\n * Request hover at `position` for `uri`, with `content` as the current\n * document state. Bundles the didChange notification with the request in one\n * worker roundtrip; degrades to a plain hover request when the worker\n * already has this exact content.\n */\n async hover(\n uri: string,\n content: string,\n position: LspPosition,\n ): Promise<LspHover | null> {\n if (this.content.get(uri) === content) {\n return this.proxy.hover(uri, position);\n }\n const isOpen = this.content.has(uri);\n const version = ++this.versionCounter;\n const result = await this.proxy.hoverWithDoc(\n uri,\n version,\n content,\n position,\n isOpen ? \"change\" : \"open\",\n );\n this.content.set(uri, content);\n return result;\n }\n\n destroy(): void {\n this.proxy[Comlink.releaseProxy]();\n this.worker.terminate();\n }\n}\n","// Injected at build time by tsup (see tsup.config.ts)\ndeclare const __WORKER_CODE__: string;\ndeclare const __ANALYZER_WORKER_CODE__: string;\ndeclare const __RENDERER_WORKER_CODE__: string;\n\n/** Create a Worker from an inlined code string, auto-revoking the blob URL on terminate. */\nfunction createBlobWorker(code: string): Worker {\n const blob = new Blob([code], { type: \"application/javascript\" });\n const url = URL.createObjectURL(blob);\n const worker = new Worker(url);\n const origTerminate = worker.terminate.bind(worker);\n worker.terminate = () => {\n origTerminate();\n URL.revokeObjectURL(url);\n };\n return worker;\n}\n\n/** Create a blob Worker from the inlined compiler worker code. */\nexport function createWorker(): Worker {\n return createBlobWorker(__WORKER_CODE__);\n}\n\n/** Create a blob Worker from the inlined analyzer worker code. */\nexport function createAnalyzerWorker(): Worker {\n return createBlobWorker(__ANALYZER_WORKER_CODE__);\n}\n\n/** Create a blob Worker from the inlined renderer worker code. */\nexport function createRendererWorker(): Worker {\n return createBlobWorker(__RENDERER_WORKER_CODE__);\n}\n","/**\n * Two addressing schemes live in this codebase. This file is the only place\n * that knows how they relate. Keeping the vocabulary and conversions colocated\n * means a new contributor can read one file and understand the model.\n *\n * 1. Path — \"/main.typ\". Always leading-slash, always forward slashes.\n * Used by the compiler VFS, the `TypstProject` public API,\n * and the `typstFilePath` facet. Addresses a file within\n * the project.\n *\n * 2. AnalyzerUri — \"untitled:project/main.typ\". What tinymist's LSP expects.\n * Derived from a Path plus the analyzer URI root.\n *\n * The types below are type aliases, not branded/opaque types. That's\n * deliberate: callers can pass string literals where a Path is expected\n * without wrapping, and the aliases only serve as self-documenting\n * signatures. Ingress points still need to call `normalizePath` to defend\n * against un-normalized input — the alias does not imply the string has\n * been normalized.\n */\n\n/** `/path/to/file.typ` — leading-slash, forward slashes only. */\nexport type Path = string;\n\n/** `untitled:project/path/to/file.typ` — what tinymist's LSP consumes. */\nexport type AnalyzerUri = string;\n\n/** Ensure a path starts with a leading slash. Idempotent. */\nexport function normalizePath(path: string): Path {\n return path.startsWith(\"/\") ? path : `/${path}`;\n}\n\n/**\n * Normalize an analyzer URI root. Ensures leading slash, strips trailing\n * slashes. Special-cases \"/\" → \"\" so URIs don't end up with a leading\n * `untitled://`.\n */\nexport function normalizeRoot(rootPath: string): string {\n const root = normalizePath(rootPath);\n return root === \"/\" ? \"\" : root.replace(/\\/+$/, \"\");\n}\n\n/**\n * Build the analyzer URI for a given project path. `root` is expected to\n * already be normalized (see `normalizeRoot`).\n *\n * pathToAnalyzerUri(\"/main.typ\", \"/project\") -> \"untitled:project/main.typ\"\n */\nexport function pathToAnalyzerUri(path: Path, root: string): AnalyzerUri {\n const bare = root.replace(/^\\//, \"\");\n return `untitled:${bare}${normalizePath(path)}`;\n}\n","import * as Comlink from \"comlink\";\nimport { createWorker } from \"./rpc.js\";\nimport type { DiagnosticMessage } from \"./types.js\";\nimport type { CompilerWorker } from \"./compiler-worker.js\";\n\ndeclare const __TYPST_TS_WEB_COMPILER_VERSION__: string;\n\nexport interface CompileResult {\n diagnostics: DiagnosticMessage[];\n /** Vector artifact bytes from the compiler, usable with TypstRenderer for SVG rendering. */\n vector?: Uint8Array;\n}\n\nexport interface TypstCompilerOptions {\n /**\n * Explicit Worker instance. When omitted, an inlined blob worker is created automatically.\n * Use this for Vite apps to get proper source maps:\n * `await TypstCompiler.create({ worker: new Worker(new URL('typst-web-service/compiler-worker', import.meta.url)) })`\n */\n worker?: Worker;\n /**\n * URL to the typst-ts-web-compiler WASM binary.\n * Defaults to the matching version on jsDelivr CDN.\n * Override with a local asset URL for offline support or faster load:\n * `new URL('@myriaddreamin/typst-ts-web-compiler/pkg/typst_ts_web_compiler_bg.wasm', import.meta.url).href`\n */\n wasmUrl?: string;\n /** Font URLs to load into the Typst compiler. Defaults to Roboto from jsDelivr. */\n fonts?: string[];\n /**\n * Enable fetching @preview/ packages from packages.typst.org on demand.\n * Default: true.\n */\n packages?: boolean;\n}\n\nconst DEFAULT_FONTS = [\n \"https://cdn.jsdelivr.net/npm/roboto-font@0.1.0/fonts/Roboto/roboto-regular-webfont.ttf\",\n];\n\nconst defaultWasmUrl = () =>\n `https://cdn.jsdelivr.net/npm/@myriaddreamin/typst-ts-web-compiler@${__TYPST_TS_WEB_COMPILER_VERSION__}/pkg/typst_ts_web_compiler_bg.wasm`;\n\n/**\n * Manages a Typst compiler worker. Create one instance and share it across\n * all extensions (linter, autocomplete, preview, etc.).\n *\n * await TypstCompiler.create() // blob worker, defaults\n * await TypstCompiler.create({ wasmUrl: '...' }) // blob worker, custom WASM\n * await TypstCompiler.create({ worker: myWorker }) // explicit Worker (Vite)\n * await TypstCompiler.create({ worker: myWorker, fonts: [...] }) // explicit Worker + options\n */\nexport class TypstCompiler {\n private readonly proxy: Comlink.Remote<CompilerWorker>;\n private readonly worker: Worker;\n private readonly encoder = new TextEncoder();\n /** Last text content pushed per path. Drives own-RPC dedup. Invalidated by binary writes. */\n private readonly content = new Map<string, string>();\n\n private constructor(worker: Worker, proxy: Comlink.Remote<CompilerWorker>) {\n this.worker = worker;\n this.proxy = proxy;\n }\n\n static async create(\n options: TypstCompilerOptions = {},\n ): Promise<TypstCompiler> {\n const worker = options.worker ?? createWorker();\n const proxy = Comlink.wrap<CompilerWorker>(worker);\n\n await proxy.init(\n options.wasmUrl ?? defaultWasmUrl(),\n options.fonts ?? DEFAULT_FONTS,\n options.packages ?? true,\n );\n\n return new TypstCompiler(worker, proxy);\n }\n\n /**\n * Compile whatever is currently in the VFS (populated via\n * setText/setBinary/setJson/setMany). Defaults to compiling \"/main.typ\";\n * override with `entry`.\n */\n compile(entry?: string): Promise<CompileResult> {\n return this.proxy.compile(entry);\n }\n\n /**\n * Compile to PDF. Operates on whatever is currently in the VFS (populated\n * via setText/setBinary/setJson/setMany). Defaults to compiling \"/main.typ\";\n * override with `entry`.\n */\n compilePdf(entry?: string): Promise<Uint8Array> {\n return this.proxy.compilePdf(entry);\n }\n\n /**\n * Add or overwrite a text file in the virtual compiler filesystem. Skips\n * the worker RPC when `source` matches the last value pushed for `path`.\n */\n async setText(path: string, source: string): Promise<void> {\n if (this.content.get(path) === source) return;\n await this.proxy.mapShadow(path, this.encoder.encode(source));\n this.content.set(path, source);\n }\n\n /** Add or overwrite a JSON file in the virtual compiler filesystem. */\n setJson(\n path: string,\n value: unknown,\n replacer?: (this: unknown, key: string, value: unknown) => unknown,\n space?: string | number,\n ): Promise<void> {\n return this.setText(path, JSON.stringify(value, replacer, space));\n }\n\n /**\n * Add or overwrite multiple files in the virtual compiler filesystem in a\n * single worker roundtrip. Strings are UTF-8 encoded; Uint8Arrays are\n * passed through. Text entries unchanged since their last push are skipped;\n * binary entries always push and invalidate the text cache for their path.\n */\n async setMany(files: Record<string, string | Uint8Array>): Promise<void> {\n const encoded: Record<string, Uint8Array> = {};\n const textUpdates: Array<[string, string]> = [];\n const binaryInvalidations: string[] = [];\n for (const [path, content] of Object.entries(files)) {\n if (typeof content === \"string\") {\n if (this.content.get(path) === content) continue;\n textUpdates.push([path, content]);\n encoded[path] = this.encoder.encode(content);\n } else {\n binaryInvalidations.push(path);\n encoded[path] = content;\n }\n }\n if (Object.keys(encoded).length === 0) return;\n await this.proxy.mapShadowMany(encoded);\n for (const [path, content] of textUpdates) this.content.set(path, content);\n for (const path of binaryInvalidations) this.content.delete(path);\n }\n\n /** Add or overwrite a binary file in the virtual compiler filesystem. */\n async setBinary(\n path: string,\n content: ArrayBuffer | ArrayBufferView,\n ): Promise<void> {\n const bytes =\n content instanceof ArrayBuffer\n ? new Uint8Array(content)\n : new Uint8Array(\n content.buffer,\n content.byteOffset,\n content.byteLength,\n );\n await this.proxy.mapShadow(path, bytes);\n this.content.delete(path);\n }\n\n /** Remove a file from the virtual compiler filesystem. */\n async remove(path: string): Promise<void> {\n await this.proxy.unmapShadow(path);\n this.content.delete(path);\n }\n\n /** Clear all virtual files from the compiler filesystem. */\n async clear(): Promise<void> {\n await this.proxy.resetShadow();\n this.content.clear();\n }\n\n destroy(): void {\n this.proxy[Comlink.releaseProxy]();\n this.worker.terminate();\n }\n}\n","export interface FormatConfig {\n /** Number of spaces per indentation level. Default: 2 */\n tab_spaces?: number;\n /** Maximum line width. Default: 80 */\n max_width?: number;\n /** Maximum consecutive blank lines allowed. */\n blank_lines_upper_bound?: number;\n /** Collapse consecutive whitespace in markup to a single space. */\n collapse_markup_spaces?: boolean;\n /** Sort import items alphabetically. */\n reorder_import_items?: boolean;\n /** Wrap text in markup to fit within max_width. Implies collapse_markup_spaces. */\n wrap_text?: boolean;\n}\n\nexport interface FormatRangeResult {\n /** Start index (UTF-16) of the actual formatted range. */\n start: number;\n /** End index (UTF-16) of the actual formatted range. */\n end: number;\n /** The formatted text for the range. */\n text: string;\n}\n\ntype TypstyleModule = typeof import(\"@typstyle/typstyle-wasm-bundler\");\n\nlet typstylePromise: Promise<TypstyleModule> | null = null;\n\nfunction getTypstyle(): Promise<TypstyleModule> {\n if (!typstylePromise) {\n typstylePromise = import(\"@typstyle/typstyle-wasm-bundler\").catch((err) => {\n typstylePromise = null;\n throw err;\n });\n }\n return typstylePromise;\n}\n\n/**\n * Typst code formatter powered by typstyle.\n *\n * Runs on the main thread — typstyle is lightweight and fast.\n * The WASM module is loaded lazily on first format call.\n * Requires a bundler that supports WASM imports (e.g. Vite, webpack).\n *\n * const formatter = TypstFormatter.create({ tab_spaces: 2, max_width: 80 });\n * const formatted = await formatter.format(source);\n */\nexport class TypstFormatter {\n private config: FormatConfig;\n\n private constructor(config: FormatConfig = {}) {\n this.config = config;\n // Eagerly start loading WASM so it's ready by first use.\n // Swallow preload errors — they'll surface on first format() call.\n getTypstyle().catch(() => {});\n }\n\n static create(config: FormatConfig = {}): TypstFormatter {\n return new TypstFormatter(config);\n }\n\n /** Format an entire Typst source string. */\n async format(source: string): Promise<string> {\n const typstyle = await getTypstyle();\n return typstyle.format(source, this.config);\n }\n\n /** Format a range within a Typst source string. Indices are UTF-16 code units. */\n async formatRange(\n source: string,\n start: number,\n end: number,\n ): Promise<FormatRangeResult> {\n const typstyle = await getTypstyle();\n const result = typstyle.format_range(source, start, end, this.config);\n return { start: result.start, end: result.end, text: result.text };\n }\n}\n","interface CompileSchedulerOptions {\n /** Minimum idle time (ms) after the last request before firing. Default: 0. */\n debounceMs?: number;\n /**\n * Maximum time (ms) the debounce may keep deferring during continuous\n * requests. Guarantees a fire at least this often so users see progress\n * while typing. Default: 0 (no cap).\n */\n maxWaitMs?: number;\n}\n\n/**\n * Debounce helper with a max-wait ceiling for coalescing compile requests. A\n * burst of `schedule(cb)` calls within `debounceMs` collapses into one fire;\n * during sustained bursts, `maxWaitMs` caps how long the debounce may keep\n * deferring.\n */\nexport class CompileScheduler {\n private debounceTimer: ReturnType<typeof setTimeout> | null = null;\n private maxWaitTimer: ReturnType<typeof setTimeout> | null = null;\n\n constructor(private readonly options: CompileSchedulerOptions = {}) {}\n\n schedule(callback: () => void): void {\n if (this.debounceTimer) {\n clearTimeout(this.debounceTimer);\n this.debounceTimer = null;\n }\n\n const delay = Math.max(0, this.options.debounceMs ?? 0);\n this.debounceTimer = setTimeout(() => {\n this.debounceTimer = null;\n this.clearMaxWait();\n callback();\n }, delay);\n\n const maxWait = this.options.maxWaitMs;\n if (maxWait != null && maxWait > 0 && !this.maxWaitTimer) {\n this.maxWaitTimer = setTimeout(() => {\n this.maxWaitTimer = null;\n if (this.debounceTimer) {\n clearTimeout(this.debounceTimer);\n this.debounceTimer = null;\n callback();\n }\n }, maxWait);\n }\n }\n\n /** Cancel any pending scheduled fire without calling the callback. */\n cancel(): void {\n if (this.debounceTimer) {\n clearTimeout(this.debounceTimer);\n this.debounceTimer = null;\n }\n this.clearMaxWait();\n }\n\n private clearMaxWait(): void {\n if (this.maxWaitTimer) {\n clearTimeout(this.maxWaitTimer);\n this.maxWaitTimer = null;\n }\n }\n}\n","import type { TypstAnalyzer } from \"./analyzer.js\";\nimport type {\n LspCompletionResponse,\n LspHover,\n LspPosition,\n} from \"./analyzer-types.js\";\nimport { CompileScheduler } from \"./compile-scheduler.js\";\nimport type { CompileResult, TypstCompiler } from \"./compiler.js\";\nimport {\n normalizePath,\n normalizeRoot,\n type Path,\n pathToAnalyzerUri,\n} from \"./identifiers.js\";\n\nexport interface TypstProjectOptions {\n compiler: TypstCompiler;\n /**\n * Optional analyzer. When provided, text file operations also sync with the\n * analyzer so completions / hover reflect the current state.\n */\n analyzer?: TypstAnalyzer;\n /** Default entry file path. Default: \"/main.typ\". */\n entry?: string;\n /**\n * Prefix used to build the `untitled:` URIs handed to the analyzer.\n * Default: \"/project\". A path of `/main.typ` becomes\n * `untitled:project/main.typ`. Only affects URI construction — the compiler\n * and project VFS use the raw paths unchanged.\n */\n analyzerUriRoot?: string;\n /**\n * Scheduling for auto-compiles after VFS mutations. Mutations debounce by\n * `debounceMs`; `maxWaitMs` caps how long the debounce can keep deferring\n * during sustained edits so the user still sees progress.\n */\n autoCompile?: AutoCompileOptions;\n}\n\nexport interface AutoCompileOptions {\n /**\n * Idle time (ms) after the last VFS mutation before a compile fires.\n * Default: 0 — compile fires on the next macrotask. Set higher (e.g. 150) to\n * coalesce rapid edits.\n */\n debounceMs?: number;\n /**\n * Maximum time (ms) the debounce is allowed to defer a compile during\n * sustained mutation bursts. Default: 0 (no cap — pure debounce).\n */\n maxWaitMs?: number;\n}\n\nconst DEFAULT_ENTRY = \"/main.typ\";\nconst DEFAULT_ROOT = \"/project\";\n\n/**\n * Coordinates a compiler + analyzer pair for multi-file Typst projects.\n *\n * Owns the project's virtual filesystem state. Editors push incremental\n * `setText` updates as the user types; the project mirrors those edits to\n * both the compiler's shadow VFS and the analyzer's open-document set, then\n * compiles or services LSP requests against the current state.\n *\n * const project = new TypstProject({ compiler, analyzer });\n * await project.setMany({ \"/main.typ\": \"...\", \"/utils.typ\": \"...\" });\n * const result = await project.compile();\n */\nexport type CompileListener = (result: CompileResult) => void;\n\nfunction errorAsCompileResult(\n err: unknown,\n paths: readonly string[],\n): CompileResult {\n const message = err instanceof Error ? err.message : String(err);\n return {\n diagnostics: paths.map((path) => ({\n package: \"\",\n path,\n severity: \"Error\",\n range: { startLine: 0, startCol: 0, endLine: 0, endCol: 1 },\n message,\n })),\n };\n}\n\nexport class TypstProject {\n private readonly compiler: TypstCompiler;\n private readonly analyzer?: TypstAnalyzer;\n private readonly analyzerUriRoot: string;\n /**\n * Tracked text files: path → latest content observed. Presence in this map\n * is the source of truth for \"is this a tracked text file?\"; insertion\n * order drives the `files` getter. Per-sink dedup lives in the compiler and\n * analyzer.\n */\n private readonly contentByPath = new Map<Path, string>();\n private readonly compileListeners = new Set<CompileListener>();\n private readonly scheduler: CompileScheduler;\n private compileVersion = 0;\n private _lastResult: CompileResult | undefined;\n private _entry: Path;\n private destroyed = false;\n\n private invokeListener(\n listener: CompileListener,\n result: CompileResult,\n ): void {\n try {\n listener(result);\n } catch (err) {\n console.error(\"[typst] compile listener threw:\", err);\n }\n }\n\n constructor(options: TypstProjectOptions) {\n this.compiler = options.compiler;\n this.analyzer = options.analyzer;\n this.analyzerUriRoot = normalizeRoot(\n options.analyzerUriRoot ?? DEFAULT_ROOT,\n );\n this._entry = normalizePath(options.entry ?? DEFAULT_ENTRY);\n this.scheduler = new CompileScheduler({\n debounceMs: options.autoCompile?.debounceMs,\n maxWaitMs: options.autoCompile?.maxWaitMs,\n });\n }\n\n /**\n * Schedule an auto-compile after VFS mutations. Coalesces rapid calls via\n * the configured debounce/throttle. Errors surface through `onCompile`\n * listeners via a synthetic diagnostic; callers awaiting a specific compile\n * should call `compile()` directly.\n */\n private scheduleCompile(): void {\n if (this.destroyed) return;\n this.scheduler.schedule(() => {\n this.compile().catch((err) => console.error(\"[typst]\", err));\n });\n }\n\n /** Current entry file path. Assign to change the sticky entry used by subsequent `compile()` calls. */\n get entry(): Path {\n return this._entry;\n }\n\n set entry(path: Path) {\n const next = normalizePath(path);\n if (next === this._entry) return;\n this._entry = next;\n this.scheduleCompile();\n }\n\n /** Whether an analyzer is attached. */\n get hasAnalyzer(): boolean {\n return this.analyzer !== undefined;\n }\n\n /**\n * Most recent compile result, or `undefined` before the first compile has\n * settled. Useful for lazy-mounted UI that subscribes after boot and needs\n * an initial value.\n */\n get lastResult(): CompileResult | undefined {\n return this._lastResult;\n }\n\n /**\n * Snapshot of tracked text file paths, in insertion order. Updated by\n * `setText`, `setMany`, `remove`, and `clear`. Returns a fresh array — mutate\n * freely without affecting project state.\n */\n get files(): Path[] {\n return [...this.contentByPath.keys()];\n }\n\n /**\n * Current text content for a tracked file, or `undefined` if the path was\n * never written via `setText`/`setMany` (or was removed). Read-through to the\n * project's sync cache — lets consumers avoid shadowing the VFS themselves.\n */\n getText(path: Path): string | undefined {\n return this.contentByPath.get(normalizePath(path));\n }\n\n /**\n * Add or overwrite a text file. Goes to the compiler's VFS and, when an\n * analyzer is attached, to the analyzer as a document change. No-op when\n * the tracked path already has this exact content — skips both worker RPCs\n * and the auto-scheduled compile.\n */\n async setText(path: Path, content: string): Promise<void> {\n const p = normalizePath(path);\n if (this.contentByPath.get(p) === content) return;\n await Promise.all([\n this.compiler.setText(p, content),\n this.analyzer?.didChange(\n pathToAnalyzerUri(p, this.analyzerUriRoot),\n content,\n ) ?? Promise.resolve(),\n ]);\n this.contentByPath.set(p, content);\n this.scheduleCompile();\n }\n\n /**\n * Add or overwrite a JSON file. The analyzer does not track data files, but\n * if `path` was previously tracked as text the analyzer document is closed\n * and the text entry retired so the three views stay consistent.\n */\n async setJson(path: Path, value: unknown): Promise<void> {\n const p = normalizePath(path);\n const wasText = this.contentByPath.has(p);\n await Promise.all([\n this.compiler.setJson(p, value),\n wasText\n ? this.analyzer?.didClose(pathToAnalyzerUri(p, this.analyzerUriRoot))\n : undefined,\n ]);\n this.contentByPath.delete(p);\n this.scheduleCompile();\n }\n\n /**\n * Add or overwrite a binary file. If `path` was previously tracked as text,\n * the analyzer document is closed and the text entry retired in the same\n * call so the compiler / analyzer / project views stay consistent.\n */\n async setBinary(\n path: Path,\n content: ArrayBuffer | ArrayBufferView,\n ): Promise<void> {\n const p = normalizePath(path);\n const wasText = this.contentByPath.has(p);\n await Promise.all([\n this.compiler.setBinary(p, content),\n wasText\n ? this.analyzer?.didClose(pathToAnalyzerUri(p, this.analyzerUriRoot))\n : undefined,\n ]);\n this.contentByPath.delete(p);\n this.scheduleCompile();\n }\n\n /**\n * Batch set multiple files. Strings route to both compiler and analyzer;\n * Uint8Array entries go to the compiler only. Strings matching the last\n * tracked content for their path are skipped on both sinks. Binary entries\n * always go through (no content cache, so no dedup).\n */\n async setMany(files: Record<Path, string | Uint8Array>): Promise<void> {\n const canonical = new Map<Path, string | Uint8Array>();\n for (const [path, content] of Object.entries(files)) {\n canonical.set(normalizePath(path), content);\n }\n\n const normalized: Record<Path, string | Uint8Array> = {};\n const analyzerDocs: Record<string, string> = {};\n const textUpdates: Array<[Path, string]> = [];\n const analyzerCloses: string[] = [];\n const binaryRetirements: Path[] = [];\n for (const [p, content] of canonical) {\n if (typeof content !== \"string\") {\n normalized[p] = content;\n if (this.contentByPath.has(p)) {\n analyzerCloses.push(pathToAnalyzerUri(p, this.analyzerUriRoot));\n binaryRetirements.push(p);\n }\n continue;\n }\n if (this.contentByPath.get(p) === content) continue;\n textUpdates.push([p, content]);\n normalized[p] = content;\n analyzerDocs[pathToAnalyzerUri(p, this.analyzerUriRoot)] = content;\n }\n if (Object.keys(normalized).length === 0) return;\n await Promise.all([\n this.compiler.setMany(normalized),\n this.analyzer?.didChangeMany(analyzerDocs) ?? Promise.resolve(),\n analyzerCloses.length > 0\n ? (this.analyzer?.didCloseMany(analyzerCloses) ?? Promise.resolve())\n : Promise.resolve(),\n ]);\n for (const [p, content] of textUpdates) this.contentByPath.set(p, content);\n for (const p of binaryRetirements) this.contentByPath.delete(p);\n this.scheduleCompile();\n }\n\n /**\n * Remove a file. Always removed from the compiler's VFS; also closed on the\n * analyzer when it was previously tracked as text.\n */\n async remove(path: Path): Promise<void> {\n const p = normalizePath(path);\n const wasText = this.contentByPath.has(p);\n await Promise.all([\n this.compiler.remove(p),\n wasText\n ? this.analyzer?.didClose(pathToAnalyzerUri(p, this.analyzerUriRoot))\n : undefined,\n ]);\n this.contentByPath.delete(p);\n this.scheduleCompile();\n }\n\n /** Clear all files from both compiler VFS and analyzer document set. */\n async clear(): Promise<void> {\n const uris = Array.from(this.contentByPath.keys(), (p) =>\n pathToAnalyzerUri(p, this.analyzerUriRoot),\n );\n await Promise.all([\n this.compiler.clear(),\n uris.length > 0 ? this.analyzer?.didCloseMany(uris) : undefined,\n ]);\n this.contentByPath.clear();\n this.scheduleCompile();\n }\n\n /**\n * Subscribe to compile results. Fires after every `compile()` whose result is\n * still current (stale results from out-of-order concurrent compiles are\n * dropped). If a compile has already settled, the most recent result is\n * delivered synchronously so late-mounted listeners aren't stuck blank until\n * the next compile. Returns an unsubscribe function.\n */\n onCompile(listener: CompileListener): () => void {\n this.compileListeners.add(listener);\n if (this._lastResult !== undefined) {\n this.invokeListener(listener, this._lastResult);\n }\n return () => {\n this.compileListeners.delete(listener);\n };\n }\n\n /**\n * Compile the current VFS state using the sticky entry. Errors from the\n * underlying compiler are converted into a synthetic error diagnostic so\n * callers and listeners always receive a `CompileResult`. Listeners are\n * notified only for the most recent compile — results from an earlier call\n * that resolves after a later one are suppressed.\n *\n * VFS mutations (`setText`, `remove`, etc.) auto-schedule a debounced\n * compile; call this directly only when you need an awaitable handle on the\n * result (e.g., to flush before rendering to PDF).\n */\n async compile(): Promise<CompileResult> {\n this.scheduler.cancel();\n const version = ++this.compileVersion;\n let result: CompileResult;\n try {\n result = await this.compiler.compile(this._entry);\n } catch (err) {\n // Spread the synthetic error across every tracked text path so the\n // diagnostic is visible no matter which file the user is viewing.\n // Falls back to the entry if nothing is tracked yet.\n const paths =\n this.contentByPath.size > 0\n ? [...this.contentByPath.keys()]\n : [this._entry];\n result = errorAsCompileResult(err, paths);\n }\n if (version === this.compileVersion) {\n this._lastResult = result;\n for (const listener of this.compileListeners) {\n this.invokeListener(listener, result);\n }\n }\n return result;\n }\n\n /** Compile the current VFS state to PDF using the sticky entry. */\n compilePdf(): Promise<Uint8Array> {\n return this.compiler.compilePdf(this._entry);\n }\n\n private requireAnalyzer(operation: string): TypstAnalyzer {\n if (!this.analyzer) {\n throw new Error(`TypstProject: ${operation} requires an analyzer`);\n }\n return this.analyzer;\n }\n\n /**\n * Request completion for `path` at `position`, using `source` as the\n * current document state. Pure analyzer query — neither the compiler VFS\n * nor project tracking (`files`/`getText`) is touched. Throws when no\n * analyzer is attached.\n */\n completion(\n path: Path,\n source: string,\n position: LspPosition,\n ): Promise<LspCompletionResponse> {\n const analyzer = this.requireAnalyzer(\"completion\");\n return analyzer.completion(\n pathToAnalyzerUri(normalizePath(path), this.analyzerUriRoot),\n source,\n position,\n );\n }\n\n /**\n * Request hover for `path` at `position`, using `source` as the current\n * document state. Pure analyzer query — neither the compiler VFS nor\n * project tracking is touched. Throws when no analyzer is attached.\n */\n hover(\n path: Path,\n source: string,\n position: LspPosition,\n ): Promise<LspHover | null> {\n const analyzer = this.requireAnalyzer(\"hover\");\n return analyzer.hover(\n pathToAnalyzerUri(normalizePath(path), this.analyzerUriRoot),\n source,\n position,\n );\n }\n\n /**\n * Tear down the project and the services it owns. Destroys the attached\n * compiler and analyzer, drops all listeners, and clears VFS tracking state.\n * Idempotent — calling twice is a no-op. After destruction, further calls on\n * the project are not supported; construct a new one.\n *\n * If you need to share a compiler or analyzer across projects, destroy them\n * yourself and don't call this method — the project does not provide an\n * ownership toggle.\n */\n destroy(): void {\n if (this.destroyed) return;\n this.destroyed = true;\n this.scheduler.cancel();\n this.compileListeners.clear();\n this.contentByPath.clear();\n this._lastResult = undefined;\n this.compiler.destroy();\n this.analyzer?.destroy();\n }\n}\n","import * as Comlink from \"comlink\";\nimport { createRendererWorker } from \"./rpc.js\";\nimport type { RendererWorker } from \"./renderer-worker.js\";\n\ndeclare const __TYPST_TS_RENDERER_VERSION__: string;\n\nconst DEFAULT_RENDERER_WASM_URL = `https://cdn.jsdelivr.net/npm/@myriaddreamin/typst-ts-renderer@${__TYPST_TS_RENDERER_VERSION__}/pkg/typst_ts_renderer_bg.wasm`;\n\nexport interface TypstRendererOptions {\n /**\n * Explicit Worker instance. When omitted, an inlined blob worker is created\n * automatically. Use this for Vite apps to get proper source maps:\n * `TypstRenderer.create({ worker: new Worker(new URL('typst-web-service/renderer-worker', import.meta.url)) })`\n */\n worker?: Worker;\n /** URL to the typst-ts-renderer WASM binary. Defaults to jsDelivr CDN. */\n wasmUrl?: string;\n}\n\nexport interface RenderedSvgPage {\n /** Zero-based page index within the document. */\n index: number;\n /** Page width in typographic points. */\n width: number;\n /** Page height in typographic points. */\n height: number;\n /** Standalone SVG string for just this page. */\n svg: string;\n}\n\n/**\n * Converts Typst vector artifacts to SVG strings, off the main thread.\n *\n * Wraps `@myriaddreamin/typst.ts`'s renderer hosted in a Web Worker — the\n * WASM init, vector → SVG conversion, and base64 image-embedding all happen\n * off-thread. Returned SVG strings cross via Comlink; page splitting runs on\n * the main thread (Workers don't have `DOMParser`).\n *\n * const renderer = TypstRenderer.create();\n * const svg = await renderer.renderSvg(vector);\n */\nexport class TypstRenderer {\n readonly #proxy: Comlink.Remote<RendererWorker>;\n readonly #worker: Worker;\n readonly #wasmUrl: string;\n #initPromise: Promise<void> | null = null;\n #pending: Uint8Array | null = null;\n #inflight: Promise<string> | null = null;\n\n private constructor(\n worker: Worker,\n proxy: Comlink.Remote<RendererWorker>,\n wasmUrl: string,\n ) {\n this.#worker = worker;\n this.#proxy = proxy;\n this.#wasmUrl = wasmUrl;\n // Kick off WASM fetch eagerly so it's warm by first render.\n void this.#ensureInit();\n }\n\n static create(options: TypstRendererOptions = {}): TypstRenderer {\n const worker = options.worker ?? createRendererWorker();\n const proxy = Comlink.wrap<RendererWorker>(worker);\n return new TypstRenderer(\n worker,\n proxy,\n options.wasmUrl ?? DEFAULT_RENDERER_WASM_URL,\n );\n }\n\n #ensureInit(): Promise<void> {\n if (!this.#initPromise) {\n this.#initPromise = this.#proxy\n .init(this.#wasmUrl)\n .catch((err: unknown) => {\n this.#initPromise = null;\n throw err;\n });\n }\n return this.#initPromise;\n }\n\n /** Terminate the worker. The instance is unusable afterwards. */\n destroy(): void {\n this.#proxy[Comlink.releaseProxy]();\n this.#worker.terminate();\n }\n\n /**\n * Render a Typst vector artifact to a single merged SVG string.\n *\n * Ownership of `vector.buffer` transfers to the worker (zero-copy).\n * Don't reuse the vector after passing it in — accessing its bytes from\n * the main thread after this call is undefined behavior.\n *\n * Concurrent calls are serialized in the worker: while a render is in\n * flight, the most recent `vector` becomes the next render and any\n * intermediate calls are dropped. All overlapping callers share one\n * returned promise that resolves with the LAST rendered SVG — your\n * specific vector may have been superseded.\n */\n renderSvg(vector: Uint8Array): Promise<string> {\n this.#pending = vector;\n this.#inflight ??= this.#drain();\n return this.#inflight;\n }\n\n async #drain(): Promise<string> {\n try {\n await this.#ensureInit();\n let result = \"\";\n while (this.#pending) {\n const vector = this.#pending;\n this.#pending = null;\n result = await this.#proxy.renderSvg(\n Comlink.transfer(vector, [vector.buffer as ArrayBuffer]),\n );\n }\n return result;\n } finally {\n this.#inflight = null;\n }\n }\n\n /**\n * Render a Typst vector artifact into one self-contained SVG string per\n * physical page. The merged SVG is split by `<g class=\"typst-page\">`\n * children; each group's `data-page-width` / `data-page-height` give the\n * page-local viewBox. Shared `<defs>` / `<style>` are duplicated into each\n * page so the output SVGs render independently. Returns an empty array if\n * the document has no page groups.\n */\n async renderSvgPages(vector: Uint8Array): Promise<RenderedSvgPage[]> {\n return splitMergedSvgPages(await this.renderSvg(vector));\n }\n}\n\n// Parsing must use \"text/html\", not \"image/svg+xml\": Typst's merged SVG\n// output has repeatedly failed XML-strict parsing. HTML mode tolerates it\n// and still produces real SVGSVGElement nodes for inline SVG.\nfunction splitMergedSvgPages(svg: string): RenderedSvgPage[] {\n const doc = new DOMParser().parseFromString(svg, \"text/html\");\n const root = doc.querySelector(\"svg\");\n if (!root) return [];\n\n const children = Array.from(root.children);\n const pageGroups = children.filter(\n (el) =>\n el.tagName.toLowerCase() === \"g\" && el.classList.contains(\"typst-page\"),\n );\n if (pageGroups.length === 0) return [];\n\n const sharedHtml = children\n .filter((el) => !el.classList.contains(\"typst-page\"))\n .map((el) => el.outerHTML)\n .join(\"\");\n\n const namespaceAttrs = Array.from(root.attributes)\n .filter((attr) => attr.name === \"xmlns\" || attr.name.startsWith(\"xmlns:\"))\n .map((attr) => `${attr.name}=\"${attr.value}\"`)\n .join(\" \");\n\n return pageGroups.flatMap((group, index) => {\n const width = Number(group.getAttribute(\"data-page-width\")) || 0;\n const height = Number(group.getAttribute(\"data-page-height\")) || 0;\n if (width <= 0 || height <= 0) return [];\n\n const clone = group.cloneNode(true) as Element;\n clone.removeAttribute(\"transform\");\n\n return [\n {\n index,\n width,\n height,\n svg:\n `<svg ${namespaceAttrs} viewBox=\"0 0 ${width} ${height}\" ` +\n `width=\"${width}\" height=\"${height}\">` +\n `${sharedHtml}${clone.outerHTML}</svg>`,\n },\n ];\n });\n}\n"],"mappings":";AAAA,YAAY,aAAa;;;ACMzB,SAAS,iBAAiB,MAAsB;AAC9C,QAAM,OAAO,IAAI,KAAK,CAAC,IAAI,GAAG,EA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;AACH;","names":["Comlink","Comlink"]}
|
|
1
|
+
{"version":3,"sources":["../src/analyzer.ts","../src/rpc.ts","../src/identifiers.ts","../src/compiler.ts","../src/formatter.ts","../src/compile-scheduler.ts","../src/project.ts","../src/renderer.ts"],"sourcesContent":["import * as Comlink from \"comlink\";\nimport type {\n LspCompletionResponse,\n LspHover,\n LspPosition,\n} from \"./analyzer-types.js\";\nimport type { AnalyzerWorker } from \"./analyzer-worker.js\";\nimport { createAnalyzerWorker } from \"./rpc.js\";\n\nexport interface TypstAnalyzerOptions {\n /**\n * Explicit Worker instance. When omitted, an inlined blob worker is created automatically.\n * Use this for Vite apps:\n * `await TypstAnalyzer.create({ worker: new Worker(new URL('typst-web-service/analyzer-worker', import.meta.url), { type: 'module' }) })`\n */\n worker?: Worker;\n /**\n * URL to the tinymist WASM binary.\n * Required — there is no default CDN URL for tinymist-web.\n */\n wasmUrl: string;\n}\n\n/**\n * Manages a tinymist language server in a Web Worker. Provides LSP-based\n * completion and hover for Typst documents.\n *\n * const analyzer = await TypstAnalyzer.create({ wasmUrl: '...' });\n */\nexport class TypstAnalyzer {\n private readonly proxy: Comlink.Remote<AnalyzerWorker>;\n private readonly worker: Worker;\n private versionCounter = 0;\n /**\n * Last content pushed to the worker per URI. Presence is the source of\n * truth for \"is this URI opened on the worker?\"; value drives own-RPC dedup.\n */\n private readonly content = new Map<string, string>();\n\n private constructor(worker: Worker, proxy: Comlink.Remote<AnalyzerWorker>) {\n this.worker = worker;\n this.proxy = proxy;\n }\n\n static async create(options: TypstAnalyzerOptions): Promise<TypstAnalyzer> {\n const worker = options.worker ?? createAnalyzerWorker();\n const proxy = Comlink.wrap<AnalyzerWorker>(worker);\n const absoluteWasmUrl = new URL(options.wasmUrl, globalThis.location?.href)\n .href;\n\n const analyzer = new TypstAnalyzer(worker, proxy);\n\n await proxy.init(absoluteWasmUrl);\n\n return analyzer;\n }\n\n async didOpen(uri: string, content: string): Promise<void> {\n await this.proxy.didOpen(uri, content);\n this.content.set(uri, content);\n }\n\n async didClose(uri: string): Promise<void> {\n if (!this.content.has(uri)) return;\n await this.proxy.didClose(uri);\n this.content.delete(uri);\n }\n\n /**\n * Notify the analyzer that a document has changed. Skips the RPC when the\n * content matches what the worker last saw.\n */\n async didChange(uri: string, content: string): Promise<void> {\n if (!this.content.has(uri)) {\n await this.didOpen(uri, content);\n return;\n }\n if (this.content.get(uri) === content) return;\n const version = ++this.versionCounter;\n await this.proxy.didChange(uri, version, content);\n this.content.set(uri, content);\n }\n\n /**\n * Batch document changes. Splits inputs into opens (first-time URIs) and\n * changes (already-open URIs) and sends them in a single worker roundtrip.\n * Skips unchanged documents; returns without an RPC if nothing is pending.\n */\n async didChangeMany(docs: Record<string, string>): Promise<void> {\n const opens: Array<{ uri: string; content: string }> = [];\n const changes: Array<{ uri: string; version: number; content: string }> =\n [];\n const updates: Array<[string, string]> = [];\n for (const [uri, content] of Object.entries(docs)) {\n if (!this.content.has(uri)) {\n opens.push({ uri, content });\n updates.push([uri, content]);\n } else if (this.content.get(uri) !== content) {\n changes.push({ uri, version: ++this.versionCounter, content });\n updates.push([uri, content]);\n }\n }\n if (opens.length === 0 && changes.length === 0) return;\n await this.proxy.didChangeMany(opens, changes);\n for (const [uri, content] of updates) this.content.set(uri, content);\n }\n\n /**\n * Batch document closes. Filters to currently-open URIs and sends the set\n * in a single worker roundtrip.\n */\n async didCloseMany(uris: string[]): Promise<void> {\n const toClose: string[] = [];\n for (const uri of uris) {\n if (this.content.has(uri)) toClose.push(uri);\n }\n if (toClose.length === 0) return;\n await this.proxy.didCloseMany(toClose);\n for (const uri of toClose) this.content.delete(uri);\n }\n\n /**\n * Request completion at `position` for `uri`, with `content` as the current\n * document state. Bundles the didChange notification with the request in one\n * worker roundtrip; degrades to a plain completion request when the worker\n * already has this exact content.\n */\n async completion(\n uri: string,\n content: string,\n position: LspPosition,\n ): Promise<LspCompletionResponse> {\n if (this.content.get(uri) === content) {\n return this.proxy.completion(uri, position);\n }\n const isOpen = this.content.has(uri);\n const version = ++this.versionCounter;\n const result = await this.proxy.completionWithDoc(\n uri,\n version,\n content,\n position,\n isOpen ? \"change\" : \"open\",\n );\n this.content.set(uri, content);\n return result;\n }\n\n /**\n * Request hover at `position` for `uri`, with `content` as the current\n * document state. Bundles the didChange notification with the request in one\n * worker roundtrip; degrades to a plain hover request when the worker\n * already has this exact content.\n */\n async hover(\n uri: string,\n content: string,\n position: LspPosition,\n ): Promise<LspHover | null> {\n if (this.content.get(uri) === content) {\n return this.proxy.hover(uri, position);\n }\n const isOpen = this.content.has(uri);\n const version = ++this.versionCounter;\n const result = await this.proxy.hoverWithDoc(\n uri,\n version,\n content,\n position,\n isOpen ? \"change\" : \"open\",\n );\n this.content.set(uri, content);\n return result;\n }\n\n destroy(): void {\n this.proxy[Comlink.releaseProxy]();\n this.worker.terminate();\n }\n}\n","// Injected at build time by tsup (see tsup.config.ts)\ndeclare const __WORKER_CODE__: string;\ndeclare const __ANALYZER_WORKER_CODE__: string;\ndeclare const __RENDERER_WORKER_CODE__: string;\n\n/** Create a Worker from an inlined code string, auto-revoking the blob URL on terminate. */\nfunction createBlobWorker(code: string): Worker {\n const blob = new Blob([code], { type: \"application/javascript\" });\n const url = URL.createObjectURL(blob);\n const worker = new Worker(url);\n const origTerminate = worker.terminate.bind(worker);\n worker.terminate = () => {\n origTerminate();\n URL.revokeObjectURL(url);\n };\n return worker;\n}\n\n/** Create a blob Worker from the inlined compiler worker code. */\nexport function createWorker(): Worker {\n return createBlobWorker(__WORKER_CODE__);\n}\n\n/** Create a blob Worker from the inlined analyzer worker code. */\nexport function createAnalyzerWorker(): Worker {\n return createBlobWorker(__ANALYZER_WORKER_CODE__);\n}\n\n/** Create a blob Worker from the inlined renderer worker code. */\nexport function createRendererWorker(): Worker {\n return createBlobWorker(__RENDERER_WORKER_CODE__);\n}\n","/**\n * Two addressing schemes live in this codebase. This file is the only place\n * that knows how they relate. Keeping the vocabulary and conversions colocated\n * means a new contributor can read one file and understand the model.\n *\n * 1. Path — \"/main.typ\". Always leading-slash, always forward slashes.\n * Used by the compiler VFS, the `TypstProject` public API,\n * and the `typstFilePath` facet. Addresses a file within\n * the project.\n *\n * 2. AnalyzerUri — \"untitled:project/main.typ\". What tinymist's LSP expects.\n * Derived from a Path plus the analyzer URI root.\n *\n * The types below are type aliases, not branded/opaque types. That's\n * deliberate: callers can pass string literals where a Path is expected\n * without wrapping, and the aliases only serve as self-documenting\n * signatures. Ingress points still need to call `normalizePath` to defend\n * against un-normalized input — the alias does not imply the string has\n * been normalized.\n */\n\n/** `/path/to/file.typ` — leading-slash, forward slashes only. */\nexport type Path = string;\n\n/** `untitled:project/path/to/file.typ` — what tinymist's LSP consumes. */\nexport type AnalyzerUri = string;\n\n/** Ensure a path starts with a leading slash. Idempotent. */\nexport function normalizePath(path: string): Path {\n return path.startsWith(\"/\") ? path : `/${path}`;\n}\n\n/**\n * Normalize an analyzer URI root. Ensures leading slash, strips trailing\n * slashes. Special-cases \"/\" → \"\" so URIs don't end up with a leading\n * `untitled://`.\n */\nexport function normalizeRoot(rootPath: string): string {\n const root = normalizePath(rootPath);\n return root === \"/\" ? \"\" : root.replace(/\\/+$/, \"\");\n}\n\n/**\n * Build the analyzer URI for a given project path. `root` is expected to\n * already be normalized (see `normalizeRoot`).\n *\n * pathToAnalyzerUri(\"/main.typ\", \"/project\") -> \"untitled:project/main.typ\"\n */\nexport function pathToAnalyzerUri(path: Path, root: string): AnalyzerUri {\n const bare = root.replace(/^\\//, \"\");\n return `untitled:${bare}${normalizePath(path)}`;\n}\n","import * as Comlink from \"comlink\";\nimport { createWorker } from \"./rpc.js\";\nimport type { DiagnosticMessage } from \"./types.js\";\nimport type { CompilerWorker } from \"./compiler-worker.js\";\n\ndeclare const __TYPST_TS_WEB_COMPILER_VERSION__: string;\n\nexport interface CompileResult {\n diagnostics: DiagnosticMessage[];\n /** Vector artifact bytes from the compiler, usable with TypstRenderer for SVG rendering. */\n vector?: Uint8Array;\n}\n\nexport interface TypstCompilerOptions {\n /**\n * Explicit Worker instance. When omitted, an inlined blob worker is created automatically.\n * Use this for Vite apps to get proper source maps:\n * `await TypstCompiler.create({ worker: new Worker(new URL('typst-web-service/compiler-worker', import.meta.url)) })`\n */\n worker?: Worker;\n /**\n * URL to the typst-ts-web-compiler WASM binary.\n * Defaults to the matching version on jsDelivr CDN.\n * Override with a local asset URL for offline support or faster load:\n * `new URL('@myriaddreamin/typst-ts-web-compiler/pkg/typst_ts_web_compiler_bg.wasm', import.meta.url).href`\n */\n wasmUrl?: string;\n /** Font URLs to load into the Typst compiler. Defaults to Roboto from jsDelivr. */\n fonts?: string[];\n /**\n * Enable fetching @preview/ packages from packages.typst.org on demand.\n * Default: true.\n */\n packages?: boolean;\n}\n\nconst DEFAULT_FONTS = [\n \"https://cdn.jsdelivr.net/npm/roboto-font@0.1.0/fonts/Roboto/roboto-regular-webfont.ttf\",\n];\n\nconst defaultWasmUrl = () =>\n `https://cdn.jsdelivr.net/npm/@myriaddreamin/typst-ts-web-compiler@${__TYPST_TS_WEB_COMPILER_VERSION__}/pkg/typst_ts_web_compiler_bg.wasm`;\n\n/**\n * Manages a Typst compiler worker. Create one instance and share it across\n * all extensions (linter, autocomplete, preview, etc.).\n *\n * await TypstCompiler.create() // blob worker, defaults\n * await TypstCompiler.create({ wasmUrl: '...' }) // blob worker, custom WASM\n * await TypstCompiler.create({ worker: myWorker }) // explicit Worker (Vite)\n * await TypstCompiler.create({ worker: myWorker, fonts: [...] }) // explicit Worker + options\n */\nexport class TypstCompiler {\n private readonly proxy: Comlink.Remote<CompilerWorker>;\n private readonly worker: Worker;\n private readonly encoder = new TextEncoder();\n /** Last text content pushed per path. Drives own-RPC dedup. Invalidated by binary writes. */\n private readonly content = new Map<string, string>();\n\n private constructor(worker: Worker, proxy: Comlink.Remote<CompilerWorker>) {\n this.worker = worker;\n this.proxy = proxy;\n }\n\n static async create(\n options: TypstCompilerOptions = {},\n ): Promise<TypstCompiler> {\n const worker = options.worker ?? createWorker();\n const proxy = Comlink.wrap<CompilerWorker>(worker);\n\n await proxy.init(\n options.wasmUrl ?? defaultWasmUrl(),\n options.fonts ?? DEFAULT_FONTS,\n options.packages ?? true,\n );\n\n return new TypstCompiler(worker, proxy);\n }\n\n /**\n * Compile whatever is currently in the VFS (populated via\n * setText/setBinary/setJson/setMany). Defaults to compiling \"/main.typ\";\n * override with `entry`.\n */\n compile(entry?: string): Promise<CompileResult> {\n return this.proxy.compile(entry);\n }\n\n /**\n * Compile to PDF. Operates on whatever is currently in the VFS (populated\n * via setText/setBinary/setJson/setMany). Defaults to compiling \"/main.typ\";\n * override with `entry`.\n */\n compilePdf(entry?: string): Promise<Uint8Array> {\n return this.proxy.compilePdf(entry);\n }\n\n /**\n * Add or overwrite a text file in the virtual compiler filesystem. Skips\n * the worker RPC when `source` matches the last value pushed for `path`.\n */\n async setText(path: string, source: string): Promise<void> {\n if (this.content.get(path) === source) return;\n await this.proxy.mapShadow(path, this.encoder.encode(source));\n this.content.set(path, source);\n }\n\n /** Add or overwrite a JSON file in the virtual compiler filesystem. */\n setJson(\n path: string,\n value: unknown,\n replacer?: (this: unknown, key: string, value: unknown) => unknown,\n space?: string | number,\n ): Promise<void> {\n return this.setText(path, JSON.stringify(value, replacer, space));\n }\n\n /**\n * Add or overwrite multiple files in the virtual compiler filesystem in a\n * single worker roundtrip. Strings are UTF-8 encoded; Uint8Arrays are\n * passed through. Text entries unchanged since their last push are skipped;\n * binary entries always push and invalidate the text cache for their path.\n */\n async setMany(files: Record<string, string | Uint8Array>): Promise<void> {\n const encoded: Record<string, Uint8Array> = {};\n const textUpdates: Array<[string, string]> = [];\n const binaryInvalidations: string[] = [];\n for (const [path, content] of Object.entries(files)) {\n if (typeof content === \"string\") {\n if (this.content.get(path) === content) continue;\n textUpdates.push([path, content]);\n encoded[path] = this.encoder.encode(content);\n } else {\n binaryInvalidations.push(path);\n encoded[path] = content;\n }\n }\n if (Object.keys(encoded).length === 0) return;\n await this.proxy.mapShadowMany(encoded);\n for (const [path, content] of textUpdates) this.content.set(path, content);\n for (const path of binaryInvalidations) this.content.delete(path);\n }\n\n /** Add or overwrite a binary file in the virtual compiler filesystem. */\n async setBinary(\n path: string,\n content: ArrayBuffer | ArrayBufferView,\n ): Promise<void> {\n const bytes =\n content instanceof ArrayBuffer\n ? new Uint8Array(content)\n : new Uint8Array(\n content.buffer,\n content.byteOffset,\n content.byteLength,\n );\n await this.proxy.mapShadow(path, bytes);\n this.content.delete(path);\n }\n\n /** Remove a file from the virtual compiler filesystem. */\n async remove(path: string): Promise<void> {\n await this.proxy.unmapShadow(path);\n this.content.delete(path);\n }\n\n /** Clear all virtual files from the compiler filesystem. */\n async clear(): Promise<void> {\n await this.proxy.resetShadow();\n this.content.clear();\n }\n\n destroy(): void {\n this.proxy[Comlink.releaseProxy]();\n this.worker.terminate();\n }\n}\n","export interface FormatConfig {\n /** Number of spaces per indentation level. Default: 2 */\n tab_spaces?: number;\n /** Maximum line width. Default: 80 */\n max_width?: number;\n /** Maximum consecutive blank lines allowed. */\n blank_lines_upper_bound?: number;\n /** Collapse consecutive whitespace in markup to a single space. */\n collapse_markup_spaces?: boolean;\n /** Sort import items alphabetically. */\n reorder_import_items?: boolean;\n /** Wrap text in markup to fit within max_width. Implies collapse_markup_spaces. */\n wrap_text?: boolean;\n}\n\nexport interface FormatRangeResult {\n /** Start index (UTF-16) of the actual formatted range. */\n start: number;\n /** End index (UTF-16) of the actual formatted range. */\n end: number;\n /** The formatted text for the range. */\n text: string;\n}\n\ntype TypstyleModule = typeof import(\"@typstyle/typstyle-wasm-bundler\");\n\nlet typstylePromise: Promise<TypstyleModule> | null = null;\n\nfunction getTypstyle(): Promise<TypstyleModule> {\n if (!typstylePromise) {\n typstylePromise = import(\"@typstyle/typstyle-wasm-bundler\").catch((err) => {\n typstylePromise = null;\n throw err;\n });\n }\n return typstylePromise;\n}\n\n/**\n * Typst code formatter powered by typstyle.\n *\n * Runs on the main thread — typstyle is lightweight and fast.\n * The WASM module is loaded lazily on first format call.\n * Requires a bundler that supports WASM imports (e.g. Vite, webpack).\n *\n * const formatter = TypstFormatter.create({ tab_spaces: 2, max_width: 80 });\n * const formatted = await formatter.format(source);\n */\nexport class TypstFormatter {\n private config: FormatConfig;\n\n private constructor(config: FormatConfig = {}) {\n this.config = config;\n // Eagerly start loading WASM so it's ready by first use.\n // Swallow preload errors — they'll surface on first format() call.\n getTypstyle().catch(() => {});\n }\n\n static create(config: FormatConfig = {}): TypstFormatter {\n return new TypstFormatter(config);\n }\n\n /** Format an entire Typst source string. */\n async format(source: string): Promise<string> {\n const typstyle = await getTypstyle();\n return typstyle.format(source, this.config);\n }\n\n /** Format a range within a Typst source string. Indices are UTF-16 code units. */\n async formatRange(\n source: string,\n start: number,\n end: number,\n ): Promise<FormatRangeResult> {\n const typstyle = await getTypstyle();\n const result = typstyle.format_range(source, start, end, this.config);\n return { start: result.start, end: result.end, text: result.text };\n }\n}\n","interface CompileSchedulerOptions {\n /** Minimum idle time (ms) after the last request before firing. Default: 0. */\n debounceMs?: number;\n /**\n * Maximum time (ms) the debounce may keep deferring during continuous\n * requests. Guarantees a fire at least this often so users see progress\n * while typing. Default: 0 (no cap).\n */\n maxWaitMs?: number;\n}\n\n/**\n * Debounce helper with a max-wait ceiling for coalescing compile requests. A\n * burst of `schedule(cb)` calls within `debounceMs` collapses into one fire;\n * during sustained bursts, `maxWaitMs` caps how long the debounce may keep\n * deferring.\n */\nexport class CompileScheduler {\n private debounceTimer: ReturnType<typeof setTimeout> | null = null;\n private maxWaitTimer: ReturnType<typeof setTimeout> | null = null;\n\n constructor(private readonly options: CompileSchedulerOptions = {}) {}\n\n schedule(callback: () => void): void {\n if (this.debounceTimer) {\n clearTimeout(this.debounceTimer);\n this.debounceTimer = null;\n }\n\n const delay = Math.max(0, this.options.debounceMs ?? 0);\n this.debounceTimer = setTimeout(() => {\n this.debounceTimer = null;\n this.clearMaxWait();\n callback();\n }, delay);\n\n const maxWait = this.options.maxWaitMs;\n if (maxWait != null && maxWait > 0 && !this.maxWaitTimer) {\n this.maxWaitTimer = setTimeout(() => {\n this.maxWaitTimer = null;\n if (this.debounceTimer) {\n clearTimeout(this.debounceTimer);\n this.debounceTimer = null;\n callback();\n }\n }, maxWait);\n }\n }\n\n /** Cancel any pending scheduled fire without calling the callback. */\n cancel(): void {\n if (this.debounceTimer) {\n clearTimeout(this.debounceTimer);\n this.debounceTimer = null;\n }\n this.clearMaxWait();\n }\n\n private clearMaxWait(): void {\n if (this.maxWaitTimer) {\n clearTimeout(this.maxWaitTimer);\n this.maxWaitTimer = null;\n }\n }\n}\n","import type { TypstAnalyzer } from \"./analyzer.js\";\nimport type {\n LspCompletionResponse,\n LspHover,\n LspPosition,\n} from \"./analyzer-types.js\";\nimport { CompileScheduler } from \"./compile-scheduler.js\";\nimport type { CompileResult, TypstCompiler } from \"./compiler.js\";\nimport {\n normalizePath,\n normalizeRoot,\n type Path,\n pathToAnalyzerUri,\n} from \"./identifiers.js\";\n\nexport interface TypstProjectOptions {\n compiler: TypstCompiler;\n /**\n * Optional analyzer. When provided, text file operations also sync with the\n * analyzer so completions / hover reflect the current state.\n */\n analyzer?: TypstAnalyzer;\n /** Default entry file path. Default: \"/main.typ\". */\n entry?: string;\n /**\n * Prefix used to build the `untitled:` URIs handed to the analyzer.\n * Default: \"/project\". A path of `/main.typ` becomes\n * `untitled:project/main.typ`. Only affects URI construction — the compiler\n * and project VFS use the raw paths unchanged.\n */\n analyzerUriRoot?: string;\n /**\n * Scheduling for auto-compiles after VFS mutations. Mutations debounce by\n * `debounceMs`; `maxWaitMs` caps how long the debounce can keep deferring\n * during sustained edits so the user still sees progress.\n */\n autoCompile?: AutoCompileOptions;\n}\n\nexport interface AutoCompileOptions {\n /**\n * Idle time (ms) after the last VFS mutation before a compile fires.\n * Default: 0 — compile fires on the next macrotask. Set higher (e.g. 150) to\n * coalesce rapid edits.\n */\n debounceMs?: number;\n /**\n * Maximum time (ms) the debounce is allowed to defer a compile during\n * sustained mutation bursts. Default: 0 (no cap — pure debounce).\n */\n maxWaitMs?: number;\n}\n\nconst DEFAULT_ENTRY = \"/main.typ\";\nconst DEFAULT_ROOT = \"/project\";\n\n/**\n * Coordinates a compiler + analyzer pair for multi-file Typst projects.\n *\n * Owns the project's virtual filesystem state. Editors push incremental\n * `setText` updates as the user types; the project mirrors those edits to\n * both the compiler's shadow VFS and the analyzer's open-document set, then\n * compiles or services LSP requests against the current state.\n *\n * const project = new TypstProject({ compiler, analyzer });\n * await project.setMany({ \"/main.typ\": \"...\", \"/utils.typ\": \"...\" });\n * const result = await project.compile();\n */\nexport type CompileListener = (result: CompileResult) => void;\n\nfunction errorAsCompileResult(\n err: unknown,\n paths: readonly string[],\n): CompileResult {\n const message = err instanceof Error ? err.message : String(err);\n return {\n diagnostics: paths.map((path) => ({\n package: \"\",\n path,\n severity: \"Error\",\n range: { startLine: 0, startCol: 0, endLine: 0, endCol: 1 },\n message,\n })),\n };\n}\n\nexport class TypstProject {\n private readonly compiler: TypstCompiler;\n private readonly analyzer?: TypstAnalyzer;\n private readonly analyzerUriRoot: string;\n /**\n * Tracked text files: path → latest content observed. Presence in this map\n * is the source of truth for \"is this a tracked text file?\"; insertion\n * order drives the `files` getter. Per-sink dedup lives in the compiler and\n * analyzer.\n */\n private readonly contentByPath = new Map<Path, string>();\n private readonly compileListeners = new Set<CompileListener>();\n private readonly scheduler: CompileScheduler;\n private compileVersion = 0;\n private _lastResult: CompileResult | undefined;\n private _entry: Path;\n private destroyed = false;\n\n private invokeListener(\n listener: CompileListener,\n result: CompileResult,\n ): void {\n try {\n listener(result);\n } catch (err) {\n console.error(\"[typst] compile listener threw:\", err);\n }\n }\n\n constructor(options: TypstProjectOptions) {\n this.compiler = options.compiler;\n this.analyzer = options.analyzer;\n this.analyzerUriRoot = normalizeRoot(\n options.analyzerUriRoot ?? DEFAULT_ROOT,\n );\n this._entry = normalizePath(options.entry ?? DEFAULT_ENTRY);\n this.scheduler = new CompileScheduler({\n debounceMs: options.autoCompile?.debounceMs,\n maxWaitMs: options.autoCompile?.maxWaitMs,\n });\n }\n\n /**\n * Schedule an auto-compile after VFS mutations. Coalesces rapid calls via\n * the configured debounce/throttle. Errors surface through `onCompile`\n * listeners via a synthetic diagnostic; callers awaiting a specific compile\n * should call `compile()` directly.\n */\n private scheduleCompile(): void {\n if (this.destroyed) return;\n this.scheduler.schedule(() => {\n this.compile().catch((err) => console.error(\"[typst]\", err));\n });\n }\n\n /** Current entry file path. Assign to change the sticky entry used by subsequent `compile()` calls. */\n get entry(): Path {\n return this._entry;\n }\n\n set entry(path: Path) {\n const next = normalizePath(path);\n if (next === this._entry) return;\n this._entry = next;\n this.scheduleCompile();\n }\n\n /** Whether an analyzer is attached. */\n get hasAnalyzer(): boolean {\n return this.analyzer !== undefined;\n }\n\n /**\n * Most recent compile result, or `undefined` before the first compile has\n * settled. Useful for lazy-mounted UI that subscribes after boot and needs\n * an initial value.\n */\n get lastResult(): CompileResult | undefined {\n return this._lastResult;\n }\n\n /**\n * Snapshot of tracked text file paths, in insertion order. Updated by\n * `setText`, `setMany`, `remove`, and `clear`. Returns a fresh array — mutate\n * freely without affecting project state.\n */\n get files(): Path[] {\n return [...this.contentByPath.keys()];\n }\n\n /**\n * Current text content for a tracked file, or `undefined` if the path was\n * never written via `setText`/`setMany` (or was removed). Read-through to the\n * project's sync cache — lets consumers avoid shadowing the VFS themselves.\n */\n getText(path: Path): string | undefined {\n return this.contentByPath.get(normalizePath(path));\n }\n\n /**\n * Add or overwrite a text file. Goes to the compiler's VFS and, when an\n * analyzer is attached, to the analyzer as a document change. No-op when\n * the tracked path already has this exact content — skips both worker RPCs\n * and the auto-scheduled compile.\n */\n async setText(path: Path, content: string): Promise<void> {\n const p = normalizePath(path);\n if (this.contentByPath.get(p) === content) return;\n await Promise.all([\n this.compiler.setText(p, content),\n this.analyzer?.didChange(\n pathToAnalyzerUri(p, this.analyzerUriRoot),\n content,\n ) ?? Promise.resolve(),\n ]);\n this.contentByPath.set(p, content);\n this.scheduleCompile();\n }\n\n /**\n * Add or overwrite a JSON file. The analyzer does not track data files, but\n * if `path` was previously tracked as text the analyzer document is closed\n * and the text entry retired so the three views stay consistent.\n */\n async setJson(path: Path, value: unknown): Promise<void> {\n const p = normalizePath(path);\n const wasText = this.contentByPath.has(p);\n await Promise.all([\n this.compiler.setJson(p, value),\n wasText\n ? this.analyzer?.didClose(pathToAnalyzerUri(p, this.analyzerUriRoot))\n : undefined,\n ]);\n this.contentByPath.delete(p);\n this.scheduleCompile();\n }\n\n /**\n * Add or overwrite a binary file. If `path` was previously tracked as text,\n * the analyzer document is closed and the text entry retired in the same\n * call so the compiler / analyzer / project views stay consistent.\n */\n async setBinary(\n path: Path,\n content: ArrayBuffer | ArrayBufferView,\n ): Promise<void> {\n const p = normalizePath(path);\n const wasText = this.contentByPath.has(p);\n await Promise.all([\n this.compiler.setBinary(p, content),\n wasText\n ? this.analyzer?.didClose(pathToAnalyzerUri(p, this.analyzerUriRoot))\n : undefined,\n ]);\n this.contentByPath.delete(p);\n this.scheduleCompile();\n }\n\n /**\n * Batch set multiple files. Strings route to both compiler and analyzer;\n * Uint8Array entries go to the compiler only. Strings matching the last\n * tracked content for their path are skipped on both sinks. Binary entries\n * always go through (no content cache, so no dedup).\n */\n async setMany(files: Record<Path, string | Uint8Array>): Promise<void> {\n const canonical = new Map<Path, string | Uint8Array>();\n for (const [path, content] of Object.entries(files)) {\n canonical.set(normalizePath(path), content);\n }\n\n const normalized: Record<Path, string | Uint8Array> = {};\n const analyzerDocs: Record<string, string> = {};\n const textUpdates: Array<[Path, string]> = [];\n const analyzerCloses: string[] = [];\n const binaryRetirements: Path[] = [];\n for (const [p, content] of canonical) {\n if (typeof content !== \"string\") {\n normalized[p] = content;\n if (this.contentByPath.has(p)) {\n analyzerCloses.push(pathToAnalyzerUri(p, this.analyzerUriRoot));\n binaryRetirements.push(p);\n }\n continue;\n }\n if (this.contentByPath.get(p) === content) continue;\n textUpdates.push([p, content]);\n normalized[p] = content;\n analyzerDocs[pathToAnalyzerUri(p, this.analyzerUriRoot)] = content;\n }\n if (Object.keys(normalized).length === 0) return;\n await Promise.all([\n this.compiler.setMany(normalized),\n this.analyzer?.didChangeMany(analyzerDocs) ?? Promise.resolve(),\n analyzerCloses.length > 0\n ? (this.analyzer?.didCloseMany(analyzerCloses) ?? Promise.resolve())\n : Promise.resolve(),\n ]);\n for (const [p, content] of textUpdates) this.contentByPath.set(p, content);\n for (const p of binaryRetirements) this.contentByPath.delete(p);\n this.scheduleCompile();\n }\n\n /**\n * Remove a file. Always removed from the compiler's VFS; also closed on the\n * analyzer when it was previously tracked as text.\n */\n async remove(path: Path): Promise<void> {\n const p = normalizePath(path);\n const wasText = this.contentByPath.has(p);\n await Promise.all([\n this.compiler.remove(p),\n wasText\n ? this.analyzer?.didClose(pathToAnalyzerUri(p, this.analyzerUriRoot))\n : undefined,\n ]);\n this.contentByPath.delete(p);\n this.scheduleCompile();\n }\n\n /** Clear all files from both compiler VFS and analyzer document set. */\n async clear(): Promise<void> {\n const uris = Array.from(this.contentByPath.keys(), (p) =>\n pathToAnalyzerUri(p, this.analyzerUriRoot),\n );\n await Promise.all([\n this.compiler.clear(),\n uris.length > 0 ? this.analyzer?.didCloseMany(uris) : undefined,\n ]);\n this.contentByPath.clear();\n this.scheduleCompile();\n }\n\n /**\n * Subscribe to compile results. Fires after every `compile()` whose result is\n * still current (stale results from out-of-order concurrent compiles are\n * dropped). If a compile has already settled, the most recent result is\n * delivered synchronously so late-mounted listeners aren't stuck blank until\n * the next compile. Returns an unsubscribe function.\n */\n onCompile(listener: CompileListener): () => void {\n this.compileListeners.add(listener);\n if (this._lastResult !== undefined) {\n this.invokeListener(listener, this._lastResult);\n }\n return () => {\n this.compileListeners.delete(listener);\n };\n }\n\n /**\n * Compile the current VFS state using the sticky entry. Errors from the\n * underlying compiler are converted into a synthetic error diagnostic so\n * callers and listeners always receive a `CompileResult`. Listeners are\n * notified only for the most recent compile — results from an earlier call\n * that resolves after a later one are suppressed.\n *\n * VFS mutations (`setText`, `remove`, etc.) auto-schedule a debounced\n * compile; call this directly only when you need an awaitable handle on the\n * result (e.g., to flush before rendering to PDF).\n */\n async compile(): Promise<CompileResult> {\n this.scheduler.cancel();\n const version = ++this.compileVersion;\n let result: CompileResult;\n try {\n result = await this.compiler.compile(this._entry);\n } catch (err) {\n // Spread the synthetic error across every tracked text path so the\n // diagnostic is visible no matter which file the user is viewing.\n // Falls back to the entry if nothing is tracked yet.\n const paths =\n this.contentByPath.size > 0\n ? [...this.contentByPath.keys()]\n : [this._entry];\n result = errorAsCompileResult(err, paths);\n }\n if (version === this.compileVersion) {\n this._lastResult = result;\n for (const listener of this.compileListeners) {\n this.invokeListener(listener, result);\n }\n }\n return result;\n }\n\n /** Compile the current VFS state to PDF using the sticky entry. */\n compilePdf(): Promise<Uint8Array> {\n return this.compiler.compilePdf(this._entry);\n }\n\n private requireAnalyzer(operation: string): TypstAnalyzer {\n if (!this.analyzer) {\n throw new Error(`TypstProject: ${operation} requires an analyzer`);\n }\n return this.analyzer;\n }\n\n /**\n * Request completion for `path` at `position`, using `source` as the\n * current document state. Pure analyzer query — neither the compiler VFS\n * nor project tracking (`files`/`getText`) is touched. Throws when no\n * analyzer is attached.\n */\n completion(\n path: Path,\n source: string,\n position: LspPosition,\n ): Promise<LspCompletionResponse> {\n const analyzer = this.requireAnalyzer(\"completion\");\n return analyzer.completion(\n pathToAnalyzerUri(normalizePath(path), this.analyzerUriRoot),\n source,\n position,\n );\n }\n\n /**\n * Request hover for `path` at `position`, using `source` as the current\n * document state. Pure analyzer query — neither the compiler VFS nor\n * project tracking is touched. Throws when no analyzer is attached.\n */\n hover(\n path: Path,\n source: string,\n position: LspPosition,\n ): Promise<LspHover | null> {\n const analyzer = this.requireAnalyzer(\"hover\");\n return analyzer.hover(\n pathToAnalyzerUri(normalizePath(path), this.analyzerUriRoot),\n source,\n position,\n );\n }\n\n /**\n * Tear down the project and the services it owns. Destroys the attached\n * compiler and analyzer, drops all listeners, and clears VFS tracking state.\n * Idempotent — calling twice is a no-op. After destruction, further calls on\n * the project are not supported; construct a new one.\n *\n * If you need to share a compiler or analyzer across projects, destroy them\n * yourself and don't call this method — the project does not provide an\n * ownership toggle.\n */\n destroy(): void {\n if (this.destroyed) return;\n this.destroyed = true;\n this.scheduler.cancel();\n this.compileListeners.clear();\n this.contentByPath.clear();\n this._lastResult = undefined;\n this.compiler.destroy();\n this.analyzer?.destroy();\n }\n}\n","import * as Comlink from \"comlink\";\nimport { createRendererWorker } from \"./rpc.js\";\nimport type { RendererWorker } from \"./renderer-worker.js\";\n\ndeclare const __TYPST_TS_RENDERER_VERSION__: string;\n\nconst DEFAULT_RENDERER_WASM_URL = `https://cdn.jsdelivr.net/npm/@myriaddreamin/typst-ts-renderer@${__TYPST_TS_RENDERER_VERSION__}/pkg/typst_ts_renderer_bg.wasm`;\n\nexport interface TypstRendererOptions {\n /**\n * Explicit Worker instance. When omitted, an inlined blob worker is created\n * automatically. Use this for Vite apps to get proper source maps:\n * `TypstRenderer.create({ worker: new Worker(new URL('typst-web-service/renderer-worker', import.meta.url)) })`\n */\n worker?: Worker;\n /** URL to the typst-ts-renderer WASM binary. Defaults to jsDelivr CDN. */\n wasmUrl?: string;\n}\n\nexport interface RenderedSvgPage {\n /** Zero-based page index within the document. */\n index: number;\n /** Page width in typographic points. */\n width: number;\n /** Page height in typographic points. */\n height: number;\n /** Standalone SVG string for just this page. */\n svg: string;\n}\n\n/**\n * Converts Typst vector artifacts to SVG strings, off the main thread.\n *\n * Wraps `@myriaddreamin/typst.ts`'s renderer hosted in a Web Worker — the\n * WASM init, vector → SVG conversion, and base64 image-embedding all happen\n * off-thread. Returned SVG strings cross via Comlink; page splitting runs on\n * the main thread (Workers don't have `DOMParser`).\n *\n * const renderer = TypstRenderer.create();\n * const svg = await renderer.renderSvg(vector);\n */\nexport class TypstRenderer {\n readonly #proxy: Comlink.Remote<RendererWorker>;\n readonly #worker: Worker;\n readonly #wasmUrl: string;\n #initPromise: Promise<void> | null = null;\n #pending: Uint8Array | null = null;\n #inflight: Promise<string> | null = null;\n\n private constructor(\n worker: Worker,\n proxy: Comlink.Remote<RendererWorker>,\n wasmUrl: string,\n ) {\n this.#worker = worker;\n this.#proxy = proxy;\n this.#wasmUrl = wasmUrl;\n // Kick off WASM fetch eagerly so it's warm by first render.\n void this.#ensureInit();\n }\n\n static create(options: TypstRendererOptions = {}): TypstRenderer {\n const worker = options.worker ?? createRendererWorker();\n const proxy = Comlink.wrap<RendererWorker>(worker);\n return new TypstRenderer(\n worker,\n proxy,\n options.wasmUrl ?? DEFAULT_RENDERER_WASM_URL,\n );\n }\n\n #ensureInit(): Promise<void> {\n if (!this.#initPromise) {\n this.#initPromise = this.#proxy\n .init(this.#wasmUrl)\n .catch((err: unknown) => {\n this.#initPromise = null;\n throw err;\n });\n }\n return this.#initPromise;\n }\n\n /** Terminate the worker. The instance is unusable afterwards. */\n destroy(): void {\n this.#proxy[Comlink.releaseProxy]();\n this.#worker.terminate();\n }\n\n /**\n * Render a Typst vector artifact to a single merged SVG string.\n *\n * Ownership of `vector.buffer` transfers to the worker (zero-copy).\n * Don't reuse the vector after passing it in — accessing its bytes from\n * the main thread after this call is undefined behavior.\n *\n * Concurrent calls are serialized in the worker: while a render is in\n * flight, the most recent `vector` becomes the next render and any\n * intermediate calls are dropped. All overlapping callers share one\n * returned promise that resolves with the LAST rendered SVG — your\n * specific vector may have been superseded.\n */\n renderSvg(vector: Uint8Array): Promise<string> {\n this.#pending = vector;\n this.#inflight ??= this.#drain();\n return this.#inflight;\n }\n\n async #drain(): Promise<string> {\n try {\n await this.#ensureInit();\n let result = \"\";\n while (this.#pending) {\n const vector = this.#pending;\n this.#pending = null;\n result = await this.#proxy.renderSvg(\n Comlink.transfer(vector, [vector.buffer as ArrayBuffer]),\n );\n }\n return result;\n } finally {\n this.#inflight = null;\n }\n }\n\n /**\n * Render a Typst vector artifact into one self-contained SVG string per\n * physical page. The merged SVG is split by `<g class=\"typst-page\">`\n * children; each group's `data-page-width` / `data-page-height` give the\n * page-local viewBox. Shared `<defs>` / `<style>` are duplicated into each\n * page so the output SVGs render independently. Returns an empty array if\n * the document has no page groups.\n */\n async renderSvgPages(vector: Uint8Array): Promise<RenderedSvgPage[]> {\n return splitMergedSvgPages(await this.renderSvg(vector));\n }\n}\n\n// Parsing must use \"text/html\", not \"image/svg+xml\": Typst's merged SVG\n// output has repeatedly failed XML-strict parsing. HTML mode tolerates it\n// and still produces real SVGSVGElement nodes for inline SVG.\nfunction splitMergedSvgPages(svg: string): RenderedSvgPage[] {\n const doc = new DOMParser().parseFromString(svg, \"text/html\");\n const root = doc.querySelector(\"svg\");\n if (!root) return [];\n\n const children = Array.from(root.children);\n const pageGroups = children.filter(\n (el) =>\n el.tagName.toLowerCase() === \"g\" && el.classList.contains(\"typst-page\"),\n );\n if (pageGroups.length === 0) return [];\n\n const sharedHtml = children\n .filter((el) => !el.classList.contains(\"typst-page\"))\n .map((el) => el.outerHTML)\n .join(\"\");\n\n const namespaceAttrs = Array.from(root.attributes)\n .filter((attr) => attr.name === \"xmlns\" || attr.name.startsWith(\"xmlns:\"))\n .map((attr) => `${attr.name}=\"${attr.value}\"`)\n .join(\" \");\n\n return pageGroups.flatMap((group, index) => {\n const width = Number(group.getAttribute(\"data-page-width\")) || 0;\n const height = Number(group.getAttribute(\"data-page-height\")) || 0;\n if (width <= 0 || height <= 0) return [];\n\n const clone = group.cloneNode(true) as Element;\n clone.removeAttribute(\"transform\");\n\n return [\n {\n index,\n width,\n height,\n svg:\n `<svg ${namespaceAttrs} viewBox=\"0 0 ${width} ${height}\" ` +\n `width=\"${width}\" height=\"${height}\">` +\n `${sharedHtml}${clone.outerHTML}</svg>`,\n },\n ];\n });\n}\n"],"mappings":";AAAA,YAAY,aAAa;;;ACMzB,SAAS,iBAAiB,MAAsB;AAC9C,QAAM,OAAO,IAAI,KAAK,CAAC,IAAI,GAAG,EAAE,MAAM,yBAAyB,CAAC;AAChE,QAAM,MAAM,IAAI,gBAAgB,IAAI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