/*
THIS IS A GENERATED/BUNDLED FILE BY ESBUILD
if you want to view the source, please visit the github repository https://github.com/Myriad-Dreamin/typst.ts/blob/main/packages/typst.ts
*/


// ../../packages/parser/pkg/typst_ts_parser.mjs
var wasm;
function addHeapObject(obj) {
  if (heap_next === heap.length) heap.push(heap.length + 1);
  const idx = heap_next;
  heap_next = heap[idx];
  heap[idx] = obj;
  return idx;
}
var CLOSURE_DTORS = typeof FinalizationRegistry === "undefined" ? { register: () => {
}, unregister: () => {
} } : new FinalizationRegistry((state) => state.dtor(state.a, state.b));
function debugString(val) {
  const type = typeof val;
  if (type == "number" || type == "boolean" || val == null) {
    return `${val}`;
  }
  if (type == "string") {
    return `"${val}"`;
  }
  if (type == "symbol") {
    const description = val.description;
    if (description == null) {
      return "Symbol";
    } else {
      return `Symbol(${description})`;
    }
  }
  if (type == "function") {
    const name = val.name;
    if (typeof name == "string" && name.length > 0) {
      return `Function(${name})`;
    } else {
      return "Function";
    }
  }
  if (Array.isArray(val)) {
    const length = val.length;
    let debug = "[";
    if (length > 0) {
      debug += debugString(val[0]);
    }
    for (let i = 1; i < length; i++) {
      debug += ", " + debugString(val[i]);
    }
    debug += "]";
    return debug;
  }
  const builtInMatches = /\[object ([^\]]+)\]/.exec(toString.call(val));
  let className;
  if (builtInMatches && builtInMatches.length > 1) {
    className = builtInMatches[1];
  } else {
    return toString.call(val);
  }
  if (className == "Object") {
    try {
      return "Object(" + JSON.stringify(val) + ")";
    } catch (_) {
      return "Object";
    }
  }
  if (val instanceof Error) {
    return `${val.name}: ${val.message}
${val.stack}`;
  }
  return className;
}
function dropObject(idx) {
  if (idx < 132) return;
  heap[idx] = heap_next;
  heap_next = idx;
}
function getArrayU32FromWasm0(ptr, len) {
  ptr = ptr >>> 0;
  return getUint32ArrayMemory0().subarray(ptr / 4, ptr / 4 + len);
}
function getArrayU8FromWasm0(ptr, len) {
  ptr = ptr >>> 0;
  return getUint8ArrayMemory0().subarray(ptr / 1, ptr / 1 + len);
}
var cachedDataViewMemory0 = null;
function getDataViewMemory0() {
  if (cachedDataViewMemory0 === null || cachedDataViewMemory0.buffer.detached === true || cachedDataViewMemory0.buffer.detached === void 0 && cachedDataViewMemory0.buffer !== wasm.memory.buffer) {
    cachedDataViewMemory0 = new DataView(wasm.memory.buffer);
  }
  return cachedDataViewMemory0;
}
function getStringFromWasm0(ptr, len) {
  ptr = ptr >>> 0;
  return decodeText(ptr, len);
}
var cachedUint32ArrayMemory0 = null;
function getUint32ArrayMemory0() {
  if (cachedUint32ArrayMemory0 === null || cachedUint32ArrayMemory0.byteLength === 0) {
    cachedUint32ArrayMemory0 = new Uint32Array(wasm.memory.buffer);
  }
  return cachedUint32ArrayMemory0;
}
var cachedUint8ArrayMemory0 = null;
function getUint8ArrayMemory0() {
  if (cachedUint8ArrayMemory0 === null || cachedUint8ArrayMemory0.byteLength === 0) {
    cachedUint8ArrayMemory0 = new Uint8Array(wasm.memory.buffer);
  }
  return cachedUint8ArrayMemory0;
}
function getObject(idx) {
  return heap[idx];
}
function handleError(f, args) {
  try {
    return f.apply(this, args);
  } catch (e) {
    wasm.__wbindgen_export3(addHeapObject(e));
  }
}
var heap = new Array(128).fill(void 0);
heap.push(void 0, null, true, false);
var heap_next = heap.length;
function isLikeNone(x) {
  return x === void 0 || x === null;
}
function makeMutClosure(arg0, arg1, dtor, f) {
  const state = { a: arg0, b: arg1, cnt: 1, dtor };
  const real = (...args) => {
    state.cnt++;
    const a = state.a;
    state.a = 0;
    try {
      return f(a, state.b, ...args);
    } finally {
      state.a = a;
      real._wbg_cb_unref();
    }
  };
  real._wbg_cb_unref = () => {
    if (--state.cnt === 0) {
      state.dtor(state.a, state.b);
      state.a = 0;
      CLOSURE_DTORS.unregister(state);
    }
  };
  CLOSURE_DTORS.register(real, state, state);
  return real;
}
function passArray8ToWasm0(arg, malloc) {
  const ptr = malloc(arg.length * 1, 1) >>> 0;
  getUint8ArrayMemory0().set(arg, ptr / 1);
  WASM_VECTOR_LEN = arg.length;
  return ptr;
}
function passStringToWasm0(arg, malloc, realloc) {
  if (realloc === void 0) {
    const buf = cachedTextEncoder.encode(arg);
    const ptr2 = malloc(buf.length, 1) >>> 0;
    getUint8ArrayMemory0().subarray(ptr2, ptr2 + buf.length).set(buf);
    WASM_VECTOR_LEN = buf.length;
    return ptr2;
  }
  let len = arg.length;
  let ptr = malloc(len, 1) >>> 0;
  const mem = getUint8ArrayMemory0();
  let offset = 0;
  for (; offset < len; offset++) {
    const code = arg.charCodeAt(offset);
    if (code > 127) break;
    mem[ptr + offset] = code;
  }
  if (offset !== len) {
    if (offset !== 0) {
      arg = arg.slice(offset);
    }
    ptr = realloc(ptr, len, len = offset + arg.length * 3, 1) >>> 0;
    const view = getUint8ArrayMemory0().subarray(ptr + offset, ptr + len);
    const ret = cachedTextEncoder.encodeInto(arg, view);
    offset += ret.written;
    ptr = realloc(ptr, len, offset, 1) >>> 0;
  }
  WASM_VECTOR_LEN = offset;
  return ptr;
}
function takeObject(idx) {
  const ret = getObject(idx);
  dropObject(idx);
  return ret;
}
var cachedTextDecoder = new TextDecoder("utf-8", { ignoreBOM: true, fatal: true });
cachedTextDecoder.decode();
var MAX_SAFARI_DECODE_BYTES = 2146435072;
var numBytesDecoded = 0;
function decodeText(ptr, len) {
  numBytesDecoded += len;
  if (numBytesDecoded >= MAX_SAFARI_DECODE_BYTES) {
    cachedTextDecoder = new TextDecoder("utf-8", { ignoreBOM: true, fatal: true });
    cachedTextDecoder.decode();
    numBytesDecoded = len;
  }
  return cachedTextDecoder.decode(getUint8ArrayMemory0().subarray(ptr, ptr + len));
}
var cachedTextEncoder = new TextEncoder();
if (!("encodeInto" in cachedTextEncoder)) {
  cachedTextEncoder.encodeInto = function(arg, view) {
    const buf = cachedTextEncoder.encode(arg);
    view.set(buf);
    return {
      read: arg.length,
      written: buf.length
    };
  };
}
var WASM_VECTOR_LEN = 0;
function __wasm_bindgen_func_elem_73(arg0, arg1, arg2) {
  wasm.__wasm_bindgen_func_elem_73(arg0, arg1, addHeapObject(arg2));
}
function __wasm_bindgen_func_elem_1126(arg0, arg1, arg2, arg3) {
  wasm.__wasm_bindgen_func_elem_1126(arg0, arg1, addHeapObject(arg2), addHeapObject(arg3));
}
var ProxyContextFinalization = typeof FinalizationRegistry === "undefined" ? { register: () => {
}, unregister: () => {
} } : new FinalizationRegistry((ptr) => wasm.__wbg_proxycontext_free(ptr >>> 0, 1));
var TypstParserFinalization = typeof FinalizationRegistry === "undefined" ? { register: () => {
}, unregister: () => {
} } : new FinalizationRegistry((ptr) => wasm.__wbg_typstparser_free(ptr >>> 0, 1));
var TypstParserBuilderFinalization = typeof FinalizationRegistry === "undefined" ? { register: () => {
}, unregister: () => {
} } : new FinalizationRegistry((ptr) => wasm.__wbg_typstparserbuilder_free(ptr >>> 0, 1));
var ProxyContext = class {
  __destroy_into_raw() {
    const ptr = this.__wbg_ptr;
    this.__wbg_ptr = 0;
    ProxyContextFinalization.unregister(this);
    return ptr;
  }
  free() {
    const ptr = this.__destroy_into_raw();
    wasm.__wbg_proxycontext_free(ptr, 0);
  }
  /**
   * Creates a new `ProxyContext` instance.
   * @param {any} context
   */
  constructor(context) {
    const ret = wasm.proxycontext_new(addHeapObject(context));
    this.__wbg_ptr = ret >>> 0;
    ProxyContextFinalization.register(this, this.__wbg_ptr, this);
    return this;
  }
  /**
   * Returns the JavaScript this.
   * @returns {any}
   */
  get context() {
    const ret = wasm.proxycontext_context(this.__wbg_ptr);
    return takeObject(ret);
  }
  /**
   * A convenience function to untar a tarball and call a callback for each
   * entry.
   * @param {Uint8Array} data
   * @param {Function} cb
   */
  untar(data, cb) {
    try {
      const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);
      const ptr0 = passArray8ToWasm0(data, wasm.__wbindgen_export);
      const len0 = WASM_VECTOR_LEN;
      wasm.proxycontext_untar(retptr, this.__wbg_ptr, ptr0, len0, addHeapObject(cb));
      var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);
      var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);
      if (r1) {
        throw takeObject(r0);
      }
    } finally {
      wasm.__wbindgen_add_to_stack_pointer(16);
    }
  }
};
if (Symbol.dispose) ProxyContext.prototype[Symbol.dispose] = ProxyContext.prototype.free;
var TypstParser = class _TypstParser {
  static __wrap(ptr) {
    ptr = ptr >>> 0;
    const obj = Object.create(_TypstParser.prototype);
    obj.__wbg_ptr = ptr;
    TypstParserFinalization.register(obj, obj.__wbg_ptr, obj);
    return obj;
  }
  __destroy_into_raw() {
    const ptr = this.__wbg_ptr;
    this.__wbg_ptr = 0;
    TypstParserFinalization.unregister(this);
    return ptr;
  }
  free() {
    const ptr = this.__destroy_into_raw();
    wasm.__wbg_typstparser_free(ptr, 0);
  }
  /**
   * @returns {any}
   */
  get_semantic_token_legend() {
    try {
      const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);
      wasm.typstparser_get_semantic_token_legend(retptr, this.__wbg_ptr);
      var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);
      var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);
      var r2 = getDataViewMemory0().getInt32(retptr + 4 * 2, true);
      if (r2) {
        throw takeObject(r1);
      }
      return takeObject(r0);
    } finally {
      wasm.__wbindgen_add_to_stack_pointer(16);
    }
  }
  /**
   * @param {string} src
   * @param {string} offset_encoding
   * @returns {Uint32Array}
   */
  get_semantic_tokens_by_string(src, offset_encoding) {
    try {
      const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);
      const ptr0 = passStringToWasm0(src, wasm.__wbindgen_export, wasm.__wbindgen_export2);
      const len0 = WASM_VECTOR_LEN;
      const ptr1 = passStringToWasm0(offset_encoding, wasm.__wbindgen_export, wasm.__wbindgen_export2);
      const len1 = WASM_VECTOR_LEN;
      wasm.typstparser_get_semantic_tokens_by_string(retptr, this.__wbg_ptr, ptr0, len0, ptr1, len1);
      var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);
      var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);
      var r2 = getDataViewMemory0().getInt32(retptr + 4 * 2, true);
      if (r2) {
        throw takeObject(r1);
      }
      return takeObject(r0);
    } finally {
      wasm.__wbindgen_add_to_stack_pointer(16);
    }
  }
};
if (Symbol.dispose) TypstParser.prototype[Symbol.dispose] = TypstParser.prototype.free;
var TypstParserBuilder = class {
  __destroy_into_raw() {
    const ptr = this.__wbg_ptr;
    this.__wbg_ptr = 0;
    TypstParserBuilderFinalization.unregister(this);
    return ptr;
  }
  free() {
    const ptr = this.__destroy_into_raw();
    wasm.__wbg_typstparserbuilder_free(ptr, 0);
  }
  constructor() {
    try {
      const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);
      wasm.typstparserbuilder_new(retptr);
      var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);
      var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);
      var r2 = getDataViewMemory0().getInt32(retptr + 4 * 2, true);
      if (r2) {
        throw takeObject(r1);
      }
      this.__wbg_ptr = r0 >>> 0;
      TypstParserBuilderFinalization.register(this, this.__wbg_ptr, this);
      return this;
    } finally {
      wasm.__wbindgen_add_to_stack_pointer(16);
    }
  }
  /**
   * @returns {Promise<TypstParser>}
   */
  build() {
    const ptr = this.__destroy_into_raw();
    const ret = wasm.typstparserbuilder_build(ptr);
    return takeObject(ret);
  }
};
if (Symbol.dispose) TypstParserBuilder.prototype[Symbol.dispose] = TypstParserBuilder.prototype.free;
var EXPECTED_RESPONSE_TYPES = /* @__PURE__ */ new Set(["basic", "cors", "default"]);
async function __wbg_load(module, imports) {
  if (typeof Response === "function" && module instanceof Response) {
    if (typeof WebAssembly.instantiateStreaming === "function") {
      try {
        return await WebAssembly.instantiateStreaming(module, imports);
      } catch (e) {
        const validResponse = module.ok && EXPECTED_RESPONSE_TYPES.has(module.type);
        if (validResponse && module.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", e);
        } else {
          throw e;
        }
      }
    }
    const bytes = await module.arrayBuffer();
    return await WebAssembly.instantiate(bytes, imports);
  } else {
    const instance = await WebAssembly.instantiate(module, imports);
    if (instance instanceof WebAssembly.Instance) {
      return { instance, module };
    } else {
      return instance;
    }
  }
}
function __wbg_get_imports() {
  const imports = {};
  imports.wbg = {};
  imports.wbg.__wbg___wbindgen_debug_string_adfb662ae34724b6 = function(arg0, arg1) {
    const ret = debugString(getObject(arg1));
    const ptr1 = passStringToWasm0(ret, wasm.__wbindgen_export, wasm.__wbindgen_export2);
    const len1 = WASM_VECTOR_LEN;
    getDataViewMemory0().setInt32(arg0 + 4 * 1, len1, true);
    getDataViewMemory0().setInt32(arg0 + 4 * 0, ptr1, true);
  };
  imports.wbg.__wbg___wbindgen_is_function_8d400b8b1af978cd = function(arg0) {
    const ret = typeof getObject(arg0) === "function";
    return ret;
  };
  imports.wbg.__wbg___wbindgen_is_undefined_f6b95eab589e0269 = function(arg0) {
    const ret = getObject(arg0) === void 0;
    return ret;
  };
  imports.wbg.__wbg___wbindgen_throw_dd24417ed36fc46e = function(arg0, arg1) {
    throw new Error(getStringFromWasm0(arg0, arg1));
  };
  imports.wbg.__wbg__wbg_cb_unref_87dfb5aaa0cbcea7 = function(arg0) {
    getObject(arg0)._wbg_cb_unref();
  };
  imports.wbg.__wbg_call_3020136f7a2d6e44 = function() {
    return handleError(function(arg0, arg1, arg2) {
      const ret = getObject(arg0).call(getObject(arg1), getObject(arg2));
      return addHeapObject(ret);
    }, arguments);
  };
  imports.wbg.__wbg_call_78f94eb02ec7f9b2 = function() {
    return handleError(function(arg0, arg1, arg2, arg3, arg4) {
      const ret = getObject(arg0).call(getObject(arg1), getObject(arg2), getObject(arg3), getObject(arg4));
      return addHeapObject(ret);
    }, arguments);
  };
  imports.wbg.__wbg_call_abb4ff46ce38be40 = function() {
    return handleError(function(arg0, arg1) {
      const ret = getObject(arg0).call(getObject(arg1));
      return addHeapObject(ret);
    }, arguments);
  };
  imports.wbg.__wbg_error_7534b8e9a36f1ab4 = function(arg0, arg1) {
    let deferred0_0;
    let deferred0_1;
    try {
      deferred0_0 = arg0;
      deferred0_1 = arg1;
      console.error(getStringFromWasm0(arg0, arg1));
    } finally {
      wasm.__wbindgen_export4(deferred0_0, deferred0_1, 1);
    }
  };
  imports.wbg.__wbg_new_1ba21ce319a06297 = function() {
    const ret = new Object();
    return addHeapObject(ret);
  };
  imports.wbg.__wbg_new_25f239778d6112b9 = function() {
    const ret = new Array();
    return addHeapObject(ret);
  };
  imports.wbg.__wbg_new_8a6f238a6ece86ea = function() {
    const ret = new Error();
    return addHeapObject(ret);
  };
  imports.wbg.__wbg_new_df1173567d5ff028 = function(arg0, arg1) {
    const ret = new Error(getStringFromWasm0(arg0, arg1));
    return addHeapObject(ret);
  };
  imports.wbg.__wbg_new_ff12d2b041fb48f1 = function(arg0, arg1) {
    try {
      var state0 = { a: arg0, b: arg1 };
      var cb0 = (arg02, arg12) => {
        const a = state0.a;
        state0.a = 0;
        try {
          return __wasm_bindgen_func_elem_1126(a, state0.b, arg02, arg12);
        } finally {
          state0.a = a;
        }
      };
      const ret = new Promise(cb0);
      return addHeapObject(ret);
    } finally {
      state0.a = state0.b = 0;
    }
  };
  imports.wbg.__wbg_new_from_slice_db0691b69e9d3891 = function(arg0, arg1) {
    const ret = new Uint32Array(getArrayU32FromWasm0(arg0, arg1));
    return addHeapObject(ret);
  };
  imports.wbg.__wbg_new_from_slice_f9c22b9153b26992 = function(arg0, arg1) {
    const ret = new Uint8Array(getArrayU8FromWasm0(arg0, arg1));
    return addHeapObject(ret);
  };
  imports.wbg.__wbg_new_no_args_cb138f77cf6151ee = function(arg0, arg1) {
    const ret = new Function(getStringFromWasm0(arg0, arg1));
    return addHeapObject(ret);
  };
  imports.wbg.__wbg_queueMicrotask_9b549dfce8865860 = function(arg0) {
    const ret = getObject(arg0).queueMicrotask;
    return addHeapObject(ret);
  };
  imports.wbg.__wbg_queueMicrotask_fca69f5bfad613a5 = function(arg0) {
    queueMicrotask(getObject(arg0));
  };
  imports.wbg.__wbg_resolve_fd5bfbaa4ce36e1e = function(arg0) {
    const ret = Promise.resolve(getObject(arg0));
    return addHeapObject(ret);
  };
  imports.wbg.__wbg_set_3f1d0b984ed272ed = function(arg0, arg1, arg2) {
    getObject(arg0)[takeObject(arg1)] = takeObject(arg2);
  };
  imports.wbg.__wbg_set_7df433eea03a5c14 = function(arg0, arg1, arg2) {
    getObject(arg0)[arg1 >>> 0] = takeObject(arg2);
  };
  imports.wbg.__wbg_stack_0ed75d68575b0f3c = function(arg0, arg1) {
    const ret = getObject(arg1).stack;
    const ptr1 = passStringToWasm0(ret, wasm.__wbindgen_export, wasm.__wbindgen_export2);
    const len1 = WASM_VECTOR_LEN;
    getDataViewMemory0().setInt32(arg0 + 4 * 1, len1, true);
    getDataViewMemory0().setInt32(arg0 + 4 * 0, ptr1, true);
  };
  imports.wbg.__wbg_static_accessor_GLOBAL_769e6b65d6557335 = function() {
    const ret = typeof global === "undefined" ? null : global;
    return isLikeNone(ret) ? 0 : addHeapObject(ret);
  };
  imports.wbg.__wbg_static_accessor_GLOBAL_THIS_60cf02db4de8e1c1 = function() {
    const ret = typeof globalThis === "undefined" ? null : globalThis;
    return isLikeNone(ret) ? 0 : addHeapObject(ret);
  };
  imports.wbg.__wbg_static_accessor_SELF_08f5a74c69739274 = function() {
    const ret = typeof self === "undefined" ? null : self;
    return isLikeNone(ret) ? 0 : addHeapObject(ret);
  };
  imports.wbg.__wbg_static_accessor_WINDOW_a8924b26aa92d024 = function() {
    const ret = typeof window === "undefined" ? null : window;
    return isLikeNone(ret) ? 0 : addHeapObject(ret);
  };
  imports.wbg.__wbg_then_4f95312d68691235 = function(arg0, arg1) {
    const ret = getObject(arg0).then(getObject(arg1));
    return addHeapObject(ret);
  };
  imports.wbg.__wbg_typstparser_new = function(arg0) {
    const ret = TypstParser.__wrap(arg0);
    return addHeapObject(ret);
  };
  imports.wbg.__wbindgen_cast_2241b6af4c4b2941 = function(arg0, arg1) {
    const ret = getStringFromWasm0(arg0, arg1);
    return addHeapObject(ret);
  };
  imports.wbg.__wbindgen_cast_3b1a32895b770b74 = function(arg0, arg1) {
    const ret = makeMutClosure(arg0, arg1, wasm.__wasm_bindgen_func_elem_86, __wasm_bindgen_func_elem_73);
    return addHeapObject(ret);
  };
  imports.wbg.__wbindgen_cast_d6cd19b81560fd6e = function(arg0) {
    const ret = arg0;
    return addHeapObject(ret);
  };
  imports.wbg.__wbindgen_object_clone_ref = function(arg0) {
    const ret = getObject(arg0);
    return addHeapObject(ret);
  };
  imports.wbg.__wbindgen_object_drop_ref = function(arg0) {
    takeObject(arg0);
  };
  return imports;
}
function __wbg_finalize_init(instance, module) {
  wasm = instance.exports;
  __wbg_init.__wbindgen_wasm_module = module;
  cachedDataViewMemory0 = null;
  cachedUint32ArrayMemory0 = null;
  cachedUint8ArrayMemory0 = null;
  return wasm;
}
async function __wbg_init(module_or_path) {
  if (wasm !== void 0) return wasm;
  if (typeof module_or_path !== "undefined") {
    if (Object.getPrototypeOf(module_or_path) === Object.prototype) {
      ({ module_or_path } = module_or_path);
    } else {
      console.warn("using deprecated parameters for the initialization function; pass a single object instead");
    }
  }
  if (typeof module_or_path === "undefined") {
    module_or_path = importWasmModule("typst_ts_parser_bg.wasm", import.meta.url);
  }
  const imports = __wbg_get_imports();
  if (typeof module_or_path === "string" || typeof Request === "function" && module_or_path instanceof Request || typeof URL === "function" && module_or_path instanceof URL) {
    module_or_path = fetch(module_or_path);
  }
  const { instance, module } = await __wbg_load(await module_or_path, imports);
  return __wbg_finalize_init(instance, module);
}
var typst_ts_parser_default = __wbg_init;
var importWasmModule = async function(wasm_name, url) {
  throw new Error("Cannot import wasm module without importer: " + wasm_name + " " + url);
};
function setImportWasmModule(importer) {
  importWasmModule = importer;
}

