{"version":3,"sources":["../lib/wasm/wasm-utils-env.ts","../lib/wasm/wasm-utils-import.ts","../lib/wasm/wasm-factory.ts","../lib/wasm/wasm-utils.ts","../lib/wasm/run-options.ts","../lib/wasm/session-options.ts","../lib/wasm/wasm-common.ts","../lib/wasm/wasm-utils-load-file.ts","../lib/wasm/wasm-core-impl.ts","../lib/wasm/proxy-wrapper.ts","../lib/wasm/lora-adapter-handler.ts","../lib/wasm/session-handler-inference.ts","../lib/validate-session-options.ts","../lib/backend-wasm.ts","../lib/index.ts","../lib/version.ts"],"names":["isNode","init_wasm_utils_env","__esmMin","origin","isEsmImportMetaUrlHardcodedAsFileUri","getScriptSrc","scriptSrc","inferWasmPathPrefixFromScriptSrc","isSameOrigin","normalizeUrl","fallbackUrl","preload","dynamicImportDefault","embeddedWasmModule","importWasmModule","init_wasm_utils_import","URL2","filename","prefixOverride","baseUrl","absoluteUrl","blob","url","urlOverride","isMultiThreaded","isWasmOverridden","useEmbeddedModule","wasmModuleFilename","wasmModuleUrl","needPreload","wasm","initialized","initializing","aborted","isMultiThreadSupported","isSimdSupported","isRelaxedSimdSupported","initializeWebAssembly","getInstance","init_wasm_factory","flags","timeout","numThreads","multiThreadSupported","wasmPaths","wasmPrefixOverride","mjsPathOverrideFlag","mjsPathOverride","wasmPathOverrideFlag","wasmPathOverride","wasmBinaryOverride","objectUrl","ortWasmFactory","isTimeout","tasks","resolve","reject","config","fileName","inferredWasmPathPrefix","module","what","allocWasmString","iterateExtraOptions","checkLastError","init_wasm_utils","data","allocs","dataLength","dataOffset","options","prefix","seen","handler","key","value","name","message","stack","ptrSize","paramsOffset","errorCode","errorMessagePointer","errorMessage","setRunOptions","init_run_options","loraAdapterHandles","runOptionsHandle","runOptions","tagDataOffset","keyDataOffset","valueDataOffset","adapterHandle","e","alloc","getGraphOptimzationLevel","getExecutionMode","appendDefaultOptions","appendSessionConfig","setExecutionProviders","setSessionOptions","init_session_options","graphOptimizationLevel","executionMode","session","ep","sessionOptionsHandle","sessionOptions","executionProviders","epName","epOptions","selectedEpDevices","deviceType","webgpuOptions","epOptionsCount","keysOffset","valuesOffset","i","appendErrorCode","epDevicesOffset","epNameDataOffset","logIdDataOffset","logSeverityLevel","logVerbosityLevel","optimizedModelFilePathOffset","nameOffset","tensorDataTypeStringToEnum","tensorDataTypeEnumToString","calculateTensorSizeInBytes","tensorTypeToTypedArrayConstructor","logLevelStringToEnum","isGpuBufferSupportedType","isMLTensorSupportedType","dataLocationStringToEnum","init_wasm_common","type","typeProto","dateType","dimsOrSize","elementSize","size","a","b","logLevel","location","loadFile","init_wasm_utils_load_file","file","readFile","createReadStream","stream","chunks","chunk","response","contentLengthHeader","fileSize","reader","buffer","pages","offset","done","chunkSize","TRACE_EVENT_BEGIN","TRACE_EVENT_END","initOrt","initRuntime","initEp","activeSessions","getSessionInputOutputCount","getSessionInputOutputMetadata","copyFromExternalBuffer","createSession","releaseSession","loraAdapters","nextLoraAdapterId","loraAdapterRunCounts","createLoraAdapter","releaseLoraAdapter","prepareInputOutputTensor","run","endProfiling","init_wasm_core_impl","loggingLevel","env","webgpuAdapter","powerPreference","forceFallbackAdapter","sessionHandle","index","metadataOffset","elementType","dimsCount","dims","symbolicDimNameOffset","model","modelDataOffset","modelData","modelDataLength","ioBindingHandle","inputNamesUTF8Encoded","outputNamesUTF8Encoded","loadingPromises","path","fileData","provider","webnnOptions","context","gpuDevice","inputCount","outputCount","enableGraphCapture","inputNames","outputNames","inputMetadata","outputMetadata","outputPreferredLocations","shape","nameString","buf","sessionId","ioBindingState","adapterData","adapterId","tensor","tensorHandles","tensorNameUTF8Encoded","dataType","actualLocation","rawData","dataByteLength","gpuBuffer","registerBuffer","mlTensor","registerMLTensor","isGraphInput","isGraphOutput","tensorName","dataTypeEnum","createTemporaryTensor","uploadTensor","tensorId","dimsOffset","d","inputIndices","inputTensors","outputIndices","outputTensors","loraAdapterIds","inputOutputBound","runOptionsAllocs","inputTensorHandles","outputTensorHandles","inputOutputAllocs","preAllocatedOutputs","beforeRunStack","inputValuesOffset","inputNamesOffset","outputValuesOffset","outputNamesOffset","output","outputPromises","beforeGetTensorDataStack","tensorDataOffset","keepOutputTensor","valueType","dimsLength","preferredLocation","stringData","nextOffset","maxBytesToRead","getBuffer","bufferSize","ensureTensor","isGraphInputOutputTypeSupported","result","typedArrayConstructor","v","p","count","profileFileName","initializeWebAssemblyAndOrtRuntime","initializeOrtEp","init_proxy_wrapper","pathOrBuffer","inputs","outputs","TRACE_FUNC_BEGIN","TRACE_FUNC_END","OnnxruntimeWebAssemblyLoraAdapterHandler","init_lora_adapter_handler","Tensor","encodeTensorMetadata","decodeTensorMetadata","OnnxruntimeWebAssemblySessionHandler","init_session_handler_inference","getName","download","dispose","feeds","fetches","activeLoraAdapters","adapter","inputArray","kvp","outputArray","t","results","resultMap","validateSessionOptions","init_validate_session_options","backend_wasm_exports","__export","OnnxruntimeWebAssemblyBackend","initializeFlags","wasmBackend","init_backend_wasm","simd","numCpuLogicalCores","backendName","ort","registerBackend","version","index_default"],"mappings":";;;;;;4vBAAA,IAGaA,EAHbC,GAAAC,EAAA,kBAGaF,EAAS,CAAC,EAAE,OAAO,QAAY,KAAe,QAAQ,UAAY,QAAQ,SAAS,QCHhG,IAWMG,GAgCOC,GAGPC,GAiDOC,EAOAC,GAUPC,GAaAC,GAaAC,GAcAC,GAeAC,GA2CAC,GA0BOC,GA5ObC,GAAAb,EAAA,kBAIAD,KAOME,GAASH,GAAU,OAAO,SAAa,IAAc,OAAY,SAAS,OAgCnEI,GACU,gBAAkC,SAAW,gBAAkC,QAEhGC,GAAe,IAA0B,CAE7C,GAAI,CAAAL,EAaF,IAAII,GAAsC,CAcxC,IAAMY,EAAO,IACb,OAAO,IAAI,IAAI,IAAIA,EAAK,mBAA4B,eAA8B,EAAE,KAAMb,EAAM,EAAE,IACpG,CAEA,OAAO,gBASX,EAOaG,EAAYD,GAAa,EAOzBE,GAAmC,IAA0B,CACxE,GAAID,GAAa,CAACA,EAAU,WAAW,OAAO,EAC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U,IAAI4N,GACpB,aAAM5N,EAAQ,UAAUkN,EAAcrN,CAAO,EACtCG,CACT,CACA,MAAM,yBAAyBkN,EAAgE,CAC7F,IAAMlN,EAAU,IAAIuN,EACpB,aAAMvN,EAAQ,YAAYkN,CAAY,EAC/BlN,CACT,CACF,EAEaiP,GAAc,IAAIF,KC9F/B,WAAc,qBACd,UAAYO,OAAS,qBAGrB,OAAS,mBAAAC,GAAiB,OAAAzI,OAAW,qBCP9B,IAAM0I,GAAU,SDKvB,IAAOC,GAAQH,GAwBe,CAC5B,IAAML,EAAc,cAA0B,YAO9CM,GAAgB,MAAON,EAAa,EAAE,EACtCM,GAAgB,OAAQN,EAAa,EAAE,CACzC,CAEA,OAAO,eAAenI,GAAI,SAAU,MAAO,CAAE,MAAO0I,GAAS,WAAY,EAAK,CAAC","sourcesContent":["// Copyright (c) Microsoft Corporation. All rights reserved.\n// Licensed under the MIT License.\n\nexport const isNode = !!(typeof process !== 'undefined' && process.versions && process.versions.node);\n","// Copyright (c) Microsoft Corporation. All rights reserved.\n// Licensed under the MIT License.\n\nimport type { OrtWasmModule } from './wasm-types';\nimport { isNode } from './wasm-utils-env';\n\n/**\n * The origin of the current location.\n *\n * In Node.js, this is undefined.\n */\nconst origin = isNode || typeof location === 'undefined' ? undefined : location.origin;\n\n/**\n * Some bundlers (eg. Webpack) will rewrite `import.meta.url` to a file URL at compile time.\n *\n * This function checks if `import.meta.url` starts with `file:`, but using the `>` and `<` operators instead of\n * `startsWith` function so that code minimizers can remove the dead code correctly.\n *\n * For example, if we use terser to minify the following code:\n * ```js\n * if (\"file://hard-coded-filename\".startsWith(\"file:\")) {\n *   console.log(1)\n * } else {\n *   console.log(2)\n * }\n *\n * if (\"file://hard-coded-filename\" > \"file:\" && \"file://hard-coded-filename\" < \"file;\") {\n *   console.log(3)\n * } else {\n *   console.log(4)\n * }\n * ```\n *\n * The minified code will be:\n * ```js\n * \"file://hard-coded-filename\".startsWith(\"file:\")?console.log(1):console.log(2),console.log(3);\n * ```\n *\n * (use Terser 5.39.0 with default options, https://try.terser.org/)\n *\n * @returns true if the import.meta.url is hardcoded as a file URI.\n */\nexport const isEsmImportMetaUrlHardcodedAsFileUri =\n  BUILD_DEFS.IS_ESM && BUILD_DEFS.ESM_IMPORT_META_URL! > 'file:' && BUILD_DEFS.ESM_IMPORT_META_URL! < 'file;';\n\nconst getScriptSrc = (): string | undefined => {\n  // if Nodejs, return undefined\n  if (isNode) {\n    return undefined;\n  }\n  // if It's ESM, use import.meta.url\n  if (BUILD_DEFS.IS_ESM) {\n    // For ESM, if the import.meta.url is a file URL, this usually means the bundler rewrites `import.meta.url` to\n    // the file path at compile time. In this case, this file path cannot be used to determine the runtime URL.\n    //\n    // We need to use the URL constructor like this:\n    // ```js\n    // new URL('actual-bundle-name.js', import.meta.url).href\n    // ```\n    // So that bundler can preprocess the URL correctly.\n    if (isEsmImportMetaUrlHardcodedAsFileUri) {\n      // if the rewritten URL is a relative path, we need to use the origin to resolve the URL.\n\n      // The following is a workaround for Vite.\n      //\n      // Vite uses a bundler(rollup/rolldown) that does not rewrite `import.meta.url` to a file URL. So in theory, this\n      // code path should not be executed in Vite. However, the bundler does not know it and it still try to load the\n      // following pattern:\n      // - `return new URL('filename', import.meta.url).href`\n      //\n      // By replacing the pattern above with the following code, we can skip the resource loading behavior:\n      // - `const URL2 = URL; return new URL2('filename', import.meta.url).href;`\n      //\n      // And it still works in Webpack.\n      const URL2 = URL;\n      return new URL(new URL2(BUILD_DEFS.BUNDLE_FILENAME, BUILD_DEFS.ESM_IMPORT_META_URL).href, origin).href;\n    }\n\n    return BUILD_DEFS.ESM_IMPORT_META_URL;\n  }\n\n  return typeof document !== 'undefined'\n    ? (document.currentScript as HTMLScriptElement)?.src\n    : // use `self.location.href` if available\n      typeof self !== 'undefined'\n      ? self.location?.href\n      : undefined;\n};\n\n/**\n * The classic script source URL. This is not always available in non ESModule environments.\n *\n * In Node.js, this is undefined.\n */\nexport const scriptSrc = getScriptSrc();\n\n/**\n * Infer the wasm path prefix from the script source URL.\n *\n * @returns The inferred wasm path prefix, or undefined if the script source URL is not available or is a blob URL.\n */\nexport const inferWasmPathPrefixFromScriptSrc = (): string | undefined => {\n  if (scriptSrc && !scriptSrc.startsWith('blob:')) {\n    return scriptSrc.substring(0, scriptSrc.lastIndexOf('/') + 1);\n  }\n  return undefined;\n};\n\n/**\n * Check if the given filename with prefix is from the same origin.\n */\nconst isSameOrigin = (filename: string, prefixOverride?: string) => {\n  try {\n    const baseUrl = prefixOverride ?? scriptSrc;\n    const url = baseUrl ? new URL(filename, baseUrl) : new URL(filename);\n    return url.origin === origin;\n  } catch {\n    return false;\n  }\n};\n\n/**\n * Normalize the inputs to an absolute URL with the given prefix override. If failed, return undefined.\n */\nconst normalizeUrl = (filename: string, prefixOverride?: string) => {\n  const baseUrl = prefixOverride ?? scriptSrc;\n  try {\n    const url = baseUrl ? new URL(filename, baseUrl) : new URL(filename);\n    return url.href;\n  } catch {\n    return undefined;\n  }\n};\n\n/**\n * Create a fallback URL if an absolute URL cannot be created by the normalizeUrl function.\n */\nconst fallbackUrl = (filename: string, prefixOverride?: string) => `${prefixOverride ?? './'}${filename}`;\n\n/**\n * This helper function is used to preload a module from a URL.\n *\n * If the origin of the worker URL is different from the current origin, the worker cannot be loaded directly.\n * See discussions in https://github.com/webpack-contrib/worker-loader/issues/154\n *\n * In this case, we will fetch the worker URL and create a new Blob URL with the same origin as a workaround.\n *\n * @param absoluteUrl - The absolute URL to preload.\n *\n * @returns - A promise that resolves to a new Blob URL\n */\nconst preload = async (absoluteUrl: string): Promise<string> => {\n  const response = await fetch(absoluteUrl, { credentials: 'same-origin' });\n  const blob = await response.blob();\n  return URL.createObjectURL(blob);\n};\n\n/**\n * This helper function is used to dynamically import a module from a URL.\n *\n * The build script has special handling for this function to ensure that the URL is not bundled into the final output.\n *\n * @param url - The URL to import.\n *\n * @returns - A promise that resolves to the default export of the module.\n */\nconst dynamicImportDefault = async <T>(url: string): Promise<T> =>\n  (await import(/* webpackIgnore: true */ /* @vite-ignore */ url)).default;\n\n/**\n * The proxy worker factory imported from the proxy worker module.\n *\n * This is only available when the WebAssembly proxy is not disabled.\n */\nconst createProxyWorker: ((urlOverride?: string) => Worker) | undefined =\n  // eslint-disable-next-line @typescript-eslint/no-require-imports, @typescript-eslint/no-var-requires\n  BUILD_DEFS.DISABLE_WASM_PROXY ? undefined : require('./proxy-worker/main').default;\n\n/**\n * Import the proxy worker.\n *\n * This function will perform the following steps:\n * 1. If a preload is needed, it will preload the module and return the object URL.\n * 2. Use the proxy worker factory to create the proxy worker.\n *\n * @returns - A promise that resolves to a tuple of 2 elements:\n *            - The object URL of the preloaded module, or undefined if no preload is needed.\n *            - The proxy worker.\n */\nexport const importProxyWorker = async (): Promise<[undefined | string, Worker]> => {\n  if (!scriptSrc) {\n    throw new Error('Failed to load proxy worker: cannot determine the script source URL.');\n  }\n\n  // If the script source is from the same origin, we can use the embedded proxy module directly.\n  if (isSameOrigin(scriptSrc)) {\n    return [undefined, createProxyWorker!()];\n  }\n\n  // Otherwise, need to preload\n  const url = await preload(scriptSrc);\n  return [url, createProxyWorker!(url)];\n};\n\n/**\n * The embedded WebAssembly module.\n *\n * This is only available in ESM and when embedding is not disabled.\n */\nconst embeddedWasmModule: EmscriptenModuleFactory<OrtWasmModule> | undefined =\n  BUILD_DEFS.IS_ESM && BUILD_DEFS.ENABLE_BUNDLE_WASM_JS\n    ? // eslint-disable-next-line @typescript-eslint/no-require-imports, @typescript-eslint/no-var-requires\n      require(\n        !BUILD_DEFS.DISABLE_JSEP\n          ? '../../dist/ort-wasm-simd-threaded.jsep.mjs'\n          : BUILD_DEFS.ENABLE_JSPI\n            ? '../../dist/ort-wasm-simd-threaded.jspi.mjs'\n            : !BUILD_DEFS.DISABLE_WEBGPU\n              ? '../../dist/ort-wasm-simd-threaded.asyncify.mjs'\n              : '../../dist/ort-wasm-simd-threaded.mjs',\n      ).default\n    : undefined;\n\n/**\n * Import the WebAssembly module.\n *\n * This function will perform the following steps:\n * 1. If the embedded module exists and no custom URL is specified, use the embedded module.\n * 2. If a preload is needed, it will preload the module and return the object URL.\n * 3. Otherwise, it will perform a dynamic import of the module.\n *\n * @returns - A promise that resolves to a tuple of 2 elements:\n *            - The object URL of the preloaded module, or undefined if no preload is needed.\n *            - The default export of the module, which is a factory function to create the WebAssembly module.\n */\nexport const importWasmModule = async (\n  urlOverride: string | undefined,\n  prefixOverride: string | undefined,\n  isMultiThreaded: boolean,\n  isWasmOverridden: boolean,\n): Promise<[undefined | string, EmscriptenModuleFactory<OrtWasmModule>]> => {\n  //\n  // Check if we should use the embedded module.\n  //\n\n  // To use the embedded module, it should be available, and no URL override or prefix override should be specified.\n  let useEmbeddedModule = embeddedWasmModule && !(urlOverride || prefixOverride);\n  if (useEmbeddedModule) {\n    if (!scriptSrc) {\n      // no URL info available.\n      //\n      // Note: when the embedded module is available, it means the current script is ESM. Usually, in ESM, the\n      // `import.meta.url` is available. But in some cases (eg. Cloudflare Workers), the value of `import.meta.url`\n      // can be `null` or `undefined`. In this case, we can only load the embedded module when:\n      //\n      // 1. The WebAssembly module binary is overridden:\n      //    ```js\n      //    env.wasm.wasmPaths = undefined;  // or not specified\n      //    env.wasm.wasmBinary = /* a Uint8Array containing the WebAssembly binary */;\n      //    ```\n      //\n      // 2. The \".wasm\" only is overridden.\n      //    ```js\n      //    env.wasm.wasmPaths = { wasm: /* URL of the .wasm file */ };\n      //    ```\n      //\n      if (isWasmOverridden && !isMultiThreaded) {\n        useEmbeddedModule = true;\n      } else {\n        throw new Error('cannot determine the script source URL.');\n      }\n    } else {\n      // if the script source is available, we can check if it is from the same origin.\n      // Also use the embedded module when wasmBinary is provided and single-threaded (eg. Blob URL workers\n      // where isSameOrigin fails but no file resolution or worker spawning is needed).\n      useEmbeddedModule = isSameOrigin(scriptSrc) || (isWasmOverridden && !isMultiThreaded);\n    }\n  }\n  if (useEmbeddedModule) {\n    return [undefined, embeddedWasmModule!];\n  } else {\n    const wasmModuleFilename = !BUILD_DEFS.DISABLE_JSEP\n      ? 'ort-wasm-simd-threaded.jsep.mjs'\n      : BUILD_DEFS.ENABLE_JSPI\n        ? 'ort-wasm-simd-threaded.jspi.mjs'\n        : !BUILD_DEFS.DISABLE_WEBGPU\n          ? 'ort-wasm-simd-threaded.asyncify.mjs'\n          : 'ort-wasm-simd-threaded.mjs';\n    const wasmModuleUrl = urlOverride ?? normalizeUrl(wasmModuleFilename, prefixOverride);\n    // need to preload if all of the following conditions are met:\n    // 1. not in Node.js.\n    //    - Node.js does not have the same origin policy for creating workers.\n    // 2. multi-threaded is enabled.\n    //    - If multi-threaded is disabled, no worker will be created. So we don't need to preload the module.\n    // 3. the absolute URL is available.\n    //    - If the absolute URL is failed to be created, the origin cannot be determined. In this case, we will not\n    //    preload the module.\n    // 4. the worker URL is not from the same origin.\n    //    - If the worker URL is from the same origin, we can create the worker directly.\n    const needPreload = !isNode && isMultiThreaded && wasmModuleUrl && !isSameOrigin(wasmModuleUrl, prefixOverride);\n    const url = needPreload\n      ? await preload(wasmModuleUrl)\n      : (wasmModuleUrl ?? fallbackUrl(wasmModuleFilename, prefixOverride));\n    return [needPreload ? url : undefined, await dynamicImportDefault<EmscriptenModuleFactory<OrtWasmModule>>(url)];\n  }\n};\n","// Copyright (c) Microsoft Corporation. All rights reserved.\n// Licensed under the MIT License.\n\nimport { Env } from 'onnxruntime-common';\n\nimport type { OrtWasmModule } from './wasm-types';\nimport { importWasmModule, inferWasmPathPrefixFromScriptSrc } from './wasm-utils-import';\n\nlet wasm: OrtWasmModule | undefined;\nlet initialized = false;\nlet initializing = false;\nlet aborted = false;\n\nconst isMultiThreadSupported = (): boolean => {\n  // If 'SharedArrayBuffer' is not available, WebAssembly threads will not work.\n  if (typeof SharedArrayBuffer === 'undefined') {\n    return false;\n  }\n\n  try {\n    // Test for transferability of SABs (for browsers. needed for Firefox)\n    // https://groups.google.com/forum/#!msg/mozilla.dev.platform/IHkBZlHETpA/dwsMNchWEQAJ\n    if (typeof MessageChannel !== 'undefined') {\n      new MessageChannel().port1.postMessage(new SharedArrayBuffer(1));\n    }\n\n    // Test for WebAssembly threads capability (for both browsers and Node.js)\n    // This typed array is a WebAssembly program containing threaded instructions.\n    return WebAssembly.validate(\n      new Uint8Array([\n        0, 97, 115, 109, 1, 0, 0, 0, 1, 4, 1, 96, 0, 0, 3, 2, 1, 0, 5, 4, 1, 3, 1, 1, 10, 11, 1, 9, 0, 65, 0, 254, 16,\n        2, 0, 26, 11,\n      ]),\n    );\n  } catch {\n    return false;\n  }\n};\n\nconst isSimdSupported = (): boolean => {\n  try {\n    // Test for WebAssembly SIMD capability (for both browsers and Node.js)\n    // This typed array is a WebAssembly program containing SIMD instructions.\n\n    // The binary data is generated from the following code by wat2wasm:\n    //\n    // (module\n    //   (type $t0 (func))\n    //   (func $f0 (type $t0)\n    //     (drop\n    //       (i32x4.dot_i16x8_s\n    //         (i8x16.splat\n    //           (i32.const 0))\n    //         (v128.const i32x4 0x00000000 0x00000000 0x00000000 0x00000000)))))\n\n    return WebAssembly.validate(\n      new Uint8Array([\n        0, 97, 115, 109, 1, 0, 0, 0, 1, 4, 1, 96, 0, 0, 3, 2, 1, 0, 10, 30, 1, 28, 0, 65, 0, 253, 15, 253, 12, 0, 0, 0,\n        0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 253, 186, 1, 26, 11,\n      ]),\n    );\n  } catch {\n    return false;\n  }\n};\n\nconst isRelaxedSimdSupported = (): boolean => {\n  try {\n    // Test for WebAssembly Relaxed SIMD capability (for both browsers and Node.js)\n    // This typed array is a WebAssembly program containing Relaxed SIMD instructions.\n\n    // The binary data is generated from the following code by wat2wasm:\n    // (module\n    //   (func (result v128)\n    //      i32.const 1\n    //      i8x16.splat\n    //      i32.const 2\n    //      i8x16.splat\n    //      i32.const 3\n    //      i8x16.splat\n    //      i32x4.relaxed_dot_i8x16_i7x16_add_s\n    //   )\n    //  )\n    return WebAssembly.validate(\n      new Uint8Array([\n        0, 97, 115, 109, 1, 0, 0, 0, 1, 5, 1, 96, 0, 1, 123, 3, 2, 1, 0, 10, 19, 1, 17, 0, 65, 1, 253, 15, 65, 2, 253,\n        15, 65, 3, 253, 15, 253, 147, 2, 11,\n      ]),\n    );\n  } catch {\n    return false;\n  }\n};\n\nexport const initializeWebAssembly = async (flags: Env.WebAssemblyFlags): Promise<void> => {\n  if (initialized) {\n    return Promise.resolve();\n  }\n  if (initializing) {\n    throw new Error(\"multiple calls to 'initializeWebAssembly()' detected.\");\n  }\n  if (aborted) {\n    throw new Error(\"previous call to 'initializeWebAssembly()' failed.\");\n  }\n\n  initializing = true;\n\n  // wasm flags are already initialized\n  const timeout = flags.initTimeout!;\n  let numThreads = flags.numThreads!;\n\n  // ensure SIMD is supported\n  if (flags.simd === false) {\n    // skip SIMD feature checking as it is disabled explicitly by user\n  } else if (flags.simd === 'relaxed') {\n    // check if relaxed SIMD is supported\n    if (!isRelaxedSimdSupported()) {\n      throw new Error('Relaxed WebAssembly SIMD is not supported in the current environment.');\n    }\n  } else if (!isSimdSupported()) {\n    throw new Error('WebAssembly SIMD is not supported in the current environment.');\n  }\n\n  if (BUILD_DEFS.ENABLE_JSPI) {\n    if (!('Suspending' in WebAssembly)) {\n      throw new Error('WebAssembly JSPI is not supported in the current environment.');\n    }\n  }\n\n  // check if multi-threading is supported\n  const multiThreadSupported = isMultiThreadSupported();\n  if (numThreads > 1 && !multiThreadSupported) {\n    if (typeof self !== 'undefined' && !self.crossOriginIsolated) {\n      // eslint-disable-next-line no-console\n      console.warn(\n        'env.wasm.numThreads is set to ' +\n          numThreads +\n          ', but this will not work unless you enable crossOriginIsolated mode. ' +\n          'See https://web.dev/cross-origin-isolation-guide/ for more info.',\n      );\n    }\n\n    // eslint-disable-next-line no-console\n    console.warn(\n      'WebAssembly multi-threading is not supported in the current environment. ' + 'Falling back to single-threading.',\n    );\n\n    // set flags.numThreads to 1 so that OrtInit() will not create a global thread pool.\n    flags.numThreads = numThreads = 1;\n  }\n\n  const wasmPaths = flags.wasmPaths;\n  const wasmPrefixOverride = typeof wasmPaths === 'string' ? wasmPaths : undefined;\n  const mjsPathOverrideFlag = (wasmPaths as Env.WasmFilePaths)?.mjs;\n  const mjsPathOverride = (mjsPathOverrideFlag as URL)?.href ?? mjsPathOverrideFlag;\n  const wasmPathOverrideFlag = (wasmPaths as Env.WasmFilePaths)?.wasm;\n  const wasmPathOverride = (wasmPathOverrideFlag as URL)?.href ?? wasmPathOverrideFlag;\n  const wasmBinaryOverride = flags.wasmBinary;\n\n  const [objectUrl, ortWasmFactory] = await importWasmModule(\n    mjsPathOverride,\n    wasmPrefixOverride,\n    numThreads > 1,\n    !!wasmBinaryOverride || !!wasmPathOverride,\n  );\n\n  let isTimeout = false;\n\n  const tasks: Array<Promise<void>> = [];\n\n  // promise for timeout\n  if (timeout > 0) {\n    tasks.push(\n      new Promise((resolve) => {\n        setTimeout(() => {\n          isTimeout = true;\n          resolve();\n        }, timeout);\n      }),\n    );\n  }\n\n  // promise for module initialization\n  tasks.push(\n    new Promise((resolve, reject) => {\n      const config: Partial<OrtWasmModule> = {\n        /**\n         * The number of threads. WebAssembly will create (Module.numThreads - 1) workers. If it is 1, no worker will be\n         * created.\n         */\n        numThreads,\n      };\n\n      if (wasmBinaryOverride) {\n        // Set a custom buffer which contains the WebAssembly binary. This will skip the wasm file fetching.\n        config.wasmBinary = wasmBinaryOverride as ArrayBuffer;\n\n        // Offer an implementation of locateFile() that returns the file name directly. This helps to avoid an error\n        // thrown later from the following code when `import.meta.url` is a blob URL:\n        // ```\n        //   return new URL(\"ort-wasm-simd-threaded.jsep.wasm\", import.meta.url).href;\n        // ```\n        config.locateFile = (fileName) => fileName;\n      } else if (wasmPathOverride || wasmPrefixOverride) {\n        // A callback function to locate the WebAssembly file. The function should return the full path of the file.\n        //\n        // Since Emscripten 3.1.58, this function is only called for the .wasm file.\n        config.locateFile = (fileName) => wasmPathOverride ?? wasmPrefixOverride + fileName;\n      } else if (mjsPathOverride && mjsPathOverride.indexOf('blob:') !== 0) {\n        // if mjs path is specified, use it as the base path for the .wasm file.\n        config.locateFile = (fileName) => new URL(fileName, mjsPathOverride).href;\n      } else if (objectUrl) {\n        const inferredWasmPathPrefix = inferWasmPathPrefixFromScriptSrc();\n        if (inferredWasmPathPrefix) {\n          // if the wasm module is preloaded, use the inferred wasm path as the base path for the .wasm file.\n          config.locateFile = (fileName) => inferredWasmPathPrefix + fileName;\n        }\n      }\n\n      ortWasmFactory(config).then(\n        // wasm module initialized successfully\n        (module) => {\n          initializing = false;\n          initialized = true;\n          wasm = module;\n          resolve();\n          if (objectUrl) {\n            URL.revokeObjectURL(objectUrl);\n          }\n        },\n        // wasm module failed to initialize\n        (what) => {\n          initializing = false;\n          aborted = true;\n          reject(what);\n        },\n      );\n    }),\n  );\n\n  await Promise.race(tasks);\n\n  if (isTimeout) {\n    throw new Error(`WebAssembly backend initializing failed due to timeout: ${timeout}ms`);\n  }\n};\n\nexport const getInstance = (): OrtWasmModule => {\n  if (initialized && wasm) {\n    return wasm;\n  }\n\n  throw new Error('WebAssembly is not initialized yet.');\n};\n\nexport const dispose = (): void => {\n  if (initialized && !initializing && !aborted) {\n    // TODO: currently \"PThread.terminateAllThreads()\" is not exposed in the wasm module.\n    //       And this function is not yet called by any code.\n    //       If it is needed in the future, we should expose it in the wasm module and uncomment the following line.\n\n    // wasm?.PThread?.terminateAllThreads();\n    wasm = undefined;\n\n    initializing = false;\n    initialized = false;\n    aborted = true;\n  }\n};\n","// Copyright (c) Microsoft Corporation. All rights reserved.\n// Licensed under the MIT License.\n\nimport { getInstance } from './wasm-factory';\n\nexport const allocWasmString = (data: string, allocs: number[]): number => {\n  const wasm = getInstance();\n\n  const dataLength = wasm.lengthBytesUTF8(data) + 1;\n  const dataOffset = wasm._malloc(dataLength);\n  wasm.stringToUTF8(data, dataOffset, dataLength);\n  allocs.push(dataOffset);\n\n  return dataOffset;\n};\n\ninterface ExtraOptionsHandler {\n  (name: string, value: string): void;\n}\n\nexport const iterateExtraOptions = (\n  options: Record<string, unknown>,\n  prefix: string,\n  seen: WeakSet<Record<string, unknown>>,\n  handler: ExtraOptionsHandler,\n): void => {\n  if (typeof options == 'object' && options !== null) {\n    if (seen.has(options)) {\n      throw new Error('Circular reference in options');\n    } else {\n      seen.add(options);\n    }\n  }\n\n  Object.entries(options).forEach(([key, value]) => {\n    const name = prefix ? prefix + key : key;\n    if (typeof value === 'object') {\n      iterateExtraOptions(value as Record<string, unknown>, name + '.', seen, handler);\n    } else if (typeof value === 'string' || typeof value === 'number') {\n      handler(name, value.toString());\n    } else if (typeof value === 'boolean') {\n      handler(name, value ? '1' : '0');\n    } else {\n      throw new Error(`Can't handle extra config type: ${typeof value}`);\n    }\n  });\n};\n\n/**\n * check web assembly API's last error and throw error if any error occurred.\n * @param message a message used when an error occurred.\n */\nexport const checkLastError = (message: string): void => {\n  const wasm = getInstance();\n\n  const stack = wasm.stackSave();\n  try {\n    const ptrSize = wasm.PTR_SIZE;\n    const paramsOffset = wasm.stackAlloc(2 * ptrSize);\n    wasm._OrtGetLastError(paramsOffset, paramsOffset + ptrSize);\n    const errorCode = Number(wasm.getValue(paramsOffset, ptrSize === 4 ? 'i32' : 'i64'));\n    const errorMessagePointer = wasm.getValue(paramsOffset + ptrSize, '*');\n    const errorMessage = errorMessagePointer ? wasm.UTF8ToString(errorMessagePointer) : '';\n    throw new Error(`${message} ERROR_CODE: ${errorCode}, ERROR_MESSAGE: ${errorMessage}`);\n  } finally {\n    wasm.stackRestore(stack);\n  }\n};\n","// Copyright (c) Microsoft Corporation. All rights reserved.\n// Licensed under the MIT License.\n\nimport { InferenceSession } from 'onnxruntime-common';\n\nimport { getInstance } from './wasm-factory';\nimport { allocWasmString, checkLastError, iterateExtraOptions } from './wasm-utils';\n\nexport const setRunOptions = (\n  options: InferenceSession.RunOptions,\n  loraAdapterHandles: readonly number[],\n): [number, number[]] => {\n  const wasm = getInstance();\n  let runOptionsHandle = 0;\n  const allocs: number[] = [];\n\n  const runOptions: InferenceSession.RunOptions = options || {};\n\n  try {\n    if (options?.logSeverityLevel === undefined) {\n      runOptions.logSeverityLevel = 2; // Default to warning\n    } else if (\n      typeof options.logSeverityLevel !== 'number' ||\n      !Number.isInteger(options.logSeverityLevel) ||\n      options.logSeverityLevel < 0 ||\n      options.logSeverityLevel > 4\n    ) {\n      throw new Error(`log severity level is not valid: ${options.logSeverityLevel}`);\n    }\n\n    if (options?.logVerbosityLevel === undefined) {\n      runOptions.logVerbosityLevel = 0; // Default to 0\n    } else if (typeof options.logVerbosityLevel !== 'number' || !Number.isInteger(options.logVerbosityLevel)) {\n      throw new Error(`log verbosity level is not valid: ${options.logVerbosityLevel}`);\n    }\n\n    if (options?.terminate === undefined) {\n      runOptions.terminate = false;\n    }\n\n    let tagDataOffset = 0;\n    if (options?.tag !== undefined) {\n      tagDataOffset = allocWasmString(options.tag, allocs);\n    }\n\n    runOptionsHandle = wasm._OrtCreateRunOptions(\n      runOptions.logSeverityLevel!,\n      runOptions.logVerbosityLevel!,\n      !!runOptions.terminate!,\n      tagDataOffset,\n    );\n    if (runOptionsHandle === 0) {\n      checkLastError(\"Can't create run options.\");\n    }\n\n    if (options?.extra !== undefined) {\n      iterateExtraOptions(options.extra, '', new WeakSet<Record<string, unknown>>(), (key, value) => {\n        const keyDataOffset = allocWasmString(key, allocs);\n        const valueDataOffset = allocWasmString(value, allocs);\n\n        if (wasm._OrtAddRunConfigEntry(runOptionsHandle, keyDataOffset, valueDataOffset) !== 0) {\n          checkLastError(`Can't set a run config entry: ${key} - ${value}.`);\n        }\n      });\n    }\n\n    for (const adapterHandle of loraAdapterHandles) {\n      if (wasm._OrtRunOptionsAddActiveLoraAdapter(runOptionsHandle, adapterHandle) !== 0) {\n        checkLastError(\"Can't add an active LoRA adapter.\");\n      }\n    }\n\n    return [runOptionsHandle, allocs];\n  } catch (e) {\n    if (runOptionsHandle !== 0) {\n      wasm._OrtReleaseRunOptions(runOptionsHandle);\n    }\n    allocs.forEach((alloc) => wasm._free(alloc));\n    throw e;\n  }\n};\n","// Copyright (c) Microsoft Corporation. All rights reserved.\n// Licensed under the MIT License.\n\nimport type { InferenceSession } from 'onnxruntime-common';\n\nimport { getInstance } from './wasm-factory';\nimport { allocWasmString, checkLastError, iterateExtraOptions } from './wasm-utils';\n\nconst getGraphOptimzationLevel = (graphOptimizationLevel: string | unknown): number => {\n  switch (graphOptimizationLevel) {\n    case 'disabled':\n      return 0;\n    case 'basic':\n      return 1;\n    case 'extended':\n      return 2;\n    case 'layout':\n      return 3;\n    case 'all':\n      return 99;\n    default:\n      throw new Error(`unsupported graph optimization level: ${graphOptimizationLevel}`);\n  }\n};\n\nconst getExecutionMode = (executionMode: 'sequential' | 'parallel'): number => {\n  switch (executionMode) {\n    case 'sequential':\n      return 0;\n    case 'parallel':\n      return 1;\n    default:\n      throw new Error(`unsupported execution mode: ${executionMode}`);\n  }\n};\n\nconst appendDefaultOptions = (options: InferenceSession.SessionOptions): void => {\n  if (!options.extra) {\n    options.extra = {};\n  }\n  if (!options.extra.session) {\n    options.extra.session = {};\n  }\n  const session = options.extra.session as Record<string, string>;\n  if (!session.use_ort_model_bytes_directly) {\n    // eslint-disable-next-line camelcase\n    session.use_ort_model_bytes_directly = '1';\n  }\n\n  // if using JSEP with WebGPU, always disable memory pattern\n  if (\n    options.executionProviders &&\n    options.executionProviders.some((ep) => (typeof ep === 'string' ? ep : ep.name) === 'webgpu')\n  ) {\n    options.enableMemPattern = false;\n  }\n};\n\nconst appendSessionConfig = (sessionOptionsHandle: number, key: string, value: string, allocs: number[]): void => {\n  const keyDataOffset = allocWasmString(key, allocs);\n  const valueDataOffset = allocWasmString(value, allocs);\n  if (getInstance()._OrtAddSessionConfigEntry(sessionOptionsHandle, keyDataOffset, valueDataOffset) !== 0) {\n    checkLastError(`Can't set a session config entry: ${key} - ${value}.`);\n  }\n};\n\nconst appendEpOption = (epOptions: Array<[number, number]>, key: string, value: string, allocs: number[]): void => {\n  const keyDataOffset = allocWasmString(key, allocs);\n  const valueDataOffset = allocWasmString(value, allocs);\n  epOptions.push([keyDataOffset, valueDataOffset]);\n};\n\n// OrtErrorCode values are part of the public C API ABI.\nconst ORT_NOT_IMPLEMENTED = 9;\n\n/**\n * Get the OrtEpDevice instances registered with the environment, grouped by execution provider name.\n *\n * An execution provider may register more than one device, e.g. one per GPU, and all of them share its name.\n *\n * @returns a map of execution provider name to the OrtEpDevice pointers registered under it, or undefined if the\n * build does not support the EP device API.\n */\nconst getEpDevicesByEpName = (): Map<string, number[]> | undefined => {\n  const wasm = getInstance();\n  const stack = wasm.stackSave();\n  try {\n    const epDevicesPtr = wasm.stackAlloc(wasm.PTR_SIZE);\n    const numEpDevicesPtr = wasm.stackAlloc(wasm.PTR_SIZE);\n    const errorCode = wasm._OrtGetEpDevices(epDevicesPtr, numEpDevicesPtr);\n    if (errorCode === ORT_NOT_IMPLEMENTED) {\n      return undefined;\n    }\n    if (errorCode !== 0) {\n      checkLastError(\"Can't get execution provider devices.\");\n    }\n    // The array is owned by the environment, so only the pointers are read out here.\n    // getValue() with '*' returns a BigInt in a wasm64 build, so convert before doing pointer arithmetic.\n    const epDevices = Number(wasm.getValue(epDevicesPtr, '*'));\n    const numEpDevices = Number(wasm.getValue(numEpDevicesPtr, '*'));\n\n    const epDevicesByEpName = new Map<string, number[]>();\n    for (let i = 0; i < numEpDevices; i++) {\n      const epDevice = Number(wasm.getValue(epDevices + i * wasm.PTR_SIZE, '*'));\n      const epName = wasm.UTF8ToString(wasm._OrtEpDevice_EpName(epDevice));\n      const devices = epDevicesByEpName.get(epName);\n      if (devices) {\n        devices.push(epDevice);\n      } else {\n        epDevicesByEpName.set(epName, [epDevice]);\n      }\n    }\n    return epDevicesByEpName;\n  } finally {\n    wasm.stackRestore(stack);\n  }\n};\n\nconst setExecutionProviders = async (\n  sessionOptionsHandle: number,\n  sessionOptions: InferenceSession.SessionOptions,\n  allocs: number[],\n): Promise<void> => {\n  const executionProviders = sessionOptions.executionProviders!;\n  for (const ep of executionProviders) {\n    let epName = typeof ep === 'string' ? ep : ep.name;\n    const epOptions: Array<[number, number]> = [];\n    let selectedEpDevices: number[] | undefined;\n\n    // check EP name\n    switch (epName) {\n      case 'webnn':\n        epName = 'WEBNN';\n        // Disable QDQ fusion so DQ/Q nodes are preserved as individual ops for WebNN EP.\n        appendSessionConfig(sessionOptionsHandle, 'session.disable_quant_qdq', '1', allocs);\n        // Forcibly prevent constant folding from replacing DQ nodes with constants.\n        appendSessionConfig(sessionOptionsHandle, 'session.disable_qdq_constant_folding', '1', allocs);\n        if (typeof ep !== 'string') {\n          const webnnOptions = ep as InferenceSession.WebNNExecutionProviderOption;\n          // const context = (webnnOptions as InferenceSession.WebNNOptionsWithMLContext)?.context;\n          const deviceType = (webnnOptions as InferenceSession.WebNNContextOptions)?.deviceType;\n          if (deviceType) {\n            appendSessionConfig(sessionOptionsHandle, 'deviceType', deviceType, allocs);\n          }\n        }\n        break;\n      case 'webgpu':\n        if (!BUILD_DEFS.DISABLE_WEBGPU) {\n          epName = 'WebGPU';\n          const epDevicesByEpName = getEpDevicesByEpName();\n          if (epDevicesByEpName !== undefined) {\n            // Non-minimal builds select by OrtEpDevice under the EP's canonical name. Minimal builds do not support\n            // the EP device API and continue to use the built-in EP name table.\n            epName = 'WebGpuExecutionProvider';\n            selectedEpDevices = epDevicesByEpName.get(epName);\n            if (selectedEpDevices === undefined) {\n              const registered = [...epDevicesByEpName.keys()].join(', ') || '(none)';\n              throw new Error(`no execution provider device is registered for: ${epName}. registered: ${registered}.`);\n            }\n          }\n          let customDevice: GPUDevice | undefined;\n\n          if (typeof ep !== 'string') {\n            const webgpuOptions = ep as InferenceSession.WebGpuExecutionProviderOption;\n\n            // set custom GPU device\n            if (webgpuOptions.device) {\n              if (typeof GPUDevice !== 'undefined' && webgpuOptions.device instanceof GPUDevice) {\n                customDevice = webgpuOptions.device;\n              } else {\n                throw new Error('Invalid GPU device set in WebGPU EP options.');\n              }\n            }\n\n            // set graph capture option from session options\n            const { enableGraphCapture } = sessionOptions;\n            if (typeof enableGraphCapture === 'boolean' && enableGraphCapture) {\n              appendEpOption(epOptions, 'enableGraphCapture', '1', allocs);\n            }\n\n            // set layout option\n            if (typeof webgpuOptions.preferredLayout === 'string') {\n              appendEpOption(epOptions, 'preferredLayout', webgpuOptions.preferredLayout, allocs);\n            }\n\n            // set force CPU fallback nodes\n            if (webgpuOptions.forceCpuNodeNames) {\n              const names = Array.isArray(webgpuOptions.forceCpuNodeNames)\n                ? webgpuOptions.forceCpuNodeNames\n                : [webgpuOptions.forceCpuNodeNames];\n\n              appendEpOption(epOptions, 'forceCpuNodeNames', names.join('\\n'), allocs);\n            }\n\n            // set validation mode\n            if (webgpuOptions.validationMode) {\n              appendEpOption(epOptions, 'validationMode', webgpuOptions.validationMode, allocs);\n            }\n\n            // set f32 accumulation for the MatMulNBits kernels\n            if (typeof webgpuOptions.enableMatmulFp32Accumulation === 'boolean') {\n              appendEpOption(\n                epOptions,\n                'enableMatmulFp32Accumulation',\n                webgpuOptions.enableMatmulFp32Accumulation ? '1' : '0',\n                allocs,\n              );\n            }\n\n            // set buffer cache modes\n            for (const key of [\n              'storageBufferCacheMode',\n              'uniformBufferCacheMode',\n              'queryResolveBufferCacheMode',\n              'defaultBufferCacheMode',\n            ] as const) {\n              const mode = webgpuOptions[key];\n              if (mode) {\n                if (mode !== 'disabled' && mode !== 'lazyRelease' && mode !== 'simple' && mode !== 'bucket') {\n                  throw new Error(`${key} must be one of 'disabled', 'lazyRelease', 'simple' or 'bucket': ${mode}`);\n                }\n                appendEpOption(epOptions, key, mode, allocs);\n              }\n            }\n          }\n\n          const info = getInstance().webgpuRegisterDevice!(customDevice);\n          if (info) {\n            const [deviceId, instanceHandle, deviceHandle] = info;\n            appendEpOption(epOptions, 'deviceId', deviceId.toString(), allocs);\n            appendEpOption(epOptions, 'webgpuInstance', instanceHandle.toString(), allocs);\n            appendEpOption(epOptions, 'webgpuDevice', deviceHandle.toString(), allocs);\n          }\n        } else {\n          epName = 'JS';\n          if (typeof ep !== 'string') {\n            const webgpuOptions = ep as InferenceSession.WebGpuExecutionProviderOption;\n            if (webgpuOptions?.preferredLayout) {\n              if (webgpuOptions.preferredLayout !== 'NCHW' && webgpuOptions.preferredLayout !== 'NHWC') {\n                throw new Error(`preferredLayout must be either 'NCHW' or 'NHWC': ${webgpuOptions.preferredLayout}`);\n              }\n              appendSessionConfig(sessionOptionsHandle, 'preferredLayout', webgpuOptions.preferredLayout, allocs);\n            }\n          }\n        }\n        break;\n      case 'wasm':\n      case 'cpu':\n        continue;\n      default:\n        throw new Error(`not supported execution provider: ${epName}`);\n    }\n\n    const epOptionsCount = epOptions.length;\n    let keysOffset = 0;\n    let valuesOffset = 0;\n    if (epOptionsCount > 0) {\n      keysOffset = getInstance()._malloc(epOptionsCount * getInstance().PTR_SIZE);\n      allocs.push(keysOffset);\n      valuesOffset = getInstance()._malloc(epOptionsCount * getInstance().PTR_SIZE);\n      allocs.push(valuesOffset);\n      for (let i = 0; i < epOptionsCount; i++) {\n        getInstance().setValue(keysOffset + i * getInstance().PTR_SIZE, epOptions[i][0], '*');\n        getInstance().setValue(valuesOffset + i * getInstance().PTR_SIZE, epOptions[i][1], '*');\n      }\n    }\n\n    let appendErrorCode: number;\n    if (selectedEpDevices !== undefined) {\n      // Select a single OrtEpDevice, even though more than one may match the EP name.\n      //\n      // Necessary: the WebGPU EP backs a session with one Dawn device, so its factory rejects any device\n      // count other than 1 (see WebGpuEpFactory::CreateIExecutionProvider for the built-in EP and\n      // Factory::CreateEpImpl in core/providers/webgpu/ep/factory.cc for the plugin EP).\n      //\n      // Safe to take the first: the factory reads nothing from the device except whether it is virtual, and\n      // Emscripten device discovery reports a single GPU entry derived from navigator.gpu, so there is at\n      // most one real candidate. Which GPU is used is decided by the adapter ORT Web hands to Dawn, not by\n      // this device (see env.webgpu.adapter and the WebGPU EP `device` option). A second entry only appears\n      // when virtual devices are enabled, and the factory registers those after the real ones, so the first\n      // is still a real device. Should that order ever change, EP creation fails with an explicit\n      // \"selected on a virtual GPU device\" error rather than silently running on the wrong device.\n      const epDevicesOffset = getInstance()._malloc(getInstance().PTR_SIZE);\n      allocs.push(epDevicesOffset);\n      getInstance().setValue(epDevicesOffset, selectedEpDevices[0], '*');\n\n      appendErrorCode = await getInstance()._OrtAppendExecutionProviderV2(\n        sessionOptionsHandle,\n        epDevicesOffset,\n        1,\n        keysOffset,\n        valuesOffset,\n        epOptionsCount,\n      );\n    } else {\n      const epNameDataOffset = allocWasmString(epName, allocs);\n      appendErrorCode = await getInstance()._OrtAppendExecutionProvider(\n        sessionOptionsHandle,\n        epNameDataOffset,\n        keysOffset,\n        valuesOffset,\n        epOptionsCount,\n      );\n    }\n\n    if (appendErrorCode !== 0) {\n      checkLastError(`Can't append execution provider: ${epName}.`);\n    }\n  }\n};\n\nexport const setSessionOptions = async (options?: InferenceSession.SessionOptions): Promise<[number, number[]]> => {\n  const wasm = getInstance();\n  let sessionOptionsHandle = 0;\n  const allocs: number[] = [];\n\n  const sessionOptions: InferenceSession.SessionOptions = options || {};\n  appendDefaultOptions(sessionOptions);\n\n  try {\n    const graphOptimizationLevel = getGraphOptimzationLevel(sessionOptions.graphOptimizationLevel ?? 'all');\n    const executionMode = getExecutionMode(sessionOptions.executionMode ?? 'sequential');\n    const logIdDataOffset =\n      typeof sessionOptions.logId === 'string' ? allocWasmString(sessionOptions.logId, allocs) : 0;\n\n    const logSeverityLevel = sessionOptions.logSeverityLevel ?? 2; // Default to 2 - warning\n    if (!Number.isInteger(logSeverityLevel) || logSeverityLevel < 0 || logSeverityLevel > 4) {\n      throw new Error(`log severity level is not valid: ${logSeverityLevel}`);\n    }\n\n    const logVerbosityLevel = sessionOptions.logVerbosityLevel ?? 0; // Default to 0 - verbose\n    if (!Number.isInteger(logVerbosityLevel) || logVerbosityLevel < 0 || logVerbosityLevel > 4) {\n      throw new Error(`log verbosity level is not valid: ${logVerbosityLevel}`);\n    }\n\n    const optimizedModelFilePathOffset =\n      typeof sessionOptions.optimizedModelFilePath === 'string'\n        ? allocWasmString(sessionOptions.optimizedModelFilePath, allocs)\n        : 0;\n\n    sessionOptionsHandle = wasm._OrtCreateSessionOptions(\n      graphOptimizationLevel,\n      !!sessionOptions.enableCpuMemArena,\n      !!sessionOptions.enableMemPattern,\n      executionMode,\n      !!sessionOptions.enableProfiling,\n      0,\n      logIdDataOffset,\n      logSeverityLevel,\n      logVerbosityLevel,\n      optimizedModelFilePathOffset,\n    );\n    if (sessionOptionsHandle === 0) {\n      checkLastError(\"Can't create session options.\");\n    }\n\n    if (sessionOptions.executionProviders) {\n      await setExecutionProviders(sessionOptionsHandle, sessionOptions, allocs);\n    }\n\n    if (sessionOptions.enableGraphCapture !== undefined) {\n      if (typeof sessionOptions.enableGraphCapture !== 'boolean') {\n        throw new Error(`enableGraphCapture must be a boolean value: ${sessionOptions.enableGraphCapture}`);\n      }\n      appendSessionConfig(\n        sessionOptionsHandle,\n        'enableGraphCapture',\n        sessionOptions.enableGraphCapture.toString(),\n        allocs,\n      );\n    }\n\n    if (sessionOptions.freeDimensionOverrides) {\n      for (const [name, value] of Object.entries(sessionOptions.freeDimensionOverrides)) {\n        if (typeof name !== 'string') {\n          throw new Error(`free dimension override name must be a string: ${name}`);\n        }\n        if (typeof value !== 'number' || !Number.isInteger(value) || value < 0) {\n          throw new Error(`free dimension override value must be a non-negative integer: ${value}`);\n        }\n        const nameOffset = allocWasmString(name, allocs);\n        if (wasm._OrtAddFreeDimensionOverride(sessionOptionsHandle, nameOffset, value) !== 0) {\n          checkLastError(`Can't set a free dimension override: ${name} - ${value}.`);\n        }\n      }\n    }\n\n    if (sessionOptions.extra !== undefined) {\n      iterateExtraOptions(sessionOptions.extra, '', new WeakSet<Record<string, unknown>>(), (key, value) => {\n        appendSessionConfig(sessionOptionsHandle, key, value, allocs);\n      });\n    }\n\n    return [sessionOptionsHandle, allocs];\n  } catch (e) {\n    if (sessionOptionsHandle !== 0) {\n      if (wasm._OrtReleaseSessionOptions(sessionOptionsHandle) !== 0) {\n        checkLastError(\"Can't release session options.\");\n      }\n    }\n    allocs.forEach((alloc) => wasm._free(alloc));\n    throw e;\n  }\n};\n","// Copyright (c) Microsoft Corporation. All rights reserved.\n// Licensed under the MIT License.\n\nimport { Tensor } from 'onnxruntime-common';\n\n// This file includes common definitions. They do NOT have dependency on the WebAssembly instance.\n\n/**\n * Copied from ONNX definition. Use this to drop dependency 'onnx_proto' to decrease compiled .js file size.\n */\nexport const enum DataType {\n  undefined = 0,\n  float = 1,\n  uint8 = 2,\n  int8 = 3,\n  uint16 = 4,\n  int16 = 5,\n  int32 = 6,\n  int64 = 7,\n  string = 8,\n  bool = 9,\n  float16 = 10,\n  double = 11,\n  uint32 = 12,\n  uint64 = 13,\n  complex64 = 14,\n  complex128 = 15,\n  bfloat16 = 16,\n\n  // 4-bit data-types\n  uint4 = 21,\n  int4 = 22,\n}\n\n/**\n * Map string tensor data to enum value\n */\nexport const tensorDataTypeStringToEnum = (type: string): DataType => {\n  switch (type) {\n    case 'int8':\n      return DataType.int8;\n    case 'uint8':\n      return DataType.uint8;\n    case 'bool':\n      return DataType.bool;\n    case 'int16':\n      return DataType.int16;\n    case 'uint16':\n      return DataType.uint16;\n    case 'int32':\n      return DataType.int32;\n    case 'uint32':\n      return DataType.uint32;\n    case 'float16':\n      return DataType.float16;\n    case 'float32':\n      return DataType.float;\n    case 'float64':\n      return DataType.double;\n    case 'string':\n      return DataType.string;\n    case 'int64':\n      return DataType.int64;\n    case 'uint64':\n      return DataType.uint64;\n    case 'int4':\n      return DataType.int4;\n    case 'uint4':\n      return DataType.uint4;\n\n    default:\n      throw new Error(`unsupported data type: ${type}`);\n  }\n};\n\n/**\n * Map enum value to string tensor data\n */\nexport const tensorDataTypeEnumToString = (typeProto: DataType): Tensor.Type => {\n  switch (typeProto) {\n    case DataType.int8:\n      return 'int8';\n    case DataType.uint8:\n      return 'uint8';\n    case DataType.bool:\n      return 'bool';\n    case DataType.int16:\n      return 'int16';\n    case DataType.uint16:\n      return 'uint16';\n    case DataType.int32:\n      return 'int32';\n    case DataType.uint32:\n      return 'uint32';\n    case DataType.float16:\n      return 'float16';\n    case DataType.float:\n      return 'float32';\n    case DataType.double:\n      return 'float64';\n    case DataType.string:\n      return 'string';\n    case DataType.int64:\n      return 'int64';\n    case DataType.uint64:\n      return 'uint64';\n    case DataType.int4:\n      return 'int4';\n    case DataType.uint4:\n      return 'uint4';\n\n    default:\n      throw new Error(`unsupported data type: ${typeProto}`);\n  }\n};\n\n/**\n * get tensor size in bytes by the given data type and dimensions\n * @returns size in integer or undefined if the data type is not supported\n */\nexport const calculateTensorSizeInBytes = (\n  dateType: number,\n  dimsOrSize: readonly number[] | number,\n): number | undefined => {\n  const elementSize = [\n    -1, // undefined = 0\n    4, // float = 1\n    1, // uint8 = 2\n    1, // int8 = 3\n    2, // uint16 = 4\n    2, // int16 = 5\n    4, // int32 = 6\n    8, // int64 = 7\n    -1, // string = 8\n    1, // bool = 9\n    2, // float16 = 10\n    8, // double = 11\n    4, // uint32 = 12\n    8, // uint64 = 13\n    -1, // complex64 = 14\n    -1, // complex128 = 15\n    -1, // bfloat16 = 16\n    -1, // FLOAT8E4M3FN = 17\n    -1, // FLOAT8E4M3FNUZ = 18\n    -1, // FLOAT8E5M2 = 19\n    -1, // FLOAT8E5M2FNUZ = 20\n    0.5, // uint4 = 21\n    0.5, // int4 = 22\n  ][dateType];\n\n  const size = typeof dimsOrSize === 'number' ? dimsOrSize : dimsOrSize.reduce((a, b) => a * b, 1);\n  return elementSize > 0 ? Math.ceil(size * elementSize) : undefined;\n};\n\n/**\n * get typed array constructor by the given tensor type\n */\nexport const tensorTypeToTypedArrayConstructor = (\n  type: Tensor.Type,\n):\n  | Float32ArrayConstructor\n  | Uint8ArrayConstructor\n  | Int8ArrayConstructor\n  | Uint16ArrayConstructor\n  | Int16ArrayConstructor\n  | Int32ArrayConstructor\n  | BigInt64ArrayConstructor\n  | Uint8ArrayConstructor\n  | Float64ArrayConstructor\n  | Uint32ArrayConstructor\n  | BigUint64ArrayConstructor => {\n  switch (type) {\n    case 'float16':\n      // Float16 tensor data is stored as raw 16-bit values. Prefer a native or polyfilled Float16Array when\n      // available so callers can work with float16 values directly; otherwise fall back to Uint16Array storage.\n      return typeof Float16Array !== 'undefined' ? (Float16Array as unknown as Uint16ArrayConstructor) : Uint16Array;\n    case 'float32':\n      return Float32Array;\n    case 'uint8':\n      return Uint8Array;\n    case 'int8':\n      return Int8Array;\n    case 'uint16':\n      return Uint16Array;\n    case 'int16':\n      return Int16Array;\n    case 'int32':\n      return Int32Array;\n    case 'bool':\n      return Uint8Array;\n    case 'float64':\n      return Float64Array;\n    case 'uint32':\n      return Uint32Array;\n    case 'int64':\n      return BigInt64Array;\n    case 'uint64':\n      return BigUint64Array;\n    default:\n      throw new Error(`unsupported type: ${type}`);\n  }\n};\n\n/**\n * Map string log level to integer value\n */\nexport const logLevelStringToEnum = (logLevel?: 'verbose' | 'info' | 'warning' | 'error' | 'fatal'): number => {\n  switch (logLevel) {\n    case 'verbose':\n      return 0;\n    case 'info':\n      return 1;\n    case 'warning':\n      return 2;\n    case 'error':\n      return 3;\n    case 'fatal':\n      return 4;\n    default:\n      throw new Error(`unsupported logging level: ${logLevel}`);\n  }\n};\n\n/**\n * Check whether the given tensor type is supported by GPU buffer\n */\nexport const isGpuBufferSupportedType = (type: Tensor.Type): type is Tensor.GpuBufferDataTypes =>\n  type === 'float32' ||\n  type === 'float16' ||\n  type === 'int32' ||\n  type === 'int64' ||\n  type === 'uint32' ||\n  type === 'uint8' ||\n  type === 'bool' ||\n  type === 'uint4' ||\n  type === 'int4';\n\n/**\n * Check whether the given tensor type is supported by WebNN MLTensor\n */\nexport const isMLTensorSupportedType = (type: Tensor.Type): type is Tensor.MLTensorDataTypes =>\n  type === 'float32' ||\n  type === 'float16' ||\n  type === 'int32' ||\n  type === 'int64' ||\n  type === 'uint32' ||\n  type === 'uint64' ||\n  type === 'int8' ||\n  type === 'uint8' ||\n  type === 'bool' ||\n  type === 'uint4' ||\n  type === 'int4';\n\n/**\n * Map string data location to integer value\n */\nexport const dataLocationStringToEnum = (location: Tensor.DataLocation): number => {\n  switch (location) {\n    case 'none':\n      return 0;\n    case 'cpu':\n      return 1;\n    case 'cpu-pinned':\n      return 2;\n    case 'texture':\n      return 3;\n    case 'gpu-buffer':\n      return 4;\n    case 'ml-tensor':\n      return 5;\n    default:\n      throw new Error(`unsupported data location: ${location}`);\n  }\n};\n\n/**\n * Map integer data location to string value\n */\nexport const dataLocationEnumToString = (location: number): Tensor.DataLocation | undefined =>\n  (['none', 'cpu', 'cpu-pinned', 'texture', 'gpu-buffer', 'ml-tensor'] as const)[location];\n","// Copyright (c) Microsoft Corporation. All rights reserved.\n// Licensed under the MIT License.\n\nimport { isNode } from './wasm-utils-env';\n\n/**\n * Load a file into a Uint8Array.\n *\n * @param file - the file to load. Can be a URL/path, a Blob, an ArrayBuffer, or a Uint8Array.\n * @returns a Uint8Array containing the file data.\n */\nexport const loadFile = async (file: string | Blob | ArrayBufferLike | Uint8Array): Promise<Uint8Array> => {\n  if (typeof file === 'string') {\n    if (isNode) {\n      // load file into ArrayBuffer in Node.js\n      try {\n        const { readFile } = require('node:fs/promises');\n        return new Uint8Array(await readFile(file));\n      } catch (e) {\n        if (e.code === 'ERR_FS_FILE_TOO_LARGE') {\n          // file is too large, use fs.createReadStream instead\n          const { createReadStream } = require('node:fs');\n          const stream = createReadStream(file);\n          const chunks: Uint8Array[] = [];\n          for await (const chunk of stream) {\n            chunks.push(chunk);\n          }\n          return new Uint8Array(Buffer.concat(chunks));\n        }\n        throw e;\n      }\n    } else {\n      // load file into ArrayBuffer in browsers\n      const response = await fetch(file);\n      if (!response.ok) {\n        throw new Error(`failed to load external data file: ${file}`);\n      }\n      const contentLengthHeader = response.headers.get('Content-Length');\n      const fileSize = contentLengthHeader ? parseInt(contentLengthHeader, 10) : 0;\n      if (fileSize < 1073741824 /* 1GB */) {\n        // when Content-Length header is not set, we cannot determine the file size. We assume it is small enough to\n        // load into memory.\n        return new Uint8Array(await response.arrayBuffer());\n      } else {\n        // file is too large, use stream instead\n        if (!response.body) {\n          throw new Error(`failed to load external data file: ${file}, no response body.`);\n        }\n        const reader = response.body.getReader();\n\n        let buffer;\n        try {\n          // try to create ArrayBuffer directly\n          buffer = new ArrayBuffer(fileSize);\n        } catch (e) {\n          if (e instanceof RangeError) {\n            // use WebAssembly Memory to allocate larger ArrayBuffer\n            const pages = Math.ceil(fileSize / 65536);\n            buffer = new WebAssembly.Memory({ initial: pages, maximum: pages }).buffer;\n          } else {\n            throw e;\n          }\n        }\n\n        let offset = 0;\n        while (true) {\n          const { done, value } = await reader.read();\n          if (done) {\n            break;\n          }\n          const chunkSize = value.byteLength;\n          const chunk = new Uint8Array(buffer, offset, chunkSize);\n          chunk.set(value);\n          offset += chunkSize;\n        }\n        return new Uint8Array(buffer, 0, fileSize);\n      }\n    }\n  } else if (file instanceof Blob) {\n    return new Uint8Array(await file.arrayBuffer());\n  } else if (file instanceof Uint8Array) {\n    return file;\n  } else {\n    return new Uint8Array(file);\n  }\n};\n","// Copyright (c) Microsoft Corporation. All rights reserved.\n// Licensed under the MIT License.\n\n// WebNN API currently does not have a TypeScript definition file. This file is a workaround with types generated from\n// WebNN API specification.\n// https://github.com/webmachinelearning/webnn/issues/677\n/// <reference path=\"jsep/webnn/webnn.d.ts\" />\n\nimport { Env, InferenceSession, Tensor, TRACE_EVENT_BEGIN, TRACE_EVENT_END } from 'onnxruntime-common';\n\nimport {\n  SerializableInternalBuffer,\n  SerializableSessionMetadata,\n  SerializableTensorMetadata,\n  TensorMetadata,\n} from './proxy-messages';\nimport { setRunOptions } from './run-options';\nimport { setSessionOptions } from './session-options';\nimport {\n  calculateTensorSizeInBytes,\n  dataLocationStringToEnum,\n  isGpuBufferSupportedType,\n  isMLTensorSupportedType,\n  logLevelStringToEnum,\n  tensorDataTypeEnumToString,\n  tensorDataTypeStringToEnum,\n  tensorTypeToTypedArrayConstructor,\n} from './wasm-common';\nimport { getInstance } from './wasm-factory';\nimport { allocWasmString, checkLastError } from './wasm-utils';\nimport { loadFile } from './wasm-utils-load-file';\n\n// #region Initializations\n\n/**\n * There are 4 different \"initialization\" steps for ORT. They happen in different places and different time.\n *\n * 1. JavaScript initialization for onnxruntime-common and onnxruntime-web.\n *    This is the first initialization step. In this step, onnxruntime-web calls onnxruntime-common's registerBackend()\n * function multiple times to register all the available backends. The backend registration is very fast. It only\n * registers the backend name with the uninitialized backend object. No heavy initialization is done in this step.\n *    Refer to web/lib/index.ts for the backend registration.\n *\n * 2. WebAssembly artifact initialization.\n *    This happens when any registered wasm backend is used for the first time (ie. `ort.InferenceSession.create()` is\n * called). In this step, onnxruntime-web does the followings:\n *     - create a proxy worker and make sure the proxy worker is ready to receive messages, if proxy is enabled.\n *     - perform feature detection, locate correct WebAssembly artifact path and call the Emscripten generated\n * JavaScript code to initialize the WebAssembly runtime.\n *         - if proxy is enabled, this step happens in the proxy worker using message 'init-wasm'.\n *         - downloading the 'ort-wasm{...}.wasm' file is done in this step.\n *         - if multi-thread is enabled, one or more webworker will be created to initialize the PThread threadpool.\n *\n * 3. ORT environment initialization.\n *    This happens after step 2. In this step, onnxruntime-web performs ONNX Runtime environment initialization.\n * Function `_OrtInit()` is called in this step.\n *     - if proxy is enabled, this step happens in the proxy worker using message 'init-ort'.\n *     - logging level (ort.env.logLevel) and thread number (ort.env.wasm.numThreads) are set in this step.\n *\n * 4. Session initialization.\n *    This happens when `ort.InferenceSession.create()` is called. Unlike the first 3 steps (they only called once),\n * this step will be done for each session. In this step, onnxruntime-web does the followings:\n *    If the parameter is a URL:\n *    - download the model data from the URL.\n *    - copy the model data to the WASM heap. (proxy: 'copy-from')\n *    - dereference the model buffer. This step allows the original ArrayBuffer to be garbage collected.\n *    - call `_OrtCreateSession()` to create the session. (proxy: 'create')\n *\n *    If the parameter is a Uint8Array object:\n *    - copy the model data to the WASM heap. (proxy: 'copy-from')\n *    - call `_OrtCreateSession()` to create the session. (proxy: 'create')\n *\n *\n */\n\n/**\n * initialize ORT environment.\n *\n * @param numThreads SetGlobalIntraOpNumThreads(numThreads)\n * @param loggingLevel CreateEnv(static_cast<OrtLoggingLevel>(logging_level))\n */\nconst initOrt = (numThreads: number, loggingLevel: number): void => {\n  const errorCode = getInstance()._OrtInit(numThreads, loggingLevel);\n  if (errorCode !== 0) {\n    checkLastError(\"Can't initialize onnxruntime.\");\n  }\n};\n\n/**\n * initialize runtime environment.\n * @param env passed in the environment config object.\n */\nexport const initRuntime = async (env: Env): Promise<void> => {\n  // init ORT\n  initOrt(env.wasm.numThreads!, logLevelStringToEnum(env.logLevel));\n};\n\n/**\n * perform EP specific initialization.\n *\n * @param env\n * @param epName\n */\nexport const initEp = async (env: Env, epName: string): Promise<void> => {\n  // initialize ASYNCIFY support\n  getInstance().asyncInit?.();\n\n  // perform WebGPU availability check ( either JSEP or WebGPU EP )\n  let webgpuAdapter: GPUAdapter | null = env.webgpu.adapter;\n  if (epName === 'webgpu') {\n    if (typeof navigator === 'undefined' || !navigator.gpu) {\n      throw new Error('WebGPU is not supported in current environment');\n    }\n    if (!webgpuAdapter) {\n      // if adapter is not set, request a new adapter.\n      const powerPreference = env.webgpu.powerPreference;\n      if (powerPreference !== undefined && powerPreference !== 'low-power' && powerPreference !== 'high-performance') {\n        throw new Error(`Invalid powerPreference setting: \"${powerPreference}\"`);\n      }\n      const forceFallbackAdapter = env.webgpu.forceFallbackAdapter;\n      if (forceFallbackAdapter !== undefined && typeof forceFallbackAdapter !== 'boolean') {\n        throw new Error(`Invalid forceFallbackAdapter setting: \"${forceFallbackAdapter}\"`);\n      }\n      webgpuAdapter = await navigator.gpu.requestAdapter({ powerPreference, forceFallbackAdapter });\n      if (!webgpuAdapter) {\n        throw new Error(\n          'Failed to get GPU adapter. ' +\n            'You may need to enable flag \"--enable-unsafe-webgpu\" if you are using Chrome.',\n        );\n      }\n    } else {\n      // if adapter is set, validate it.\n      if (\n        typeof webgpuAdapter.limits !== 'object' ||\n        typeof webgpuAdapter.features !== 'object' ||\n        typeof webgpuAdapter.requestDevice !== 'function'\n      ) {\n        throw new Error('Invalid GPU adapter set in `env.webgpu.adapter`. It must be a GPUAdapter object.');\n      }\n    }\n  }\n\n  // perform WebNN availability check ( either JSEP or WebNN EP )\n  if (epName === 'webnn') {\n    if (typeof navigator === 'undefined' || !(navigator as unknown as { ml: unknown }).ml) {\n      throw new Error('WebNN is not supported in current environment');\n    }\n  }\n\n  if (!BUILD_DEFS.DISABLE_JSEP) {\n    // eslint-disable-next-line @typescript-eslint/no-require-imports, @typescript-eslint/no-var-requires\n    const initJsep = require('./jsep/init').init;\n\n    if (epName === 'webgpu') {\n      await initJsep('webgpu', getInstance(), env, webgpuAdapter);\n    }\n    if (epName === 'webnn') {\n      await initJsep('webnn', getInstance(), env);\n    }\n  } else {\n    if (!BUILD_DEFS.DISABLE_WEBGPU && epName === 'webgpu') {\n      getInstance().webgpuInit!((device) => {\n        env.webgpu.device = device;\n      });\n    }\n    if (!BUILD_DEFS.DISABLE_WEBNN && epName === 'webnn') {\n      // eslint-disable-next-line @typescript-eslint/no-require-imports, @typescript-eslint/no-var-requires\n      const backend = new (require('./jsep/backend-webnn').WebNNBackend)(env);\n      getInstance().webnnInit!([\n        backend,\n        // webnnReserveTensorId\n        () => backend.reserveTensorId(),\n        // webnnReleaseTensorId,\n        (tensorId: number) => backend.releaseTensorId(tensorId),\n        // webnnEnsureTensor\n        async (sessionId: number | undefined, tensorId: number, onnxDataType: number, shape: number[], copyOld) =>\n          backend.ensureTensor(sessionId, tensorId, onnxDataType, shape, copyOld),\n        // webnnUploadTensor\n        (tensorId: number, data: Uint8Array) => {\n          backend.uploadTensor(tensorId, data);\n        },\n        // webnnDownloadTensor\n        async (tensorId: number, dstBuffer: ArrayBufferView | ArrayBuffer) =>\n          backend.downloadTensor(tensorId, dstBuffer),\n        // webnnRegisterMLContext\n        (sessionId: number, mlContext: MLContext) => backend.registerMLContext(sessionId, mlContext),\n        // webnnEnableTraceEvent\n        !!env.trace,\n      ]);\n    }\n  }\n};\n\n// #endregion Initializations\n\n/**\n * valid data locations for input/output tensors.\n */\ntype SupportedTensorDataLocationForInputOutput =\n  | 'cpu'\n  | 'cpu-pinned'\n  | 'gpu-buffer'\n  | 'ml-tensor'\n  // Use 'ml-tensor' during inference, but output a tensor located on the CPU.\n  | 'ml-tensor-cpu-output';\n\ntype IOBindingState = {\n  /**\n   * the handle of IO binding.\n   */\n  readonly handle: number;\n\n  /**\n   * the preferred location for each output tensor.\n   *\n   * value is one of 'cpu', 'cpu-pinned', 'gpu-buffer', 'ml-tensor'.\n   */\n  readonly outputPreferredLocations: readonly SupportedTensorDataLocationForInputOutput[];\n\n  /**\n   * enum value of the preferred location for each output tensor.\n   */\n  readonly outputPreferredLocationsEncoded: readonly number[];\n};\n\n/**\n *  tuple elements are: InferenceSession ID; inputNamesUTF8Encoded; outputNamesUTF8Encoded; bindingState\n */\ntype SessionMetadata = [\n  inferenceSessionId: number,\n  inputNamesUTF8Encoded: number[],\n  outputNamesUTF8Encoded: number[],\n  bindingState: IOBindingState | null,\n  enableGraphCapture: boolean,\n  inputOutputBound: boolean,\n];\n\nconst activeSessions = new Map<number, SessionMetadata>();\n\n/**\n * get the input/output count of the session.\n * @param sessionHandle the handle representing the session. should be non-zero.\n * @returns a tuple including 2 numbers, representing the input count and output count.\n */\nconst getSessionInputOutputCount = (sessionHandle: number): [number, number] => {\n  const wasm = getInstance();\n  const stack = wasm.stackSave();\n  try {\n    const ptrSize = wasm.PTR_SIZE;\n    const dataOffset = wasm.stackAlloc(2 * ptrSize);\n    const errorCode = wasm._OrtGetInputOutputCount(sessionHandle, dataOffset, dataOffset + ptrSize);\n    if (errorCode !== 0) {\n      checkLastError(\"Can't get session input/output count.\");\n    }\n    const type = ptrSize === 4 ? 'i32' : 'i64';\n    return [Number(wasm.getValue(dataOffset, type)), Number(wasm.getValue(dataOffset + ptrSize, type))];\n  } finally {\n    wasm.stackRestore(stack);\n  }\n};\n\nconst getSessionInputOutputMetadata = (\n  sessionHandle: number,\n  index: number,\n): [nameOffset: number, elementType: number, dims?: Array<number | string>] => {\n  const wasm = getInstance();\n  const stack = wasm.stackSave();\n  let metadataOffset = 0;\n  try {\n    const ptrSize = wasm.PTR_SIZE;\n    const dataOffset = wasm.stackAlloc(2 * ptrSize);\n    const errorCode = wasm._OrtGetInputOutputMetadata(sessionHandle, index, dataOffset, dataOffset + ptrSize);\n    if (errorCode !== 0) {\n      checkLastError(\"Can't get session input/output metadata.\");\n    }\n    const nameOffset = Number(wasm.getValue(dataOffset, '*'));\n    metadataOffset = Number(wasm.getValue(dataOffset + ptrSize, '*'));\n    // get element type\n    const elementType = wasm.HEAP32[metadataOffset / 4];\n    if (elementType === 0) {\n      return [nameOffset, 0]; // non-tensor\n    }\n\n    // get dims count\n    const dimsCount = wasm.HEAPU32[metadataOffset / 4 + 1];\n    // get dims\n    const dims: Array<number | string> = [];\n    for (let i = 0; i < dimsCount; i++) {\n      const symbolicDimNameOffset = Number(wasm.getValue(metadataOffset + 8 + i * ptrSize, '*'));\n      dims.push(\n        symbolicDimNameOffset !== 0\n          ? wasm.UTF8ToString(symbolicDimNameOffset)\n          : Number(wasm.getValue(metadataOffset + 8 + (i + dimsCount) * ptrSize, '*')),\n      );\n    }\n    return [nameOffset, elementType, dims];\n  } finally {\n    wasm.stackRestore(stack);\n    if (metadataOffset !== 0) {\n      wasm._OrtFree(metadataOffset);\n    }\n  }\n};\n\n/**\n * allocate the memory and memcpy the external buffer.\n *\n * @param model - the external buffer containing the model data. Must not be the same buffer as the WASM heap.\n * @returns a 2-elements tuple - the pointer and size of the allocated buffer\n */\nexport const copyFromExternalBuffer = (model: Uint8Array): [number, number] => {\n  const wasm = getInstance();\n  const modelDataOffset = wasm._malloc(model.byteLength);\n  if (modelDataOffset === 0) {\n    throw new Error(`Can't create a session. failed to allocate a buffer of size ${model.byteLength}.`);\n  }\n  wasm.HEAPU8.set(model, modelDataOffset);\n  return [modelDataOffset, model.byteLength];\n};\n\n/**\n * create an inference session from a model data buffer.\n *\n * @param modelData - either a Uint8Array object representing the model data, or a 2-elements tuple containing the\n *     pointer and size of the model data buffer.\n * @param options an optional session options object.\n * @returns a 3-elements tuple containing [session handle, input names, output names]\n */\nexport const createSession = async (\n  modelData: Uint8Array | SerializableInternalBuffer,\n  options?: InferenceSession.SessionOptions,\n): Promise<SerializableSessionMetadata> => {\n  let modelDataOffset: number, modelDataLength: number;\n  const wasm = getInstance();\n\n  if (Array.isArray(modelData)) {\n    // if model data is an array, it must be a 2-elements tuple containing the pointer and size of the model data\n    [modelDataOffset, modelDataLength] = modelData;\n  } else if (modelData.buffer === wasm.HEAPU8.buffer) {\n    // if model data uses the same buffer as the WASM heap, we don't need to copy it.\n    [modelDataOffset, modelDataLength] = [modelData.byteOffset, modelData.byteLength];\n  } else {\n    // otherwise, copy the model data to the WASM heap.\n    [modelDataOffset, modelDataLength] = copyFromExternalBuffer(modelData);\n  }\n\n  let sessionHandle = 0;\n  let sessionOptionsHandle = 0;\n  let ioBindingHandle = 0;\n  let allocs: number[] = [];\n  const inputNamesUTF8Encoded = [];\n  const outputNamesUTF8Encoded = [];\n\n  try {\n    [sessionOptionsHandle, allocs] = await setSessionOptions(options);\n\n    if (options?.externalData && wasm.mountExternalData) {\n      const loadingPromises = [];\n      for (const file of options.externalData) {\n        const path = typeof file === 'string' ? file : file.path;\n        const data = typeof file === 'string' ? file : file.data;\n        if (BUILD_DEFS.ENABLE_JSPI && data instanceof Blob) {\n          wasm.mountExternalData(path, data);\n          continue;\n        }\n        loadingPromises.push(\n          loadFile(data).then((fileData) => {\n            wasm.mountExternalData(path, fileData);\n          }),\n        );\n      }\n\n      // wait for all external data files to be loaded\n      await Promise.all(loadingPromises);\n    }\n\n    for (const provider of options?.executionProviders ?? []) {\n      const providerName = typeof provider === 'string' ? provider : provider.name;\n      if (providerName === 'webnn') {\n        wasm.shouldTransferToMLTensor = false;\n        if (typeof provider !== 'string') {\n          const webnnOptions = provider as InferenceSession.WebNNExecutionProviderOption;\n          const context = (webnnOptions as InferenceSession.WebNNOptionsWithMLContext)?.context;\n          const gpuDevice = (webnnOptions as InferenceSession.WebNNOptionsWebGpu)?.gpuDevice;\n          const deviceType = (webnnOptions as InferenceSession.WebNNContextOptions)?.deviceType;\n          const powerPreference = (webnnOptions as InferenceSession.WebNNContextOptions)?.powerPreference;\n          if (context) {\n            wasm.currentContext = context as MLContext;\n          } else if (gpuDevice) {\n            wasm.currentContext = await wasm.webnnCreateMLContext!(gpuDevice);\n          } else {\n            wasm.currentContext = await wasm.webnnCreateMLContext!({ deviceType, powerPreference });\n          }\n        } else {\n          wasm.currentContext = await wasm.webnnCreateMLContext!();\n        }\n        break;\n      }\n    }\n\n    sessionHandle = await wasm._OrtCreateSession(modelDataOffset, modelDataLength, sessionOptionsHandle);\n    wasm.webgpuOnCreateSession?.(sessionHandle);\n    if (sessionHandle === 0) {\n      checkLastError(\"Can't create a session.\");\n    }\n\n    wasm.jsepOnCreateSession?.();\n\n    // clear current MLContext after session creation\n    if (wasm.currentContext) {\n      wasm.webnnRegisterMLContext!(sessionHandle, wasm.currentContext);\n      wasm.currentContext = undefined;\n      wasm.shouldTransferToMLTensor = true;\n    }\n\n    const [inputCount, outputCount] = getSessionInputOutputCount(sessionHandle);\n\n    const enableGraphCapture = !!options?.enableGraphCapture;\n\n    const inputNames = [];\n    const outputNames = [];\n    const inputMetadata: InferenceSession.ValueMetadata[] = [];\n    const outputMetadata: InferenceSession.ValueMetadata[] = [];\n    const outputPreferredLocations: SupportedTensorDataLocationForInputOutput[] = [];\n    for (let i = 0; i < inputCount; i++) {\n      const [nameOffset, elementType, shape] = getSessionInputOutputMetadata(sessionHandle, i);\n      if (nameOffset === 0) {\n        checkLastError(\"Can't get an input name.\");\n      }\n      inputNamesUTF8Encoded.push(nameOffset);\n      const name = wasm.UTF8ToString(nameOffset);\n      inputNames.push(name);\n      inputMetadata.push(\n        elementType === 0\n          ? { name, isTensor: false }\n          : { name, isTensor: true, type: tensorDataTypeEnumToString(elementType), shape: shape! },\n      );\n    }\n    for (let i = 0; i < outputCount; i++) {\n      const [nameOffset, elementType, shape] = getSessionInputOutputMetadata(sessionHandle, i + inputCount);\n      if (nameOffset === 0) {\n        checkLastError(\"Can't get an output name.\");\n      }\n      outputNamesUTF8Encoded.push(nameOffset);\n      const nameString = wasm.UTF8ToString(nameOffset);\n      outputNames.push(nameString);\n      outputMetadata.push(\n        elementType === 0\n          ? { name: nameString, isTensor: false }\n          : { name: nameString, isTensor: true, type: tensorDataTypeEnumToString(elementType), shape: shape! },\n      );\n\n      if (!BUILD_DEFS.DISABLE_JSEP || !BUILD_DEFS.DISABLE_WEBGPU) {\n        if (enableGraphCapture && options?.preferredOutputLocation === undefined) {\n          outputPreferredLocations.push('gpu-buffer');\n          continue;\n        }\n        const location =\n          typeof options?.preferredOutputLocation === 'string'\n            ? options.preferredOutputLocation\n            : (options?.preferredOutputLocation?.[nameString] ?? 'cpu');\n        const isGraphOutput = wasm.webnnIsGraphOutput;\n        if (location === 'cpu' && isGraphOutput && isGraphOutput(sessionHandle, nameString)) {\n          outputPreferredLocations.push('ml-tensor-cpu-output');\n          continue;\n        }\n        if (location !== 'cpu' && location !== 'cpu-pinned' && location !== 'gpu-buffer' && location !== 'ml-tensor') {\n          throw new Error(`Not supported preferred output location: ${location}.`);\n        }\n        if (enableGraphCapture && location !== 'gpu-buffer') {\n          throw new Error(\n            `Not supported preferred output location: ${location}. Only 'gpu-buffer' location is supported when enableGraphCapture is true.`,\n          );\n        }\n        outputPreferredLocations.push(location);\n      }\n    }\n\n    // use IO binding only when at least one output is preferred to be on GPU.\n    let bindingState: IOBindingState | null = null;\n    if (\n      (!BUILD_DEFS.DISABLE_JSEP || !BUILD_DEFS.DISABLE_WEBGPU) &&\n      outputPreferredLocations.some((l) => l === 'gpu-buffer' || l === 'ml-tensor' || l === 'ml-tensor-cpu-output')\n    ) {\n      ioBindingHandle = wasm._OrtCreateBinding(sessionHandle);\n      if (ioBindingHandle === 0) {\n        checkLastError(\"Can't create IO binding.\");\n      }\n\n      bindingState = {\n        handle: ioBindingHandle,\n        outputPreferredLocations,\n        outputPreferredLocationsEncoded: outputPreferredLocations\n          // 'ml-tensor-cpu-output' is treated as 'ml-tensor' for the purpose of IO binding.\n          .map((l) => (l === 'ml-tensor-cpu-output' ? 'ml-tensor' : l))\n          .map((l) => dataLocationStringToEnum(l)),\n      };\n    }\n\n    activeSessions.set(sessionHandle, [\n      sessionHandle,\n      inputNamesUTF8Encoded,\n      outputNamesUTF8Encoded,\n      bindingState,\n      enableGraphCapture,\n      false,\n    ]);\n    return [sessionHandle, inputNames, outputNames, inputMetadata, outputMetadata];\n  } catch (e) {\n    inputNamesUTF8Encoded.forEach((buf) => wasm._OrtFree(buf));\n    outputNamesUTF8Encoded.forEach((buf) => wasm._OrtFree(buf));\n\n    if (ioBindingHandle !== 0) {\n      if (wasm._OrtReleaseBinding(ioBindingHandle) !== 0) {\n        checkLastError(\"Can't release IO binding.\");\n      }\n    }\n\n    if (sessionHandle !== 0) {\n      if (wasm._OrtReleaseSession(sessionHandle) !== 0) {\n        checkLastError(\"Can't release session.\");\n      }\n    }\n    throw e;\n  } finally {\n    wasm._free(modelDataOffset);\n    if (sessionOptionsHandle !== 0) {\n      if (wasm._OrtReleaseSessionOptions(sessionOptionsHandle) !== 0) {\n        checkLastError(\"Can't release session options.\");\n      }\n    }\n    allocs.forEach((alloc) => wasm._free(alloc));\n\n    // unmount external data if necessary\n    wasm.unmountExternalData?.();\n  }\n};\n\nexport const releaseSession = (sessionId: number): void => {\n  const wasm = getInstance();\n  const session = activeSessions.get(sessionId);\n  if (!session) {\n    throw new Error(`cannot release session. invalid session id: ${sessionId}`);\n  }\n  const [sessionHandle, inputNamesUTF8Encoded, outputNamesUTF8Encoded, ioBindingState, enableGraphCapture] = session;\n\n  if (ioBindingState) {\n    if (enableGraphCapture) {\n      if (wasm._OrtClearBoundOutputs(ioBindingState.handle) !== 0) {\n        checkLastError(\"Can't clear bound outputs.\");\n      }\n    }\n    if (wasm._OrtReleaseBinding(ioBindingState.handle) !== 0) {\n      checkLastError(\"Can't release IO binding.\");\n    }\n  }\n\n  wasm.jsepOnReleaseSession?.(sessionId);\n  wasm.webnnOnReleaseSession?.(sessionId);\n  wasm.webgpuOnReleaseSession?.(sessionId);\n\n  inputNamesUTF8Encoded.forEach((buf) => wasm._OrtFree(buf));\n  outputNamesUTF8Encoded.forEach((buf) => wasm._OrtFree(buf));\n  if (wasm._OrtReleaseSession(sessionHandle) !== 0) {\n    checkLastError(\"Can't release session.\");\n  }\n  activeSessions.delete(sessionId);\n};\n\n// map from LoRA adapter ID to native LoRA adapter handle. The native handle is not used as the ID, because the\n// memory of a released adapter can be reused by a new one.\nconst loraAdapters = new Map<number, number>();\nlet nextLoraAdapterId = 1;\n// number of runs in progress that use each LoRA adapter. An adapter cannot be released while it is in use.\nconst loraAdapterRunCounts = new Map<number, number>();\n\n/**\n * create a LoRA adapter from a buffer in the LoRA adapter format.\n *\n * @param adapterData - the LoRA adapter data.\n * @returns the LoRA adapter ID\n */\nexport const createLoraAdapter = (adapterData: Uint8Array): number => {\n  const wasm = getInstance();\n  const dataOffset = wasm._malloc(adapterData.byteLength);\n  if (dataOffset === 0) {\n    throw new Error(`Can't create a LoRA adapter. failed to allocate a buffer of size ${adapterData.byteLength}.`);\n  }\n\n  try {\n    wasm.HEAPU8.set(adapterData, dataOffset);\n    const adapterHandle = wasm._OrtCreateLoraAdapter(dataOffset, adapterData.byteLength);\n    if (adapterHandle === 0) {\n      checkLastError(\"Can't create a LoRA adapter.\");\n    }\n    const adapterId = nextLoraAdapterId++;\n    loraAdapters.set(adapterId, adapterHandle);\n    return adapterId;\n  } finally {\n    // the data is copied by ORT, so it can be freed here.\n    wasm._free(dataOffset);\n  }\n};\n\nexport const releaseLoraAdapter = (adapterId: number): void => {\n  const wasm = getInstance();\n  const adapterHandle = loraAdapters.get(adapterId);\n  if (adapterHandle === undefined) {\n    throw new Error(`cannot release LoRA adapter. invalid adapter id: ${adapterId}`);\n  }\n  if (loraAdapterRunCounts.has(adapterId)) {\n    throw new Error(`cannot release LoRA adapter. the adapter is used by a run in progress. adapter id: ${adapterId}`);\n  }\n  if (wasm._OrtReleaseLoraAdapter(adapterHandle) !== 0) {\n    checkLastError(\"Can't release LoRA adapter.\");\n  }\n  loraAdapters.delete(adapterId);\n};\n\nexport const prepareInputOutputTensor = async (\n  tensor: TensorMetadata | null,\n  tensorHandles: number[],\n  allocs: number[],\n  sessionId: number,\n  tensorNameUTF8Encoded: number,\n  index: number,\n  enableGraphCapture = false,\n): Promise<void> => {\n  if (!tensor) {\n    tensorHandles.push(0);\n    return;\n  }\n\n  const wasm = getInstance();\n  const ptrSize = wasm.PTR_SIZE;\n\n  const dataType = tensor[0];\n  const dims = tensor[1];\n  const location = tensor[3];\n  let actualLocation = location;\n\n  let rawData: number;\n  let dataByteLength: number;\n\n  if (dataType === 'string' && (location === 'gpu-buffer' || location === 'ml-tensor')) {\n    throw new Error('String tensor is not supported on GPU.');\n  }\n\n  if (enableGraphCapture && location !== 'gpu-buffer') {\n    throw new Error(\n      `External buffer must be provided for input/output index ${index} when enableGraphCapture is true.`,\n    );\n  }\n\n  if (location === 'gpu-buffer') {\n    const gpuBuffer = tensor[2].gpuBuffer;\n    dataByteLength = calculateTensorSizeInBytes(tensorDataTypeStringToEnum(dataType), dims)!;\n\n    if (!BUILD_DEFS.DISABLE_WEBGPU) {\n      const registerBuffer = wasm.webgpuRegisterBuffer;\n      if (!registerBuffer) {\n        throw new Error('Tensor location \"gpu-buffer\" is not supported without using WebGPU.');\n      }\n\n      rawData = registerBuffer(gpuBuffer, sessionId);\n    } else {\n      const registerBuffer = wasm.jsepRegisterBuffer;\n      if (!registerBuffer) {\n        throw new Error('Tensor location \"gpu-buffer\" is not supported without using WebGPU.');\n      }\n      rawData = registerBuffer(sessionId, index, gpuBuffer, dataByteLength);\n    }\n  } else if (location === 'ml-tensor') {\n    const mlTensor = tensor[2].mlTensor;\n    dataByteLength = calculateTensorSizeInBytes(tensorDataTypeStringToEnum(dataType), dims)!;\n\n    const registerMLTensor = wasm.webnnRegisterMLTensor;\n    if (!registerMLTensor) {\n      throw new Error('Tensor location \"ml-tensor\" is not supported without using WebNN.');\n    }\n    rawData = registerMLTensor(sessionId, mlTensor, tensorDataTypeStringToEnum(dataType), dims);\n  } else {\n    const data = tensor[2];\n\n    if (Array.isArray(data)) {\n      // string tensor\n      dataByteLength = ptrSize * data.length;\n      rawData = wasm._malloc(dataByteLength);\n      allocs.push(rawData);\n      for (let i = 0; i < data.length; i++) {\n        if (typeof data[i] !== 'string') {\n          throw new TypeError(`tensor data at index ${i} is not a string`);\n        }\n        wasm.setValue(rawData + i * ptrSize, allocWasmString(data[i], allocs), '*');\n      }\n    } else {\n      const isGraphInput = wasm.webnnIsGraphInput;\n      const isGraphOutput = wasm.webnnIsGraphOutput;\n      if (dataType !== 'string' && isGraphInput && isGraphOutput) {\n        const tensorName = wasm.UTF8ToString(tensorNameUTF8Encoded);\n        // Promote the tensor to 'ml-tensor' if it is a graph input.\n        if (isGraphInput(sessionId, tensorName) || isGraphOutput(sessionId, tensorName)) {\n          const dataTypeEnum = tensorDataTypeStringToEnum(dataType);\n          dataByteLength = calculateTensorSizeInBytes(dataTypeEnum, dims)!;\n          actualLocation = 'ml-tensor';\n          const createTemporaryTensor = wasm.webnnCreateTemporaryTensor;\n          const uploadTensor = wasm.webnnUploadTensor;\n          if (!createTemporaryTensor || !uploadTensor) {\n            throw new Error('Tensor location \"ml-tensor\" is not supported without using WebNN.');\n          }\n          const tensorId = await createTemporaryTensor(sessionId, dataTypeEnum, dims);\n          uploadTensor(tensorId, new Uint8Array(data.buffer, data.byteOffset, data.byteLength));\n          rawData = tensorId;\n        } else {\n          dataByteLength = data.byteLength;\n          rawData = wasm._malloc(dataByteLength);\n          allocs.push(rawData);\n          wasm.HEAPU8.set(new Uint8Array(data.buffer, data.byteOffset, dataByteLength), rawData);\n        }\n      } else {\n        dataByteLength = data.byteLength;\n        rawData = wasm._malloc(dataByteLength);\n        allocs.push(rawData);\n        wasm.HEAPU8.set(new Uint8Array(data.buffer, data.byteOffset, dataByteLength), rawData);\n      }\n    }\n  }\n\n  const stack = wasm.stackSave();\n  const dimsOffset = wasm.stackAlloc(4 * dims.length);\n  try {\n    dims.forEach((d, index) => wasm.setValue(dimsOffset + index * ptrSize, d, ptrSize === 4 ? 'i32' : 'i64'));\n    const tensor = wasm._OrtCreateTensor(\n      tensorDataTypeStringToEnum(dataType),\n      rawData,\n      dataByteLength,\n      dimsOffset,\n      dims.length,\n      dataLocationStringToEnum(actualLocation),\n    );\n    if (tensor === 0) {\n      checkLastError(`Can't create tensor for input/output. session=${sessionId}, index=${index}.`);\n    }\n    tensorHandles.push(tensor);\n  } finally {\n    wasm.stackRestore(stack);\n  }\n};\n\n/**\n * perform inference run\n */\nexport const run = async (\n  sessionId: number,\n  inputIndices: number[],\n  inputTensors: TensorMetadata[],\n  outputIndices: number[],\n  outputTensors: Array<TensorMetadata | null>,\n  options: InferenceSession.RunOptions,\n  loraAdapterIds: readonly number[] = [],\n): Promise<TensorMetadata[]> => {\n  const wasm = getInstance();\n  const ptrSize = wasm.PTR_SIZE;\n  const session = activeSessions.get(sessionId);\n  if (!session) {\n    throw new Error(`cannot run inference. invalid session id: ${sessionId}`);\n  }\n  const sessionHandle = session[0];\n  const inputNamesUTF8Encoded = session[1];\n  const outputNamesUTF8Encoded = session[2];\n  const ioBindingState = session[3];\n  const enableGraphCapture = session[4];\n  const inputOutputBound = session[5];\n\n  const loraAdapterHandles: number[] = [];\n  if (loraAdapterIds.length > 0) {\n    // ORT does not apply active LoRA adapters in RunWithBinding(). Fail instead of silently ignoring them.\n    if (ioBindingState) {\n      throw new Error(\n        'LoRA adapters are not supported for a session that uses IO binding, e.g. when an output is preferred to be ' +\n          'on GPU, or when the WebNN execution provider produces an output.',\n      );\n    }\n    for (const adapterId of loraAdapterIds) {\n      const adapterHandle = loraAdapters.get(adapterId);\n      if (adapterHandle === undefined) {\n        throw new Error(`cannot run inference. invalid LoRA adapter id: ${adapterId}`);\n      }\n      loraAdapterHandles.push(adapterHandle);\n    }\n  }\n\n  const inputCount = inputIndices.length;\n  const outputCount = outputIndices.length;\n\n  let runOptionsHandle = 0;\n  let runOptionsAllocs: number[] = [];\n\n  const inputTensorHandles: number[] = [];\n  const outputTensorHandles: number[] = [];\n  const inputOutputAllocs: number[] = [];\n  const preAllocatedOutputs: number[] = [];\n\n  const beforeRunStack = wasm.stackSave();\n  const inputValuesOffset = wasm.stackAlloc(inputCount * ptrSize);\n  const inputNamesOffset = wasm.stackAlloc(inputCount * ptrSize);\n  const outputValuesOffset = wasm.stackAlloc(outputCount * ptrSize);\n  const outputNamesOffset = wasm.stackAlloc(outputCount * ptrSize);\n\n  try {\n    for (const adapterId of loraAdapterIds) {\n      loraAdapterRunCounts.set(adapterId, (loraAdapterRunCounts.get(adapterId) ?? 0) + 1);\n    }\n    [runOptionsHandle, runOptionsAllocs] = setRunOptions(options, loraAdapterHandles);\n\n    TRACE_EVENT_BEGIN('wasm prepareInputOutputTensor');\n    // create input tensors\n    for (let i = 0; i < inputCount; i++) {\n      await prepareInputOutputTensor(\n        inputTensors[i],\n        inputTensorHandles,\n        inputOutputAllocs,\n        sessionId,\n        inputNamesUTF8Encoded[inputIndices[i]],\n        inputIndices[i],\n        enableGraphCapture,\n      );\n    }\n\n    // create output tensors\n    for (let i = 0; i < outputCount; i++) {\n      await prepareInputOutputTensor(\n        outputTensors[i],\n        outputTensorHandles,\n        inputOutputAllocs,\n        sessionId,\n        outputNamesUTF8Encoded[outputIndices[i]],\n        inputCount + outputIndices[i],\n        enableGraphCapture,\n      );\n    }\n    TRACE_EVENT_END('wasm prepareInputOutputTensor');\n\n    for (let i = 0; i < inputCount; i++) {\n      wasm.setValue(inputValuesOffset + i * ptrSize, inputTensorHandles[i], '*');\n      wasm.setValue(inputNamesOffset + i * ptrSize, inputNamesUTF8Encoded[inputIndices[i]], '*');\n    }\n    for (let i = 0; i < outputCount; i++) {\n      wasm.setValue(outputValuesOffset + i * ptrSize, outputTensorHandles[i], '*');\n      wasm.setValue(outputNamesOffset + i * ptrSize, outputNamesUTF8Encoded[outputIndices[i]], '*');\n    }\n\n    if ((!BUILD_DEFS.DISABLE_JSEP || !BUILD_DEFS.DISABLE_WEBGPU) && ioBindingState && !inputOutputBound) {\n      const { handle, outputPreferredLocations, outputPreferredLocationsEncoded } = ioBindingState;\n\n      if (inputNamesUTF8Encoded.length !== inputCount) {\n        throw new Error(\n          `input count from feeds (${inputCount}) is expected to be always equal to model's input count (${inputNamesUTF8Encoded.length}).`,\n        );\n      }\n\n      TRACE_EVENT_BEGIN('wasm bindInputsOutputs');\n      // process inputs\n      for (let i = 0; i < inputCount; i++) {\n        const index = inputIndices[i];\n        const errorCode = await wasm._OrtBindInput(handle, inputNamesUTF8Encoded[index], inputTensorHandles[i]);\n        if (errorCode !== 0) {\n          checkLastError(`Can't bind input[${i}] for session=${sessionId}.`);\n        }\n      }\n\n      // process pre-allocated outputs\n      for (let i = 0; i < outputCount; i++) {\n        const index = outputIndices[i];\n        const location = outputTensors[i]?.[3]; // undefined means output is not pre-allocated.\n\n        if (location) {\n          // output is pre-allocated, store and bind the tensor.\n          preAllocatedOutputs.push(outputTensorHandles[i]);\n          const errorCode = wasm._OrtBindOutput(handle, outputNamesUTF8Encoded[index], outputTensorHandles[i], 0);\n          if (errorCode !== 0) {\n            checkLastError(`Can't bind pre-allocated output[${i}] for session=${sessionId}.`);\n          }\n        } else {\n          // output is not pre-allocated. reset preferred location.\n          const errorCode = wasm._OrtBindOutput(\n            handle,\n            outputNamesUTF8Encoded[index],\n            0,\n            outputPreferredLocationsEncoded[index],\n          );\n          if (errorCode !== 0) {\n            checkLastError(`Can't bind output[${i}] to ${outputPreferredLocations[i]} for session=${sessionId}.`);\n          }\n        }\n      }\n      TRACE_EVENT_END('wasm bindInputsOutputs');\n      activeSessions.set(sessionId, [\n        sessionHandle,\n        inputNamesUTF8Encoded,\n        outputNamesUTF8Encoded,\n        ioBindingState,\n        enableGraphCapture,\n        true,\n      ]);\n    }\n\n    wasm.jsepOnRunStart?.(sessionHandle);\n    wasm.webnnOnRunStart?.(sessionHandle);\n\n    let errorCode: number;\n    if ((!BUILD_DEFS.DISABLE_JSEP || !BUILD_DEFS.DISABLE_WEBGPU) && ioBindingState) {\n      errorCode = await wasm._OrtRunWithBinding(\n        sessionHandle,\n        ioBindingState.handle,\n        outputCount,\n        outputValuesOffset,\n        runOptionsHandle,\n      );\n    } else {\n      errorCode = await wasm._OrtRun(\n        sessionHandle,\n        inputNamesOffset,\n        inputValuesOffset,\n        inputCount,\n        outputNamesOffset,\n        outputCount,\n        outputValuesOffset,\n        runOptionsHandle,\n      );\n    }\n\n    if (errorCode !== 0) {\n      checkLastError('failed to call OrtRun().');\n    }\n\n    const output: TensorMetadata[] = [];\n    const outputPromises: Array<Promise<[number, Tensor.DataType]>> = [];\n\n    TRACE_EVENT_BEGIN('wasm ProcessOutputTensor');\n    for (let i = 0; i < outputCount; i++) {\n      const tensor = Number(wasm.getValue(outputValuesOffset + i * ptrSize, '*'));\n      // TODO: revisit this part to ensure it works for WebGPU when both pre-allocated outputs and\n      // preferred location are specified.\n      // Certain pre-allocated tensors may already be bound in the IO binding. e.g. the WebNN backend\n      // always binds its tensor to 'ml-tensor'. In such cases, the tensor ID might change after binding,\n      // but copying data for these tensors should still be avoided.\n      if (tensor === outputTensorHandles[i] || preAllocatedOutputs.includes(outputTensorHandles[i])) {\n        // output tensor is pre-allocated. no need to copy data.\n        output.push(outputTensors[i]!);\n        if (tensor !== outputTensorHandles[i]) {\n          // release redundant tensor earlier.\n          if (wasm._OrtReleaseTensor(tensor) !== 0) {\n            checkLastError(\"Can't release tensor.\");\n          }\n        }\n        continue;\n      }\n\n      const beforeGetTensorDataStack = wasm.stackSave();\n      // stack allocate 4 pointer value\n      const tensorDataOffset = wasm.stackAlloc(4 * ptrSize);\n\n      let keepOutputTensor = false;\n      let type: Tensor.Type | undefined,\n        dataOffset = 0;\n      try {\n        const errorCode = wasm._OrtGetTensorData(\n          tensor,\n          tensorDataOffset,\n          tensorDataOffset + ptrSize,\n          tensorDataOffset + 2 * ptrSize,\n\n          tensorDataOffset + 3 * ptrSize,\n        );\n        if (errorCode !== 0) {\n          checkLastError(`Can't access output tensor data on index ${i}.`);\n        }\n        const valueType = ptrSize === 4 ? 'i32' : 'i64';\n        const dataType = Number(wasm.getValue(tensorDataOffset, valueType));\n        dataOffset = wasm.getValue(tensorDataOffset + ptrSize, '*');\n        const dimsOffset = wasm.getValue(tensorDataOffset + ptrSize * 2, '*');\n        const dimsLength = Number(wasm.getValue(tensorDataOffset + ptrSize * 3, valueType));\n        const dims = [];\n        for (let i = 0; i < dimsLength; i++) {\n          dims.push(Number(wasm.getValue(dimsOffset + i * ptrSize, valueType)));\n        }\n        if (wasm._OrtFree(dimsOffset) !== 0) {\n          checkLastError(\"Can't free memory for tensor dims.\");\n        }\n        const size = dims.reduce((a, b) => a * b, 1);\n        type = tensorDataTypeEnumToString(dataType);\n\n        const preferredLocation = ioBindingState?.outputPreferredLocations[outputIndices[i]];\n\n        if (type === 'string') {\n          if (preferredLocation === 'gpu-buffer' || preferredLocation === 'ml-tensor') {\n            throw new Error('String tensor is not supported on GPU.');\n          }\n          const stringData: string[] = [];\n          for (let i = 0; i < size; i++) {\n            const offset = wasm.getValue(dataOffset + i * ptrSize, '*');\n            const nextOffset = wasm.getValue(dataOffset + (i + 1) * ptrSize, '*');\n            const maxBytesToRead = i === size - 1 ? undefined : nextOffset - offset;\n            stringData.push(wasm.UTF8ToString(offset, maxBytesToRead));\n          }\n          output.push([type, dims, stringData, 'cpu']);\n        } else {\n          // If a certain output's preferred location is GPU but the tensor is empty, we still need to create a CPU\n          // tensor for it. There is no mapping GPU buffer for an empty tensor.\n          if (preferredLocation === 'gpu-buffer' && size > 0) {\n            const getBuffer = !BUILD_DEFS.DISABLE_WEBGPU ? wasm.webgpuGetBuffer : wasm.jsepGetBuffer;\n            if (!getBuffer) {\n              throw new Error('preferredLocation \"gpu-buffer\" is not supported without using WebGPU.');\n            }\n            const gpuBuffer = getBuffer(dataOffset);\n            const bufferSize = calculateTensorSizeInBytes(dataType, size);\n            if (bufferSize === undefined || !isGpuBufferSupportedType(type)) {\n              throw new Error(`Unsupported data type: ${type}`);\n            }\n\n            // do not release the tensor right now. it will be released when user calls tensor.dispose().\n            keepOutputTensor = true;\n\n            if (!BUILD_DEFS.DISABLE_WEBGPU) {\n              wasm.webgpuRegisterBuffer!(gpuBuffer, sessionId, dataOffset);\n              const downloadDataFunction = wasm.webgpuCreateDownloader!(gpuBuffer, bufferSize, sessionId);\n              output.push([\n                type,\n                dims,\n                {\n                  gpuBuffer,\n                  download: async () => {\n                    const arrayBuffer = await downloadDataFunction();\n                    const data = new (tensorTypeToTypedArrayConstructor(type!))(arrayBuffer);\n                    return data as Tensor.DataTypeMap[Tensor.GpuBufferDataTypes];\n                  },\n                  dispose: () => {\n                    if (wasm._OrtReleaseTensor(tensor) !== 0) {\n                      checkLastError(\"Can't release tensor.\");\n                    }\n                  },\n                },\n                'gpu-buffer',\n              ]);\n            } else {\n              output.push([\n                type,\n                dims,\n                {\n                  gpuBuffer,\n                  download: wasm.jsepCreateDownloader!(gpuBuffer, bufferSize, type),\n                  dispose: () => {\n                    if (wasm._OrtReleaseTensor(tensor) !== 0) {\n                      checkLastError(\"Can't release tensor.\");\n                    }\n                  },\n                },\n                'gpu-buffer',\n              ]);\n            }\n          } else if (preferredLocation === 'ml-tensor' && size > 0) {\n            const ensureTensor = wasm.webnnEnsureTensor;\n            const isGraphInputOutputTypeSupported = wasm.webnnIsGraphInputOutputTypeSupported;\n            if (!ensureTensor || !isGraphInputOutputTypeSupported) {\n              throw new Error('preferredLocation \"ml-tensor\" is not supported without using WebNN.');\n            }\n            const tensorSize = calculateTensorSizeInBytes(dataType, size);\n            if (tensorSize === undefined || !isMLTensorSupportedType(type)) {\n              throw new Error(`Unsupported data type: ${type}`);\n            }\n            if (!isGraphInputOutputTypeSupported(sessionId, type, false)) {\n              throw new Error(\n                `preferredLocation \"ml-tensor\" for ${type} output is not supported by current WebNN Context.`,\n              );\n            }\n\n            // If the graph has been partitioned, the output tensor may have not been created. For this reason, we use\n            // ensureTensor to get/create the MLTensor. In which case, we don't need to copy the data if a new tensor\n            // has been created.\n            const mlTensor = await ensureTensor(sessionId, dataOffset, dataType, dims, false);\n\n            // do not release the tensor right now. it will be released when user calls tensor.dispose().\n            keepOutputTensor = true;\n\n            output.push([\n              type,\n              dims,\n              {\n                mlTensor,\n                download: wasm.webnnCreateMLTensorDownloader!(dataOffset, type),\n                dispose: () => {\n                  wasm.webnnReleaseTensorId!(dataOffset);\n                  wasm._OrtReleaseTensor(tensor);\n                },\n              },\n              'ml-tensor',\n            ]);\n          } else if (preferredLocation === 'ml-tensor-cpu-output' && size > 0) {\n            const data = wasm.webnnCreateMLTensorDownloader!(dataOffset, type as Tensor.MLTensorDataTypes)();\n            const index = output.length;\n            // Delay the data download and releasing the tensor until we can wait for all output tensors to be downloaded.\n            keepOutputTensor = true;\n            outputPromises.push(\n              (async () => {\n                const result: [number, Tensor.DataType] = [index, await data];\n                wasm.webnnReleaseTensorId!(dataOffset);\n                wasm._OrtReleaseTensor(tensor);\n                return result;\n              })(),\n            );\n            output.push([type, dims, [], 'cpu']);\n          } else {\n            const typedArrayConstructor = tensorTypeToTypedArrayConstructor(type);\n            const data = new typedArrayConstructor(size);\n            new Uint8Array(data.buffer, data.byteOffset, data.byteLength).set(\n              wasm.HEAPU8.subarray(dataOffset, dataOffset + data.byteLength),\n            );\n            output.push([type, dims, data, 'cpu']);\n          }\n        }\n      } finally {\n        wasm.stackRestore(beforeGetTensorDataStack);\n        if (type === 'string' && dataOffset) {\n          wasm._free(dataOffset);\n        }\n        if (!keepOutputTensor) {\n          wasm._OrtReleaseTensor(tensor);\n        }\n      }\n    }\n\n    if (ioBindingState && !enableGraphCapture) {\n      if (wasm._OrtClearBoundOutputs(ioBindingState.handle) !== 0) {\n        checkLastError(\"Can't clear bound outputs.\");\n      }\n      activeSessions.set(sessionId, [\n        sessionHandle,\n        inputNamesUTF8Encoded,\n        outputNamesUTF8Encoded,\n        ioBindingState,\n        enableGraphCapture,\n        false,\n      ]);\n    }\n    // Wait for all output tensor data to be downloaded.\n    for (const [index, data] of await Promise.all(outputPromises)) {\n      output[index][2] = data;\n    }\n    TRACE_EVENT_END('wasm ProcessOutputTensor');\n    return output;\n  } finally {\n    wasm.webnnOnRunEnd?.(sessionHandle);\n\n    wasm.stackRestore(beforeRunStack);\n\n    if (!BUILD_DEFS.DISABLE_WEBGPU) {\n      inputTensors.forEach((t) => {\n        if (t && t[3] === 'gpu-buffer') {\n          wasm.webgpuUnregisterBuffer!(t[2].gpuBuffer);\n        }\n      });\n      outputTensors.forEach((t) => {\n        if (t && t[3] === 'gpu-buffer') {\n          wasm.webgpuUnregisterBuffer!(t[2].gpuBuffer);\n        }\n      });\n    }\n    inputTensorHandles.forEach((v) => wasm._OrtReleaseTensor(v));\n    outputTensorHandles.forEach((v) => wasm._OrtReleaseTensor(v));\n    inputOutputAllocs.forEach((p) => wasm._free(p));\n\n    if (runOptionsHandle !== 0) {\n      wasm._OrtReleaseRunOptions(runOptionsHandle);\n    }\n    runOptionsAllocs.forEach((p) => wasm._free(p));\n\n    for (const adapterId of loraAdapterIds) {\n      const count = loraAdapterRunCounts.get(adapterId)! - 1;\n      if (count === 0) {\n        loraAdapterRunCounts.delete(adapterId);\n      } else {\n        loraAdapterRunCounts.set(adapterId, count);\n      }\n    }\n  }\n};\n\n/**\n * end profiling\n */\nexport const endProfiling = (sessionId: number): void => {\n  const wasm = getInstance();\n  const session = activeSessions.get(sessionId);\n  if (!session) {\n    throw new Error('invalid session id');\n  }\n  const sessionHandle = session[0];\n\n  // profile file name is not used yet, but it must be freed.\n  const profileFileName = wasm._OrtEndProfiling(sessionHandle);\n  if (profileFileName === 0) {\n    checkLastError(\"Can't get an profile file name.\");\n  }\n  wasm._OrtFree(profileFileName);\n};\n\nexport const extractTransferableBuffers = (tensors: readonly SerializableTensorMetadata[]): ArrayBufferLike[] => {\n  const buffers: ArrayBufferLike[] = [];\n  for (const tensor of tensors) {\n    const data = tensor[2];\n    if (!Array.isArray(data) && 'buffer' in data) {\n      buffers.push(data.buffer);\n    }\n  }\n  return buffers;\n};\n","// Copyright (c) Microsoft Corporation. All rights reserved.\n// Licensed under the MIT License.\n\nimport { env, InferenceSession } from 'onnxruntime-common';\n\nimport {\n  OrtWasmMessage,\n  SerializableInternalBuffer,\n  SerializableSessionMetadata,\n  SerializableTensorMetadata,\n  TensorMetadata,\n} from './proxy-messages';\nimport * as core from './wasm-core-impl';\nimport { initializeWebAssembly } from './wasm-factory';\nimport {\n  importProxyWorker,\n  inferWasmPathPrefixFromScriptSrc,\n  isEsmImportMetaUrlHardcodedAsFileUri,\n} from './wasm-utils-import';\nimport { loadFile } from './wasm-utils-load-file';\n\nconst isProxy = (): boolean => !!env.wasm.proxy && typeof document !== 'undefined';\nlet proxyWorker: Worker | undefined;\nlet initializing = false;\nlet initialized = false;\nlet aborted = false;\nlet temporaryObjectUrl: string | undefined;\n\ntype PromiseCallbacks<T = void> = [resolve: (result: T) => void, reject: (reason: unknown) => void];\nlet initWasmCallbacks: PromiseCallbacks;\nconst queuedCallbacks: Map<OrtWasmMessage['type'], Array<PromiseCallbacks<unknown>>> = new Map();\n\nconst enqueueCallbacks = (type: OrtWasmMessage['type'], callbacks: PromiseCallbacks<unknown>): void => {\n  const queue = queuedCallbacks.get(type);\n  if (queue) {\n    queue.push(callbacks);\n  } else {\n    queuedCallbacks.set(type, [callbacks]);\n  }\n};\n\nconst ensureWorker = (): void => {\n  if (initializing || !initialized || aborted || !proxyWorker) {\n    throw new Error('worker not ready');\n  }\n};\n\nconst onProxyWorkerMessage = (ev: MessageEvent<OrtWasmMessage>): void => {\n  switch (ev.data.type) {\n    case 'init-wasm':\n      initializing = false;\n      if (ev.data.err) {\n        aborted = true;\n        initWasmCallbacks[1](ev.data.err);\n      } else {\n        initialized = true;\n        initWasmCallbacks[0]();\n      }\n      if (temporaryObjectUrl) {\n        URL.revokeObjectURL(temporaryObjectUrl);\n        temporaryObjectUrl = undefined;\n      }\n      break;\n    case 'init-ep':\n    case 'copy-from':\n    case 'create':\n    case 'release':\n    case 'run':\n    case 'end-profiling': {\n      const callbacks = queuedCallbacks.get(ev.data.type)!;\n      if (ev.data.err) {\n        callbacks.shift()![1](ev.data.err);\n      } else {\n        callbacks.shift()![0](ev.data.out!);\n      }\n      break;\n    }\n    default:\n  }\n};\n\nexport const initializeWebAssemblyAndOrtRuntime = async (): Promise<void> => {\n  if (initialized) {\n    return;\n  }\n  if (initializing) {\n    throw new Error(\"multiple calls to 'initWasm()' detected.\");\n  }\n  if (aborted) {\n    throw new Error(\"previous call to 'initWasm()' failed.\");\n  }\n\n  initializing = true;\n\n  if (!BUILD_DEFS.DISABLE_WASM_PROXY && isProxy()) {\n    return new Promise<void>((resolve, reject) => {\n      proxyWorker?.terminate();\n\n      void importProxyWorker().then(([objectUrl, worker]) => {\n        try {\n          proxyWorker = worker;\n          proxyWorker.onerror = (ev: ErrorEvent) => reject(ev);\n          proxyWorker.onmessage = onProxyWorkerMessage;\n          initWasmCallbacks = [resolve, reject];\n          const message: OrtWasmMessage = { type: 'init-wasm', in: env };\n\n          // if the proxy worker is loaded from a blob URL, we need to make sure the path information is not lost.\n          //\n          // when `env.wasm.wasmPaths` is not set, we need to pass the path information to the worker.\n          //\n          if (!BUILD_DEFS.ENABLE_BUNDLE_WASM_JS && !message.in!.wasm.wasmPaths && objectUrl) {\n            // for a build not bundled the wasm JS, we need to pass the path prefix to the worker.\n            // the path prefix will be used to resolve the path to both the wasm JS and the wasm file.\n            const inferredWasmPathPrefix = inferWasmPathPrefixFromScriptSrc();\n            if (inferredWasmPathPrefix) {\n              message.in!.wasm.wasmPaths = inferredWasmPathPrefix;\n            }\n          }\n\n          if (\n            BUILD_DEFS.IS_ESM &&\n            BUILD_DEFS.ENABLE_BUNDLE_WASM_JS &&\n            !message.in!.wasm.wasmPaths &&\n            (objectUrl || isEsmImportMetaUrlHardcodedAsFileUri)\n          ) {\n            // for a build bundled the wasm JS, if either of the following conditions is met:\n            // - the proxy worker is loaded from a blob URL\n            // - `import.meta.url` is a file URL, it means it is overwritten by the bundler.\n            //\n            // in either case, the path information is lost, we need to pass the path of the .wasm file to the worker.\n            // we need to use the bundler preferred URL format:\n            // new URL('filename', import.meta.url)\n            // so that the bundler can handle the file using corresponding loaders.\n            message.in!.wasm.wasmPaths = {\n              wasm: !BUILD_DEFS.DISABLE_JSEP\n                ? new URL('ort-wasm-simd-threaded.jsep.wasm', BUILD_DEFS.ESM_IMPORT_META_URL).href\n                : BUILD_DEFS.ENABLE_JSPI\n                  ? new URL('ort-wasm-simd-threaded.jspi.wasm', BUILD_DEFS.ESM_IMPORT_META_URL).href\n                  : !BUILD_DEFS.DISABLE_WEBGPU\n                    ? new URL('ort-wasm-simd-threaded.asyncify.wasm', BUILD_DEFS.ESM_IMPORT_META_URL).href\n                    : new URL('ort-wasm-simd-threaded.wasm', BUILD_DEFS.ESM_IMPORT_META_URL).href,\n            };\n          }\n          proxyWorker.postMessage(message);\n          temporaryObjectUrl = objectUrl;\n        } catch (e) {\n          reject(e);\n        }\n      }, reject);\n    });\n  } else {\n    try {\n      await initializeWebAssembly(env.wasm);\n      await core.initRuntime(env);\n      initialized = true;\n    } catch (e) {\n      aborted = true;\n      throw e;\n    } finally {\n      initializing = false;\n    }\n  }\n};\n\nexport const initializeOrtEp = async (epName: string): Promise<void> => {\n  if (!BUILD_DEFS.DISABLE_WASM_PROXY && isProxy()) {\n    ensureWorker();\n    return new Promise<void>((resolve, reject) => {\n      enqueueCallbacks('init-ep', [resolve, reject]);\n      const message: OrtWasmMessage = { type: 'init-ep', in: { epName, env } };\n      proxyWorker!.postMessage(message);\n    });\n  } else {\n    await core.initEp(env, epName);\n  }\n};\n\nexport const copyFromExternalBuffer = async (buffer: Uint8Array): Promise<SerializableInternalBuffer> => {\n  if (!BUILD_DEFS.DISABLE_WASM_PROXY && isProxy()) {\n    ensureWorker();\n    return new Promise<SerializableInternalBuffer>((resolve, reject) => {\n      enqueueCallbacks('copy-from', [resolve, reject]);\n      const message: OrtWasmMessage = { type: 'copy-from', in: { buffer } };\n      proxyWorker!.postMessage(message, [buffer.buffer]);\n    });\n  } else {\n    return core.copyFromExternalBuffer(buffer);\n  }\n};\n\nexport const createSession = async (\n  model: SerializableInternalBuffer | Uint8Array,\n  options?: InferenceSession.SessionOptions,\n): Promise<SerializableSessionMetadata> => {\n  if (!BUILD_DEFS.DISABLE_WASM_PROXY && isProxy()) {\n    // check unsupported options\n    if (options?.preferredOutputLocation) {\n      throw new Error('session option \"preferredOutputLocation\" is not supported for proxy.');\n    }\n    ensureWorker();\n    return new Promise<SerializableSessionMetadata>((resolve, reject) => {\n      enqueueCallbacks('create', [resolve, reject]);\n      const message: OrtWasmMessage = { type: 'create', in: { model, options: { ...options } } };\n      const transferable: Transferable[] = [];\n      if (model instanceof Uint8Array) {\n        transferable.push(model.buffer);\n      }\n      proxyWorker!.postMessage(message, transferable);\n    });\n  } else {\n    return core.createSession(model, options);\n  }\n};\n\nexport const releaseSession = async (sessionId: number): Promise<void> => {\n  if (!BUILD_DEFS.DISABLE_WASM_PROXY && isProxy()) {\n    ensureWorker();\n    return new Promise<void>((resolve, reject) => {\n      enqueueCallbacks('release', [resolve, reject]);\n      const message: OrtWasmMessage = { type: 'release', in: sessionId };\n      proxyWorker!.postMessage(message);\n    });\n  } else {\n    core.releaseSession(sessionId);\n  }\n};\n\nexport const createLoraAdapter = async (pathOrBuffer: string | Uint8Array): Promise<number> => {\n  if (!BUILD_DEFS.DISABLE_WASM_PROXY && isProxy()) {\n    throw new Error('LoRA adapter is not supported for proxy.');\n  }\n  const adapterData = typeof pathOrBuffer === 'string' ? await loadFile(pathOrBuffer) : pathOrBuffer;\n  return core.createLoraAdapter(adapterData);\n};\n\nexport const releaseLoraAdapter = async (adapterId: number): Promise<void> => {\n  if (!BUILD_DEFS.DISABLE_WASM_PROXY && isProxy()) {\n    throw new Error('LoRA adapter is not supported for proxy.');\n  }\n  core.releaseLoraAdapter(adapterId);\n};\n\nexport const run = async (\n  sessionId: number,\n  inputIndices: number[],\n  inputs: TensorMetadata[],\n  outputIndices: number[],\n  outputs: Array<TensorMetadata | null>,\n  options: InferenceSession.RunOptions,\n  loraAdapterIds: readonly number[],\n): Promise<TensorMetadata[]> => {\n  if (!BUILD_DEFS.DISABLE_WASM_PROXY && isProxy()) {\n    if (loraAdapterIds.length > 0) {\n      throw new Error('LoRA adapter is not supported for proxy.');\n    }\n    // check inputs location\n    if (inputs.some((t) => t[3] !== 'cpu')) {\n      throw new Error('input tensor on GPU is not supported for proxy.');\n    }\n    // check outputs location\n    if (outputs.some((t) => t)) {\n      throw new Error('pre-allocated output tensor is not supported for proxy.');\n    }\n    ensureWorker();\n    return new Promise<SerializableTensorMetadata[]>((resolve, reject) => {\n      enqueueCallbacks('run', [resolve, reject]);\n      const serializableInputs = inputs as SerializableTensorMetadata[]; // every input is on CPU.\n      const message: OrtWasmMessage = {\n        type: 'run',\n        in: { sessionId, inputIndices, inputs: serializableInputs, outputIndices, options },\n      };\n      proxyWorker!.postMessage(message, core.extractTransferableBuffers(serializableInputs));\n    });\n  } else {\n    return core.run(sessionId, inputIndices, inputs, outputIndices, outputs, options, loraAdapterIds);\n  }\n};\n\nexport const endProfiling = async (sessionId: number): Promise<void> => {\n  if (!BUILD_DEFS.DISABLE_WASM_PROXY && isProxy()) {\n    ensureWorker();\n    return new Promise<void>((resolve, reject) => {\n      enqueueCallbacks('end-profiling', [resolve, reject]);\n      const message: OrtWasmMessage = { type: 'end-profiling', in: sessionId };\n      proxyWorker!.postMessage(message);\n    });\n  } else {\n    core.endProfiling(sessionId);\n  }\n};\n","// Copyright (c) Microsoft Corporation. All rights reserved.\n// Licensed under the MIT License.\n\nimport { LoraAdapterHandler, TRACE_FUNC_BEGIN, TRACE_FUNC_END } from 'onnxruntime-common';\n\nimport { createLoraAdapter, releaseLoraAdapter } from './proxy-wrapper';\n\nexport class OnnxruntimeWebAssemblyLoraAdapterHandler implements LoraAdapterHandler {\n  adapterId: number;\n\n  async loadAdapter(pathOrBuffer: string | Uint8Array): Promise<void> {\n    TRACE_FUNC_BEGIN();\n    this.adapterId = await createLoraAdapter(pathOrBuffer);\n    TRACE_FUNC_END();\n  }\n\n  async dispose(): Promise<void> {\n    return releaseLoraAdapter(this.adapterId);\n  }\n}\n","// Copyright (c) Microsoft Corporation. All rights reserved.\n// Licensed under the MIT License.\n\nimport {\n  InferenceSession,\n  InferenceSessionHandler,\n  LoraAdapterHandler,\n  SessionHandler,\n  Tensor,\n  TRACE_FUNC_BEGIN,\n  TRACE_FUNC_END,\n} from 'onnxruntime-common';\n\nimport { OnnxruntimeWebAssemblyLoraAdapterHandler } from './lora-adapter-handler';\nimport { SerializableInternalBuffer, TensorMetadata } from './proxy-messages';\nimport { copyFromExternalBuffer, createSession, endProfiling, releaseSession, run } from './proxy-wrapper';\nimport { isGpuBufferSupportedType, isMLTensorSupportedType } from './wasm-common';\nimport { isNode } from './wasm-utils-env';\nimport { loadFile } from './wasm-utils-load-file';\n\nexport const encodeTensorMetadata = (tensor: Tensor, getName: () => string): TensorMetadata => {\n  switch (tensor.location) {\n    case 'cpu':\n      return [tensor.type, tensor.dims, tensor.data, 'cpu'];\n    case 'gpu-buffer':\n      return [tensor.type, tensor.dims, { gpuBuffer: tensor.gpuBuffer }, 'gpu-buffer'];\n    case 'ml-tensor':\n      return [tensor.type, tensor.dims, { mlTensor: tensor.mlTensor }, 'ml-tensor'];\n    default:\n      throw new Error(`invalid data location: ${tensor.location} for ${getName()}`);\n  }\n};\n\nexport const decodeTensorMetadata = (tensor: TensorMetadata): Tensor => {\n  switch (tensor[3]) {\n    case 'cpu':\n      return new Tensor(tensor[0], tensor[2], tensor[1]);\n    case 'gpu-buffer': {\n      const dataType = tensor[0];\n      if (!isGpuBufferSupportedType(dataType)) {\n        throw new Error(`not supported data type: ${dataType} for deserializing GPU tensor`);\n      }\n      const { gpuBuffer, download, dispose } = tensor[2];\n      return Tensor.fromGpuBuffer(gpuBuffer, { dataType, dims: tensor[1], download, dispose });\n    }\n    case 'ml-tensor': {\n      const dataType = tensor[0];\n      if (!isMLTensorSupportedType(dataType)) {\n        throw new Error(`not supported data type: ${dataType} for deserializing MLTensor tensor`);\n      }\n      const { mlTensor, download, dispose } = tensor[2];\n      return Tensor.fromMLTensor(mlTensor, { dataType, dims: tensor[1], download, dispose });\n    }\n    default:\n      throw new Error(`invalid data location: ${tensor[3]}`);\n  }\n};\n\nexport class OnnxruntimeWebAssemblySessionHandler implements InferenceSessionHandler {\n  private sessionId: number;\n\n  inputNames: readonly string[];\n  outputNames: readonly string[];\n  inputMetadata: readonly InferenceSession.ValueMetadata[];\n  outputMetadata: readonly InferenceSession.ValueMetadata[];\n\n  async fetchModelAndCopyToWasmMemory(path: string): Promise<SerializableInternalBuffer> {\n    // fetch model from url and move to wasm heap.\n    return copyFromExternalBuffer(await loadFile(path));\n  }\n\n  async loadModel(pathOrBuffer: string | Uint8Array, options?: InferenceSession.SessionOptions): Promise<void> {\n    TRACE_FUNC_BEGIN();\n    let model: Parameters<typeof createSession>[0];\n\n    if (typeof pathOrBuffer === 'string') {\n      if (isNode) {\n        // node\n        model = await loadFile(pathOrBuffer);\n      } else {\n        // browser\n        // fetch model and copy to wasm heap.\n        model = await this.fetchModelAndCopyToWasmMemory(pathOrBuffer);\n      }\n    } else {\n      model = pathOrBuffer;\n    }\n\n    [this.sessionId, this.inputNames, this.outputNames, this.inputMetadata, this.outputMetadata] = await createSession(\n      model,\n      options,\n    );\n    TRACE_FUNC_END();\n  }\n\n  async dispose(): Promise<void> {\n    return releaseSession(this.sessionId);\n  }\n\n  async run(\n    feeds: SessionHandler.FeedsType,\n    fetches: SessionHandler.FetchesType,\n    options: InferenceSession.RunOptions,\n    activeLoraAdapters: readonly LoraAdapterHandler[] = [],\n  ): Promise<SessionHandler.ReturnType> {\n    TRACE_FUNC_BEGIN();\n    const loraAdapterIds = activeLoraAdapters.map((adapter) => {\n      if (!(adapter instanceof OnnxruntimeWebAssemblyLoraAdapterHandler)) {\n        throw new Error('LoRA adapter was not created by the WebAssembly backend.');\n      }\n      return adapter.adapterId;\n    });\n\n    const inputArray: Tensor[] = [];\n    const inputIndices: number[] = [];\n    Object.entries(feeds).forEach((kvp) => {\n      const name = kvp[0];\n      const tensor = kvp[1];\n      const index = this.inputNames.indexOf(name);\n      if (index === -1) {\n        throw new Error(`invalid input '${name}'`);\n      }\n      inputArray.push(tensor);\n      inputIndices.push(index);\n    });\n\n    const outputArray: Array<Tensor | null> = [];\n    const outputIndices: number[] = [];\n    Object.entries(fetches).forEach((kvp) => {\n      const name = kvp[0];\n      const tensor = kvp[1];\n      const index = this.outputNames.indexOf(name);\n      if (index === -1) {\n        throw new Error(`invalid output '${name}'`);\n      }\n      outputArray.push(tensor);\n      outputIndices.push(index);\n    });\n\n    const inputs = inputArray.map((t, i) =>\n      encodeTensorMetadata(t, () => `input \"${this.inputNames[inputIndices[i]]}\"`),\n    );\n    const outputs = outputArray.map((t, i) =>\n      t ? encodeTensorMetadata(t, () => `output \"${this.outputNames[outputIndices[i]]}\"`) : null,\n    );\n\n    const results = await run(this.sessionId, inputIndices, inputs, outputIndices, outputs, options, loraAdapterIds);\n\n    const resultMap: SessionHandler.ReturnType = {};\n    for (let i = 0; i < results.length; i++) {\n      resultMap[this.outputNames[outputIndices[i]]] = outputArray[i] ?? decodeTensorMetadata(results[i]);\n    }\n    TRACE_FUNC_END();\n    return resultMap;\n  }\n\n  startProfiling(): void {\n    // TODO: implement profiling\n  }\n\n  endProfiling(): void {\n    void endProfiling(this.sessionId);\n  }\n}\n","// Copyright (c) Microsoft Corporation. All rights reserved.\n// Licensed under the MIT License.\n\nimport type { InferenceSession } from 'onnxruntime-common';\n\nexport const validateSessionOptions = (options?: InferenceSession.SessionOptions): void => {\n  if (options?.epContextDataRead) {\n    throw new Error('session option \"epContextDataRead\" is not supported by ONNX Runtime Web');\n  }\n};\n","// Copyright (c) Microsoft Corporation. All rights reserved.\n// Licensed under the MIT License.\n\nimport { Backend, env, InferenceSession, InferenceSessionHandler, LoraAdapterHandler } from 'onnxruntime-common';\n\nimport { OnnxruntimeWebAssemblyLoraAdapterHandler } from './wasm/lora-adapter-handler';\nimport { initializeOrtEp, initializeWebAssemblyAndOrtRuntime } from './wasm/proxy-wrapper';\nimport { OnnxruntimeWebAssemblySessionHandler } from './wasm/session-handler-inference';\nimport { validateSessionOptions } from './validate-session-options';\n\n/**\n * This function initializes all flags for WebAssembly.\n *\n * Those flags are accessible from `ort.env.wasm`. Users are allow to set those flags before the first inference session\n * being created, to override default value.\n */\nexport const initializeFlags = (): void => {\n  if (typeof env.wasm.initTimeout !== 'number' || env.wasm.initTimeout < 0) {\n    env.wasm.initTimeout = 0;\n  }\n\n  const simd = env.wasm.simd;\n  if (typeof simd !== 'boolean' && simd !== undefined && simd !== 'fixed' && simd !== 'relaxed') {\n    // eslint-disable-next-line no-console\n    console.warn(\n      `Property \"env.wasm.simd\" is set to unknown value \"${simd}\". Reset it to \\`false\\` and ignore SIMD feature checking.`,\n    );\n    env.wasm.simd = false;\n  }\n\n  if (typeof env.wasm.proxy !== 'boolean') {\n    env.wasm.proxy = false;\n  }\n\n  if (typeof env.wasm.trace !== 'boolean') {\n    env.wasm.trace = false;\n  }\n\n  if (typeof env.wasm.numThreads !== 'number' || !Number.isInteger(env.wasm.numThreads) || env.wasm.numThreads <= 0) {\n    // The following logic only applies when `ort.env.wasm.numThreads` is not set by user. We will always honor user's\n    // setting if it is provided.\n\n    // Browser: when crossOriginIsolated is false, SharedArrayBuffer is not available so WebAssembly threads will not\n    // work. In this case, we will set numThreads to 1.\n    //\n    // There is an exception: when the browser is configured to force-enable SharedArrayBuffer (e.g. Chromuim with\n    // --enable-features=SharedArrayBuffer), it is possible that `self.crossOriginIsolated` is false and\n    // SharedArrayBuffer is available at the same time. This is usually for testing. In this case,  we will still set\n    // numThreads to 1 here. If we want to enable multi-threading in test, we should set `ort.env.wasm.numThreads` to a\n    // value greater than 1.\n    if (typeof self !== 'undefined' && !self.crossOriginIsolated) {\n      env.wasm.numThreads = 1;\n    } else {\n      const numCpuLogicalCores =\n        typeof navigator === 'undefined' ? require('node:os').cpus().length : navigator.hardwareConcurrency;\n      env.wasm.numThreads = Math.min(4, Math.ceil((numCpuLogicalCores || 1) / 2));\n    }\n  }\n};\n\nexport class OnnxruntimeWebAssemblyBackend implements Backend {\n  /**\n   * This function initializes the WebAssembly backend.\n   *\n   * This function will be called only once for each backend name. It will be called the first time when\n   * `ort.InferenceSession.create()` is called with a registered backend name.\n   *\n   * @param backendName - the registered backend name.\n   */\n  async init(backendName: string): Promise<void> {\n    // populate wasm flags\n    initializeFlags();\n\n    // init wasm\n    await initializeWebAssemblyAndOrtRuntime();\n\n    // performe EP specific initialization\n    await initializeOrtEp(backendName);\n  }\n  createInferenceSessionHandler(\n    path: string,\n    options?: InferenceSession.SessionOptions,\n  ): Promise<InferenceSessionHandler>;\n  createInferenceSessionHandler(\n    buffer: Uint8Array,\n    options?: InferenceSession.SessionOptions,\n  ): Promise<InferenceSessionHandler>;\n  async createInferenceSessionHandler(\n    pathOrBuffer: string | Uint8Array,\n    options?: InferenceSession.SessionOptions,\n  ): Promise<InferenceSessionHandler> {\n    validateSessionOptions(options);\n    const handler = new OnnxruntimeWebAssemblySessionHandler();\n    await handler.loadModel(pathOrBuffer, options);\n    return handler;\n  }\n  async createLoraAdapterHandler(pathOrBuffer: string | Uint8Array): Promise<LoraAdapterHandler> {\n    const handler = new OnnxruntimeWebAssemblyLoraAdapterHandler();\n    await handler.loadAdapter(pathOrBuffer);\n    return handler;\n  }\n}\n\nexport const wasmBackend = new OnnxruntimeWebAssemblyBackend();\n","// Copyright (c) Microsoft Corporation. All rights reserved.\n// Licensed under the MIT License.\n\n/* eslint-disable @typescript-eslint/no-var-requires, @typescript-eslint/no-require-imports */\n\n// We use \"require\" instead of \"import\" here because import statement must be put in top level. Our current code does\n// not allow bundler to tree-shaking code as expected because some codes are treated as having side effects.\n// So we import code inside the if-clause to allow bundler remove the code safely.\n\nexport * from 'onnxruntime-common';\nimport * as ort from 'onnxruntime-common';\nexport default ort;\n\nimport { registerBackend, env } from 'onnxruntime-common';\nimport { version } from './version';\n\nif (!BUILD_DEFS.DISABLE_WEBGL) {\n  const onnxjsBackend = require('./backend-onnxjs').onnxjsBackend;\n  registerBackend('webgl', onnxjsBackend, -10);\n}\n\nif (!BUILD_DEFS.DISABLE_JSEP && !BUILD_DEFS.DISABLE_WEBGPU) {\n  throw new Error(\n    'The current build is specified to enable both JSEP and WebGPU EP. This is not a valid configuration. ' +\n      'JSEP and WebGPU EPs cannot be enabled at the same time.',\n  );\n}\n\nif (!BUILD_DEFS.DISABLE_WEBNN && BUILD_DEFS.DISABLE_JSEP && BUILD_DEFS.DISABLE_WEBGPU) {\n  throw new Error(\n    'The current build is specified to enable WebNN EP without JSEP or WebGPU EP. This is not a valid configuration. ' +\n      'WebNN EP requires either JSEP or WebGPU EP to be enabled.',\n  );\n}\n\nif (!BUILD_DEFS.DISABLE_WASM) {\n  const wasmBackend = require('./backend-wasm').wasmBackend;\n  if (!BUILD_DEFS.DISABLE_JSEP || !BUILD_DEFS.DISABLE_WEBGPU) {\n    registerBackend('webgpu', wasmBackend, 5);\n  }\n  if (!BUILD_DEFS.DISABLE_WEBNN) {\n    registerBackend('webnn', wasmBackend, 5);\n  }\n  registerBackend('cpu', wasmBackend, 10);\n  registerBackend('wasm', wasmBackend, 10);\n}\n\nObject.defineProperty(env.versions, 'web', { value: version, enumerable: true });\n","// Copyright (c) Microsoft Corporation. All rights reserved.\n// Licensed under the MIT License.\n\n// This file is generated by /js/scripts/update-version.ts\n// Do not modify file content manually.\n\nexport const version = '1.31.1';\n"]}