// ../../packages/parser/pkg/wasm-pack-shim.mjs
var wasm_pack_shim_default = typst_ts_parser_default;
var nodeJsImportWasmModule = async function(wasm_name, url) {
  const escapeImport = new Function("m", "return import(m)");
  const { readFileSync } = await escapeImport("fs");
  const wasmPath = new URL(wasm_name, url);
  return await readFileSync(wasmPath).buffer;
};
var isNode = typeof process !== "undefined" && process.versions != null && process.versions.node != null;
if (isNode) {
  setImportWasmModule(nodeJsImportWasmModule);
}

// src/semantic_tokens.mts
function toMultilineTokens2(tokens, styling2, languageId) {
  const srcData = tokens.data;
  const tokenCount = tokens.data.length / 5 | 0;
  const tokensPerArea = Math.max(
    Math.ceil(tokenCount / 1024 /* DesiredMaxAreas */),
    400 /* DesiredTokensPerArea */
  );
  const result = [];
  let tokenIndex = 0;
  let lastLineNumber = 1;
  let lastStartCharacter = 0;
  while (tokenIndex < tokenCount) {
    const tokenStartIndex = tokenIndex;
    let tokenEndIndex = Math.min(tokenStartIndex + tokensPerArea, tokenCount);
    if (tokenEndIndex < tokenCount) {
      let smallTokenEndIndex = tokenEndIndex;
      while (smallTokenEndIndex - 1 > tokenStartIndex && srcData[5 * smallTokenEndIndex] === 0) {
        smallTokenEndIndex--;
      }
      if (smallTokenEndIndex - 1 === tokenStartIndex) {
        let bigTokenEndIndex = tokenEndIndex;
        while (bigTokenEndIndex + 1 < tokenCount && srcData[5 * bigTokenEndIndex] === 0) {
          bigTokenEndIndex++;
        }
        tokenEndIndex = bigTokenEndIndex;
      } else {
        tokenEndIndex = smallTokenEndIndex;
      }
    }
    let destData = new Uint32Array((tokenEndIndex - tokenStartIndex) * 4);
    let destOffset = 0;
    let areaLine = 0;
    let prevLineNumber = 0;
    let prevEndCharacter = 0;
    while (tokenIndex < tokenEndIndex) {
      const srcOffset = 5 * tokenIndex;
      const deltaLine = srcData[srcOffset];
      const deltaCharacter = srcData[srcOffset + 1];
      const lineNumber = lastLineNumber + deltaLine | 0;
      const startCharacter = deltaLine === 0 ? lastStartCharacter + deltaCharacter | 0 : deltaCharacter;
      const length = srcData[srcOffset + 2];
      const endCharacter = startCharacter + length | 0;
      const tokenTypeIndex = srcData[srcOffset + 3];
      const tokenModifierSet = srcData[srcOffset + 4];
      if (endCharacter <= startCharacter) {
        styling2.warnInvalidLengthSemanticTokens(lineNumber, startCharacter + 1);
      } else if (prevLineNumber === lineNumber && prevEndCharacter > startCharacter) {
        styling2.warnOverlappingSemanticTokens(lineNumber, startCharacter + 1);
      } else {
        const metadata = styling2.getMetadata(tokenTypeIndex, tokenModifierSet, languageId);
        if (metadata !== 2147483647 /* NO_STYLING */) {
          if (areaLine === 0) {
            areaLine = lineNumber;
          }
          destData[destOffset] = lineNumber - areaLine;
          destData[destOffset + 1] = startCharacter;
          destData[destOffset + 2] = endCharacter;
          destData[destOffset + 3] = metadata;
          destOffset += 4;
          prevLineNumber = lineNumber;
          prevEndCharacter = endCharacter;
        }
      }
      lastLineNumber = lineNumber;
      lastStartCharacter = startCharacter;
      tokenIndex++;
    }
    if (destOffset !== destData.length) {
      destData = destData.subarray(0, destOffset);
    }
    result.push([areaLine, destData]);
  }
  return result;
}
var LANGUAGE_ID = 0;
var _TypstSemaTokenStyling = class _TypstSemaTokenStyling {
  constructor(enableWarnings) {
    this.enableWarnings = enableWarnings;
    this._hashTable = new HashTable();
  }
  resolveTokenStyle(tokenType, tokenModifiers, languageId) {
    return 2147483647 /* NO_STYLING */;
  }
  getMetadata(tokenTypeIndex, tokenModifierSet, languageId) {
    const entry = this._hashTable.get(tokenTypeIndex, tokenModifierSet, LANGUAGE_ID);
    let metadata;
    if (entry) {
      metadata = entry.metadata;
    } else {
      let tokenType = _TypstSemaTokenStyling._legend.tokenTypes[tokenTypeIndex];
      const tokenModifiers = [];
      if (tokenType) {
        let modifierSet = tokenModifierSet;
        for (let modifierIndex = 0; modifierSet > 0 && modifierIndex < _TypstSemaTokenStyling._legend.tokenModifiers.length; modifierIndex++) {
          if (modifierSet & 1) {
            tokenModifiers.push(_TypstSemaTokenStyling._legend.tokenModifiers[modifierIndex]);
          }
          modifierSet = modifierSet >> 1;
        }
        metadata = this.resolveTokenStyle(tokenType, tokenModifiers, languageId);
      } else {
        metadata = 2147483647 /* NO_STYLING */;
      }
      this._hashTable.add(tokenTypeIndex, tokenModifierSet, LANGUAGE_ID, metadata);
    }
    return metadata;
  }
  warnInvalidLengthSemanticTokens(lineNumber, startCharacter) {
    if (this.enableWarnings) {
      console.warn("warnInvalidLengthSemanticTokens", lineNumber, startCharacter);
    }
  }
  warnOverlappingSemanticTokens(lineNumber, startCharacter) {
    if (this.enableWarnings) {
      console.warn("warnOverlappingSemanticTokens", lineNumber, startCharacter);
    }
  }
};
_TypstSemaTokenStyling._legend = void 0;
var TypstSemaTokenStyling = _TypstSemaTokenStyling;
var HashTableEntry = class {
  constructor(tokenTypeIndex, tokenModifierSet, languageId, metadata) {
    this.tokenTypeIndex = tokenTypeIndex;
    this.tokenModifierSet = tokenModifierSet;
    this.languageId = languageId;
    this.metadata = metadata;
    this.next = null;
  }
};
var _HashTable = class _HashTable {
  constructor() {
    this._elementsCount = 0;
    this._currentLengthIndex = 0;
    this._currentLength = _HashTable._SIZES[this._currentLengthIndex];
    this._growCount = Math.round(
      this._currentLengthIndex + 1 < _HashTable._SIZES.length ? 2 / 3 * this._currentLength : 0
    );
    this._elements = [];
    _HashTable._nullOutEntries(this._elements, this._currentLength);
  }
  static _nullOutEntries(entries, length) {
    for (let i = 0; i < length; i++) {
      entries[i] = null;
    }
  }
  _hash2(n1, n2) {
    return (n1 << 5) - n1 + n2 | 0;
  }
  _hashFunc(tokenTypeIndex, tokenModifierSet, languageId) {
    return this._hash2(this._hash2(tokenTypeIndex, tokenModifierSet), languageId) % this._currentLength;
  }
  get(tokenTypeIndex, tokenModifierSet, languageId) {
    const hash = this._hashFunc(tokenTypeIndex, tokenModifierSet, languageId);
    let p = this._elements[hash];
    while (p) {
      if (p.tokenTypeIndex === tokenTypeIndex && p.tokenModifierSet === tokenModifierSet && p.languageId === languageId) {
        return p;
      }
      p = p.next;
    }
    return null;
  }
  add(tokenTypeIndex, tokenModifierSet, languageId, metadata) {
    this._elementsCount++;
    if (this._growCount !== 0 && this._elementsCount >= this._growCount) {
      const oldElements = this._elements;
      this._currentLengthIndex++;
      this._currentLength = _HashTable._SIZES[this._currentLengthIndex];
      this._growCount = Math.round(
        this._currentLengthIndex + 1 < _HashTable._SIZES.length ? 2 / 3 * this._currentLength : 0
      );
      this._elements = [];
      _HashTable._nullOutEntries(this._elements, this._currentLength);
      for (const first of oldElements) {
        let p = first;
        while (p) {
          const oldNext = p.next;
          p.next = null;
          this._add(p);
          p = oldNext;
        }
      }
    }
    this._add(new HashTableEntry(tokenTypeIndex, tokenModifierSet, languageId, metadata));
  }
  _add(element) {
    const hash = this._hashFunc(
      element.tokenTypeIndex,
      element.tokenModifierSet,
      element.languageId
    );
    element.next = this._elements[hash];
    this._elements[hash] = element;
  }
};
_HashTable._SIZES = [
  3,
  7,
  13,
  31,
  61,
  127,
  251,
  509,
  1021,
  2039,
  4093,
  8191,
  16381,
  32749,
  65521,
  131071,
  262139,
  524287,
  1048573,
  2097143
];
var HashTable = _HashTable;
var HljsScopes = /* @__PURE__ */ ((HljsScopes2) => {
  HljsScopes2[HljsScopes2["keyword"] = 0] = "keyword";
  HljsScopes2[HljsScopes2["built_in"] = 1] = "built_in";
  HljsScopes2[HljsScopes2["type"] = 2] = "type";
  HljsScopes2[HljsScopes2["literal"] = 3] = "literal";
  HljsScopes2[HljsScopes2["number"] = 4] = "number";
  HljsScopes2[HljsScopes2["operator"] = 5] = "operator";
  HljsScopes2[HljsScopes2["comment"] = 6] = "comment";
  HljsScopes2[HljsScopes2["punctuation"] = 7] = "punctuation";
  HljsScopes2[HljsScopes2["property"] = 8] = "property";
  HljsScopes2[HljsScopes2["string"] = 9] = "string";
  HljsScopes2[HljsScopes2["regexp"] = 10] = "regexp";
  HljsScopes2[HljsScopes2["char.escape"] = 11] = "char.escape";
  HljsScopes2[HljsScopes2["subst"] = 12] = "subst";
  HljsScopes2[HljsScopes2["symbol"] = 13] = "symbol";
  HljsScopes2[HljsScopes2["title.function"] = 14] = "title.function";
  HljsScopes2[HljsScopes2["title.class"] = 15] = "title.class";
  HljsScopes2[HljsScopes2["variable"] = 16] = "variable";
  HljsScopes2[HljsScopes2["variable.language"] = 17] = "variable.language";
  HljsScopes2[HljsScopes2["variable.constant"] = 18] = "variable.constant";
  HljsScopes2[HljsScopes2["title"] = 19] = "title";
  HljsScopes2[HljsScopes2["title.class.inherited"] = 20] = "title.class.inherited";
  HljsScopes2[HljsScopes2["title.function.invoke"] = 21] = "title.function.invoke";
  HljsScopes2[HljsScopes2["params"] = 22] = "params";
  HljsScopes2[HljsScopes2["doctag"] = 23] = "doctag";
  HljsScopes2[HljsScopes2["meta"] = 24] = "meta";
  HljsScopes2[HljsScopes2["meta.prompt"] = 25] = "meta.prompt";
  HljsScopes2[HljsScopes2["meta keyword"] = 26] = "meta keyword";
  HljsScopes2[HljsScopes2["meta string"] = 27] = "meta string";
  HljsScopes2[HljsScopes2["section"] = 28] = "section";
  HljsScopes2[HljsScopes2["tag"] = 29] = "tag";
  HljsScopes2[HljsScopes2["name"] = 30] = "name";
  HljsScopes2[HljsScopes2["attr"] = 31] = "attr";
  HljsScopes2[HljsScopes2["attribute"] = 32] = "attribute";
  HljsScopes2[HljsScopes2["bullet"] = 33] = "bullet";
  HljsScopes2[HljsScopes2["code"] = 34] = "code";
  HljsScopes2[HljsScopes2["emphasis"] = 35] = "emphasis";
  HljsScopes2[HljsScopes2["strong"] = 36] = "strong";
  HljsScopes2[HljsScopes2["formula"] = 37] = "formula";
  HljsScopes2[HljsScopes2["link"] = 38] = "link";
  HljsScopes2[HljsScopes2["quote"] = 39] = "quote";
  HljsScopes2[HljsScopes2["selector-tag"] = 40] = "selector-tag";
  HljsScopes2[HljsScopes2["selector-id"] = 41] = "selector-id";
  HljsScopes2[HljsScopes2["selector-class"] = 42] = "selector-class";
  HljsScopes2[HljsScopes2["selector-attr"] = 43] = "selector-attr";
  HljsScopes2[HljsScopes2["selector-pseudo"] = 44] = "selector-pseudo";
  HljsScopes2[HljsScopes2["template-tag"] = 45] = "template-tag";
  HljsScopes2[HljsScopes2["template-variable"] = 46] = "template-variable";
  HljsScopes2[HljsScopes2["addition"] = 47] = "addition";
  HljsScopes2[HljsScopes2["deletion"] = 48] = "deletion";
  HljsScopes2[HljsScopes2["strong.emphasis"] = 49] = "strong.emphasis";
  return HljsScopes2;
})(HljsScopes || {});
var _TypstSemaTokenHljsStyling = class _TypstSemaTokenHljsStyling extends TypstSemaTokenStyling {
  constructor(enableWarnings) {
    super(enableWarnings);
  }
  resolveTokenStyle(tokenType, tokenModifiers, languageId) {
    if (tokenModifiers.includes("math")) {
      if (tokenType === "delim") {
        return 7 /* punctuation */;
      }
      return 37 /* formula */;
    }
    if (tokenModifiers.length > 0) {
      if (tokenModifiers.includes("strong")) {
        if (tokenModifiers.includes("emph")) {
          return 49 /* strong.emphasis */;
        }
        return 36 /* strong */;
      }
      if (tokenModifiers.includes("emph")) {
        return 35 /* emphasis */;
      }
    }
    let encoded = _TypstSemaTokenHljsStyling.typeToScope.get(tokenType);
    if (encoded !== void 0) {
      return encoded;
    }
    return 2147483647 /* NO_STYLING */;
  }
  getScope(metadata) {
    if (metadata === 49 /* strong.emphasis */) {
      return ["strong", "emphasis"];
    }
    return _TypstSemaTokenHljsStyling.scopes[metadata];
  }
};
_TypstSemaTokenHljsStyling.scopes = Object.values(HljsScopes).filter((v) => typeof v !== "number");
_TypstSemaTokenHljsStyling.typeToScope = /* @__PURE__ */ new Map([
  ["comment", 6 /* comment */],
  ["string", 9 /* string */],
  ["operator", 5 /* operator */],
  ["keyword", 0 /* keyword */],
  ["number", 4 /* number */],
  ["function", 14 /* title.function */],
  ["decorator", 14 /* title.function */],
  ["bool", 3 /* literal */],
  ["punctuation", 7 /* punctuation */],
  ["escape", 11 /* char.escape */],
  ["link", 38 /* link */],
  ["raw", 34 /* code */],
  ["label", 16 /* variable */],
  ["ref", 16 /* variable */],
  ["heading", 28 /* section */],
  ["marker", 33 /* bullet */],
  // in form of \Term
  ["term", 35 /* emphasis */],
  ["pol", 16 /* variable */]
  // error not rendered
  // ['error', HljsScopes.punctuation],
  // text not rendered
  // ['text', HljsScopes.punctuation],
]);
var TypstSemaTokenHljsStyling = _TypstSemaTokenHljsStyling;

// src/hljs.mts
var parser;
var styling = new TypstSemaTokenHljsStyling(false);
async function initHljs() {
  const p = await new TypstParserBuilder().build();
  parser = p;
  TypstSemaTokenStyling._legend = p.get_semantic_token_legend();
  console.log("typst parser module loaded for hljs", parser);
  return parser;
}
function hljsTypst(options) {
  return (hljs) => {
    const handleSubLanguage = (code, emitter, langTag, useDefault) => {
      code = code.slice(3);
      if (!useDefault) {
        code = code.slice(langTag.length);
      }
      code = code.slice(0, code.length - 3);
      const result = hljs.highlight(code, {
        language: langTag,
        ignoreIllegals: true
      });
      if (result.errorRaised) {
        return false;
      }
      emitter.startScope("code");
      emitter.addText("```");
      if (!useDefault) {
        emitter.addText(langTag);
      }
      console.log("handleNestedCodeBlocks", langTag, code, useDefault, result);
      emitter.__addSublanguage(result._emitter, langTag);
      emitter.addText("```");
      emitter.endScope("code");
      return true;
    };
    let defaultHandleCodeBlocks = options?.handleCodeBlocks === false ? void 0 : (code, emitter) => {
      if (!code.startsWith("``") || !code.endsWith("```")) {
        return false;
      }
      const useDefault = options?.codeBlockDefaultLanguage;
      let index = code.indexOf("\n");
      if (index === -1) {
        index = code.indexOf(" ");
      }
      if (index !== -1) {
        const langTag = code.slice(3, index).trim();
        if (!langTag && useDefault) {
          return handleSubLanguage(code, emitter, useDefault, true);
        }
        if (langTag && hljs.getLanguage(langTag)) {
          return handleSubLanguage(code, emitter, langTag, false);
        }
      } else if (useDefault) {
        return handleSubLanguage(code, emitter, useDefault, true);
      }
      return false;
    };
    let handleCodeBlocks = typeof options?.handleCodeBlocks === "function" ? options?.handleCodeBlocks : defaultHandleCodeBlocks;
    return {
      case_insensitive: false,
      keywords: ["let", "set", "show", "import"],
      contains: [],
      __emitTokens: function(code, emitter) {
        const semaTokens = parser.get_semantic_tokens_by_string(code, "utf-8");
        const styledTokens = toMultilineTokens2({ data: semaTokens }, styling, "typst");
        const lines = code.split("\n");
        let globalLastLine = 1;
        let globalLastColumn = 0;
        function emitFeat(content, feat) {
          if (feat === 2147483647 /* NO_STYLING */) {
            emitter.addText(content);
          } else {
            const scope = styling.getScope(feat);
            if (scope === "code" && handleCodeBlocks) {
              if (handleCodeBlocks(content, emitter)) {
                return;
              }
            }
            if (Array.isArray(scope)) {
              for (const s of scope) {
                emitter.startScope(s);
              }
              emitter.addText(content);
              for (const s of scope) {
                emitter.endScope(s);
              }
              return;
            } else {
              emitter.startScope(scope);
              emitter.addText(content);
              emitter.endScope(scope);
            }
          }
        }
        function advanceLine(deltaLine, feat) {
          for (let i = 0; i < deltaLine; i++) {
            let content = lines[globalLastLine + i - 1];
            if (i === 0) {
              content = content.substring(globalLastColumn);
              globalLastColumn = 0;
            }
            emitFeat(content, feat);
            if (globalLastLine + i !== lines.length) {
              emitFeat("\n", 2147483647 /* NO_STYLING */);
            }
          }
          globalLastLine += deltaLine;
        }
        function advanceRange(startCharacter, endCharacter, feat) {
          let line = lines[globalLastLine - 1];
          if (startCharacter !== globalLastColumn) {
            let content2 = line.substring(globalLastColumn, startCharacter);
            emitFeat(content2, 2147483647 /* NO_STYLING */);
          }
          let content = line.substring(startCharacter, endCharacter);
          if (endCharacter <= line.length) {
            globalLastColumn = endCharacter;
          } else {
            endCharacter -= line.length;
            while (endCharacter > 0) {
              content += "\n";
              globalLastLine++;
              globalLastColumn = 0;
              endCharacter--;
              if (endCharacter) {
                let newContent = lines[globalLastLine - 1].substring(0, endCharacter);
                content += newContent;
                endCharacter -= newContent.length;
                globalLastColumn = newContent.length;
              }
            }
          }
          emitFeat(content, feat);
        }
        for (const [areaLine, tokens] of styledTokens) {
          advanceLine(areaLine - globalLastLine, 0);
          for (let i = 0; i < tokens.length; i += 4) {
            const deltaLine = tokens[i];
            advanceLine(
              deltaLine + areaLine - globalLastLine,
              2147483647 /* NO_STYLING */
            );
            advanceRange(tokens[i + 1], tokens[i + 2], tokens[i + 3]);
          }
        }
        advanceLine(lines.length - globalLastLine, 0);
      }
    };
  };
}

// src/contrib/hljs/typst-lite.mts
var moduleSource = window.$typst$parserModuleSource || "jsdelivr";
var parserModule;
switch (moduleSource) {
  default:
    if (typeof moduleSource !== "string") {
      parserModule = moduleSource;
    } else {
      parserModule = fetch(moduleSource).catch((error) => {
        console.warn("unknown module source for importing typst module", moduleSource, error);
      });
    }
  case null:
  case void 0:
  case "jsdelivr":
    parserModule = fetch(
      "https://cdn.jsdelivr.net/npm/@myriaddreamin/typst-ts-parser/pkg/typst_ts_parser_bg.wasm"
    );
    break;
  case "local":
    parserModule = fetch(
      "http://127.0.0.1:20810/base/node_modules/@myriaddreamin/typst-ts-parser/pkg/typst_ts_parser_bg.wasm"
    );
    break;
}
window.$typst$parserModule = wasm_pack_shim_default(parserModule).then(() => initHljs());
window.hljsTypst = hljsTypst;
