{"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/session-handler-inference.ts","../lib/backend-wasm.ts","../lib/backend-wasm-inference.ts","../lib/index.ts","../lib/version.ts"],"names":["isNode","init_wasm_utils_env","__esmMin","scriptSrc","origin","isSameOrigin","normalizeUrl","fallbackUrl","preload","dynamicImportDefault","importWasmModule","init_wasm_utils_import","filename","prefixOverride","baseUrl","absoluteUrl","blob","url","urlOverride","isMultiThreaded","wasmModuleFilename","wasmModuleUrl","needPreload","wasm","initialized","initializing","aborted","isMultiThreadSupported","isSimdSupported","initializeWebAssembly","getInstance","init_wasm_factory","flags","timeout","numThreads","multiThreadSupported","wasmPaths","wasmPrefixOverride","mjsPathOverrideFlag","mjsPathOverride","wasmPathOverrideFlag","wasmPathOverride","wasmBinaryOverride","objectUrl","ortWasmFactory","isTimeout","tasks","resolve","reject","config","fileName","scriptDirectory","module","what","allocWasmString","iterateExtraOptions","checkLastError","init_wasm_utils","data","allocs","dataLength","dataOffset","options","prefix","seen","handler","key","value","name","message","stack","paramsOffset","errorCode","errorMessagePointer","errorMessage","setRunOptions","init_run_options","runOptionsHandle","runOptions","tagDataOffset","keyDataOffset","valueDataOffset","e","alloc","getGraphOptimzationLevel","getExecutionMode","appendDefaultOptions","setExecutionProviders","setSessionOptions","init_session_options","graphOptimizationLevel","executionMode","session","ep","sessionOptionsHandle","executionProviders","epName","deviceType","webgpuOptions","epNameDataOffset","sessionOptions","logIdDataOffset","logSeverityLevel","logVerbosityLevel","optimizedModelFilePathOffset","nameOffset","tensorDataTypeStringToEnum","tensorDataTypeEnumToString","getTensorElementSize","tensorTypeToTypedArrayConstructor","logLevelStringToEnum","isGpuBufferSupportedType","dataLocationStringToEnum","init_wasm_common","type","typeProto","dateType","logLevel","location","loadFile","init_wasm_utils_load_file","file","readFile","createReadStream","stream","chunks","chunk","response","contentLengthHeader","fileSize","reader","buffer","pages","offset","done","chunkSize","initOrt","initRuntime","initEp","activeSessions","getSessionInputOutputCount","copyFromExternalBuffer","createSession","releaseSession","prepareInputOutputTensor","run","endProfiling","init_wasm_core_impl","loggingLevel","env","sessionHandle","model","modelDataOffset","modelData","modelDataLength","ioBindingHandle","inputNamesUTF8Encoded","outputNamesUTF8Encoded","loadingPromises","path","provider","webnnOptions","context","gpuDevice","powerPreference","inputCount","outputCount","enableGraphCapture","inputNames","outputNames","outputPreferredLocations","i","nameString","bindingState","buf","sessionId","ioBindingState","tensor","tensorHandles","index","dataType","dims","rawData","dataByteLength","gpuBuffer","elementSizeInBytes","a","b","registerBuffer","dataIndex","dimsOffset","dimIndex","d","inputIndices","inputTensors","outputIndices","outputTensors","inputOutputBound","runOptionsAllocs","inputTensorHandles","outputTensorHandles","inputOutputAllocs","beforeRunStack","inputValuesOffset","inputNamesOffset","outputValuesOffset","outputNamesOffset","inputValuesIndex","inputNamesIndex","outputValuesIndex","outputNamesIndex","output","beforeGetTensorDataStack","tensorDataOffset","keepOutputTensor","tensorDataIndex","dimsLength","size","preferredLocation","stringData","maxBytesToRead","getBuffer","elementSize","typedArrayConstructor","v","p","profileFileName","initializeWebAssemblyAndOrtRuntime","initializeOrtEp","init_proxy_wrapper","inputs","outputs","Tensor","TRACE_FUNC_BEGIN","TRACE_FUNC_END","encodeTensorMetadata","decodeTensorMetadata","OnnxruntimeWebAssemblySessionHandler","init_session_handler_inference","getName","download","dispose","pathOrBuffer","feeds","fetches","inputArray","kvp","outputArray","t","results","resultMap","initializeFlags","OnnxruntimeWebAssemblyBackend","init_backend_wasm","numCpuLogicalCores","backendName","backend_wasm_inference_exports","__export","wasmBackend","init_backend_wasm_inference","ort","registerBackend","version","lib_default"],"mappings":";;;;;;usBAAA,IAGa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AAc,EAY9G,GAAI,OAAO,KAAS,KAAe,CAAC,KAAK,oBACvCA,EAAI,KAAK,WAAa,MACjB,CACL,IAAMyG,EACF,OAAO,UAAc,IAAc,GAAQ,SAAS,EAAE,KAAK,EAAE,OAAS,UAAU,oBACpFzG,EAAI,KAAK,WAAa,KAAK,IAAI,EAAG,KAAK,MAAMyG,GAAsB,GAAK,CAAC,CAAC,CAC5E,CAKIzG,EAAI,KAAK,YAAc,QAAalJ,GAAaA,EAAU,QAAQ,OAAO,IAAM,IAClFkJ,EAAI,KAAK,UAAYlJ,EAAU,UAAU,EAAGA,EAAU,YAAY,GAAG,EAAI,CAAC,EAGhF,EAEayP,GAAN,KAAuD,CAS5D,MAAM,KAAKG,EAAoC,CAE7CJ,GAAgB,EAGhB,MAAMxB,GAAmC,EAGzC,MAAMC,GAAgB2B,CAAW,CACnC,CAKA,MAAM,8BAA8Bb,EAAiCpL,EAChC,CACnC,IAAMG,EAAU,IAAI4K,GACpB,aAAM5K,EAAQ,UAAUiL,EAAcpL,CAAO,EACtC,QAAQ,QAAQG,CAAO,CAChC,CACF,IC7FA,IAAA+L,GAAA,GAAAC,GAAAD,GAAA,iBAAAE,KAAA,IAIaA,GAJbC,GAAAjQ,EAAA,kBAGA2P,KACaK,GAAc,IAAIN,KCK/B,WAAc,qBACd,UAAYQ,OAAS,qBAGrB,OAAQ,mBAAAC,GAAiB,OAAAhH,OAAU,qBCP5B,IAAMiH,GAAU,SDKvB,IAAOC,GAAQH,GAUe,CAC5B,IAAMF,EAA4C,cAAoC,YAMtFG,GAAgB,MAAOH,EAAa,EAAE,EACtCG,GAAgB,OAAQH,EAAa,EAAE,CACzC,CAEA,OAAO,eAAe7G,GAAI,SAAU,MAAO,CAAC,MAAOiH,GAAS,WAAY,EAAI,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 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 =\n    // if Nodejs, return undefined\n    isNode ? undefined :\n             // if It's ESM, use import.meta.url\n             BUILD_DEFS.ESM_IMPORT_META_URL ??\n        // use `document.currentScript.src` if available\n        (typeof document !== 'undefined' ? (document.currentScript as HTMLScriptElement)?.src :\n                                           // use `self.location.href` if available\n                                           (typeof self !== 'undefined' ? self.location?.href : undefined));\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 * 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> => (await import(/* webpackIgnore: true */ 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.DISABLE_DYNAMIC_IMPORT ?\n    // eslint-disable-next-line @typescript-eslint/no-require-imports, @typescript-eslint/no-var-requires\n    require(\n        !BUILD_DEFS.DISABLE_TRAINING ? '../../dist/ort-training-wasm-simd-threaded.mjs' :\n            !BUILD_DEFS.DISABLE_JSEP ? '../../dist/ort-wasm-simd-threaded.jsep.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 BUILD_DEFS.DISABLE_DYNAMIC_IMPORT is true, 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, prefixOverride: string|undefined,\n    isMultiThreaded: boolean): Promise<[undefined | string, EmscriptenModuleFactory<OrtWasmModule>]> => {\n  if (BUILD_DEFS.DISABLE_DYNAMIC_IMPORT) {\n    return [undefined, embeddedWasmModule!];\n  } else {\n    const wasmModuleFilename = !BUILD_DEFS.DISABLE_TRAINING ? 'ort-training-wasm-simd-threaded.mjs' :\n        !BUILD_DEFS.DISABLE_JSEP                            ? 'ort-wasm-simd-threaded.jsep.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 ? (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} 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(new Uint8Array([\n      0, 97, 115, 109, 1, 0,  0,  0, 1, 4, 1,  96, 0,   0,  3, 2, 1,  0, 5,\n      4, 1,  3,   1,   1, 10, 11, 1, 9, 0, 65, 0,  254, 16, 2, 0, 26, 11\n    ]));\n  } catch (e) {\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(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,\n      253, 15, 253, 12,  0, 0, 0, 0, 0, 0, 0, 0,  0, 0, 0, 0, 0, 0, 0,  0,  253, 186, 1, 26, 11\n    ]));\n  } catch (e) {\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 (!isSimdSupported()) {\n    throw new Error('WebAssembly SIMD is not supported in the current environment.');\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 ' + 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    // eslint-disable-next-line no-console\n    console.warn(\n        'WebAssembly multi-threading is not supported in the current environment. ' +\n        'Falling back to single-threading.');\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(mjsPathOverride, wasmPrefixOverride, numThreads > 1));\n\n  let isTimeout = false;\n\n  const tasks: Array<Promise<void>> = [];\n\n  // promise for timeout\n  if (timeout > 0) {\n    tasks.push(new Promise((resolve) => {\n      setTimeout(() => {\n        isTimeout = true;\n        resolve();\n      }, timeout);\n    }));\n  }\n\n  // promise for module initialization\n  tasks.push(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      /**\n       * Set a custom buffer which contains the WebAssembly binary. This will skip the wasm file fetching.\n       */\n      config.wasmBinary = wasmBinaryOverride;\n    } else if (wasmPathOverride || wasmPrefixOverride) {\n      /**\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       */\n      config.locateFile = (fileName, scriptDirectory) =>\n          wasmPathOverride ?? (wasmPrefixOverride ?? scriptDirectory) + fileName;\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  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>, prefix: string, seen: WeakSet<Record<string, unknown>>,\n     handler: ExtraOptionsHandler): 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 paramsOffset = wasm.stackAlloc(8);\n    wasm._OrtGetLastError(paramsOffset, paramsOffset + 4);\n    const errorCode = wasm.HEAP32[paramsOffset / 4];\n    const errorMessagePointer = wasm.HEAPU32[paramsOffset / 4 + 1];\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 = (options: InferenceSession.RunOptions): [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' || !Number.isInteger(options.logSeverityLevel) ||\n        options.logSeverityLevel < 0 || options.logSeverityLevel > 4) {\n      throw new Error(`log serverity 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!, runOptions.logVerbosityLevel!, !!runOptions.terminate!, tagDataOffset);\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    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 {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 '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 (options.executionProviders &&\n      options.executionProviders.some(ep => (typeof ep === 'string' ? ep : ep.name) === 'webgpu')) {\n    options.enableMemPattern = false;\n  }\n};\n\nconst setExecutionProviders =\n    (sessionOptionsHandle: number, executionProviders: readonly InferenceSession.ExecutionProviderConfig[],\n     allocs: number[]): void => {\n      for (const ep of executionProviders) {\n        let epName = typeof ep === 'string' ? ep : ep.name;\n\n        // check EP name\n        switch (epName) {\n          case 'webnn':\n            epName = 'WEBNN';\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                const keyDataOffset = allocWasmString('deviceType', allocs);\n                const valueDataOffset = allocWasmString(deviceType, allocs);\n                if (getInstance()._OrtAddSessionConfigEntry(sessionOptionsHandle, keyDataOffset, valueDataOffset) !==\n                    0) {\n                  checkLastError(`Can't set a session config entry: 'deviceType' - ${deviceType}.`);\n                }\n              }\n            }\n            break;\n          case 'webgpu':\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                const keyDataOffset = allocWasmString('preferredLayout', allocs);\n                const valueDataOffset = allocWasmString(webgpuOptions.preferredLayout, allocs);\n                if (getInstance()._OrtAddSessionConfigEntry(sessionOptionsHandle, keyDataOffset, valueDataOffset) !==\n                    0) {\n                  checkLastError(\n                      `Can't set a session config entry: 'preferredLayout' - ${webgpuOptions.preferredLayout}.`);\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 epNameDataOffset = allocWasmString(epName, allocs);\n        if (getInstance()._OrtAppendExecutionProvider(sessionOptionsHandle, epNameDataOffset) !== 0) {\n          checkLastError(`Can't append execution provider: ${epName}.`);\n        }\n      }\n    };\n\nexport const setSessionOptions = (options?: InferenceSession.SessionOptions): [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 serverity 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 = typeof sessionOptions.optimizedModelFilePath === 'string' ?\n        allocWasmString(sessionOptions.optimizedModelFilePath, allocs) :\n        0;\n\n    sessionOptionsHandle = wasm._OrtCreateSessionOptions(\n        graphOptimizationLevel, !!sessionOptions.enableCpuMemArena, !!sessionOptions.enableMemPattern, executionMode,\n        !!sessionOptions.enableProfiling, 0, logIdDataOffset, logSeverityLevel, logVerbosityLevel,\n        optimizedModelFilePathOffset);\n    if (sessionOptionsHandle === 0) {\n      checkLastError('Can\\'t create session options.');\n    }\n\n    if (sessionOptions.executionProviders) {\n      setExecutionProviders(sessionOptionsHandle, sessionOptions.executionProviders, 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      const keyDataOffset = allocWasmString('enableGraphCapture', allocs);\n      const valueDataOffset = allocWasmString(sessionOptions.enableGraphCapture.toString(), allocs);\n      if (wasm._OrtAddSessionConfigEntry(sessionOptionsHandle, keyDataOffset, valueDataOffset) !== 0) {\n        checkLastError(\n            `Can't set a session config entry: 'enableGraphCapture' - ${sessionOptions.enableGraphCapture}.`);\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        const keyDataOffset = allocWasmString(key, allocs);\n        const valueDataOffset = allocWasmString(value, allocs);\n\n        if (wasm._OrtAddSessionConfigEntry(sessionOptionsHandle, keyDataOffset, valueDataOffset) !== 0) {\n          checkLastError(`Can't set a session config entry: ${key} - ${value}.`);\n        }\n      });\n    }\n\n    return [sessionOptionsHandle, allocs];\n  } catch (e) {\n    if (sessionOptionsHandle !== 0) {\n      wasm._OrtReleaseSessionOptions(sessionOptionsHandle);\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// a dummy type declaration for Float16Array in case any polyfill is available.\ndeclare global {\n  // eslint-disable-next-line @typescript-eslint/naming-convention, @typescript-eslint/no-explicit-any\n  const Float16Array: any;\n}\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\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\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\n    default:\n      throw new Error(`unsupported data type: ${typeProto}`);\n  }\n};\n\n/**\n * get tensor element size in bytes by the given data type\n * @returns size in integer or undefined if the data type is not supported\n */\nexport const getTensorElementSize = (dateType: number): number|\n    undefined => [undefined, 4, 1, 1, 2, 2, 4, 8, undefined, 1, 2, 8, 4, 8, undefined, undefined, undefined][dateType];\n\n/**\n * get typed array constructor by the given tensor type\n */\nexport const tensorTypeToTypedArrayConstructor = (type: Tensor.Type): Float32ArrayConstructor|Uint8ArrayConstructor|\n    Int8ArrayConstructor|Uint16ArrayConstructor|Int16ArrayConstructor|Int32ArrayConstructor|BigInt64ArrayConstructor|\n    Uint8ArrayConstructor|Float64ArrayConstructor|Uint32ArrayConstructor|BigUint64ArrayConstructor => {\n      switch (type) {\n        case 'float16':\n          // allow Float16Array polyfill.\n          return typeof Float16Array !== 'undefined' && Float16Array.from ? Float16Array : 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 => type === 'float32' ||\n    type === 'float16' || type === 'int32' || type === 'int64' || type === 'uint32' || type === 'uint8' ||\n    type === 'bool';\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    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'] 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        // eslint-disable-next-line no-constant-condition\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\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} from 'onnxruntime-common';\n\nimport {SerializableInternalBuffer, SerializableSessionMetadata, SerializableTensorMetadata, TensorMetadata} from './proxy-messages';\nimport {setRunOptions} from './run-options';\nimport {setSessionOptions} from './session-options';\nimport {dataLocationStringToEnum, getTensorElementSize, isGpuBufferSupportedType, logLevelStringToEnum, tensorDataTypeEnumToString, tensorDataTypeStringToEnum, tensorTypeToTypedArrayConstructor} 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()` or\n * `ort.TrainingSession.create()` is 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()` or `ort.TrainingSession.create()` is called. Unlike the first 3\n * steps (they only called once), this step will be done for each session. In this step, onnxruntime-web does the\n * 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  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      // perform WebGPU availability check\n      if (typeof navigator === 'undefined' || !navigator.gpu) {\n        throw new Error('WebGPU is not supported in current environment');\n      }\n\n      let adapter = env.webgpu.adapter as GPUAdapter | null;\n      if (!adapter) {\n        // if adapter is not set, request a new adapter.\n        const powerPreference = env.webgpu.powerPreference;\n        if (powerPreference !== undefined && powerPreference !== 'low-power' &&\n            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        adapter = await navigator.gpu.requestAdapter({powerPreference, forceFallbackAdapter});\n        if (!adapter) {\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      } else {\n        // if adapter is set, validate it.\n        if (typeof adapter.limits !== 'object' || typeof adapter.features !== 'object' ||\n            typeof adapter.requestDevice !== 'function') {\n          throw new Error('Invalid GPU adapter set in `env.webgpu.adapter`. It must be a GPUAdapter object.');\n        }\n      }\n\n      await initJsep('webgpu', getInstance(), env, adapter);\n    }\n    if (epName === 'webnn') {\n      // perform WebNN availability check\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      await initJsep('webnn', getInstance(), env);\n    }\n  }\n};\n\n// #endregion Initializations\n\n/**\n * valid data locations for input/output tensors.\n */\ntype SupportedTensorDataLocationForInputOutput = 'cpu'|'cpu-pinned'|'gpu-buffer';\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'.\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, inputNamesUTF8Encoded: number[], outputNamesUTF8Encoded: number[],\n  bindingState: IOBindingState|null, enableGraphCapture: boolean, 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 dataOffset = wasm.stackAlloc(8);\n    const errorCode = wasm._OrtGetInputOutputCount(sessionHandle, dataOffset, dataOffset + 4);\n    if (errorCode !== 0) {\n      checkLastError('Can\\'t get session input/output count.');\n    }\n    return [wasm.HEAP32[dataOffset / 4], wasm.HEAP32[dataOffset / 4 + 1]];\n  } finally {\n    wasm.stackRestore(stack);\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): 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] = 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        loadingPromises.push(loadFile(typeof file === 'string' ? file : file.data).then(data => {\n          wasm.mountExternalData!(path, data);\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        if (wasm.currentContext) {\n          throw new Error('WebNN execution provider is already set.');\n        }\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 numThreads = (webnnOptions as InferenceSession.WebNNContextOptions)?.numThreads;\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 navigator.ml.createContext(gpuDevice);\n          } else {\n            wasm.currentContext = await navigator.ml.createContext({deviceType, numThreads, powerPreference});\n          }\n        } else {\n          wasm.currentContext = await navigator.ml.createContext();\n        }\n        break;\n      }\n    }\n\n    sessionHandle = await wasm._OrtCreateSession(modelDataOffset, modelDataLength, sessionOptionsHandle);\n    if (sessionHandle === 0) {\n      checkLastError('Can\\'t create a session.');\n    }\n\n    // clear current MLContext after session creation\n    if (wasm.currentContext) {\n      wasm.currentContext = undefined;\n    }\n\n    const [inputCount, outputCount] = getSessionInputOutputCount(sessionHandle);\n\n    const enableGraphCapture = !!options?.enableGraphCapture;\n\n    const inputNames = [];\n    const outputNames = [];\n    const outputPreferredLocations: SupportedTensorDataLocationForInputOutput[] = [];\n    for (let i = 0; i < inputCount; i++) {\n      const name = wasm._OrtGetInputName(sessionHandle, i);\n      if (name === 0) {\n        checkLastError('Can\\'t get an input name.');\n      }\n      inputNamesUTF8Encoded.push(name);\n      inputNames.push(wasm.UTF8ToString(name));\n    }\n    for (let i = 0; i < outputCount; i++) {\n      const name = wasm._OrtGetOutputName(sessionHandle, i);\n      if (name === 0) {\n        checkLastError('Can\\'t get an output name.');\n      }\n      outputNamesUTF8Encoded.push(name);\n      const nameString = wasm.UTF8ToString(name);\n      outputNames.push(nameString);\n\n      if (!BUILD_DEFS.DISABLE_JSEP) {\n        if (enableGraphCapture && options?.preferredOutputLocation === undefined) {\n          outputPreferredLocations.push('gpu-buffer');\n          continue;\n        }\n        const location = typeof options?.preferredOutputLocation === 'string' ?\n            options.preferredOutputLocation :\n            options?.preferredOutputLocation?.[nameString] ?? 'cpu';\n        if (location !== 'cpu' && location !== 'cpu-pinned' && location !== 'gpu-buffer') {\n          throw new Error(`Not supported preferred output location: ${location}.`);\n        }\n        if (enableGraphCapture && location !== 'gpu-buffer') {\n          throw new Error(`Not supported preferred output location: ${\n              location}. Only 'gpu-buffer' location is supported when enableGraphCapture is true.`);\n        }\n        outputPreferredLocations.push(location);\n      }\n    }\n\n    // use IO binding only when at least one output is preffered to be on GPU.\n    let bindingState: IOBindingState|null = null;\n    if (!BUILD_DEFS.DISABLE_JSEP && outputPreferredLocations.some(l => l === 'gpu-buffer')) {\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.map(l => dataLocationStringToEnum(l)),\n      };\n    }\n\n    activeSessions.set(\n        sessionHandle,\n        [sessionHandle, inputNamesUTF8Encoded, outputNamesUTF8Encoded, bindingState, enableGraphCapture, false]);\n    return [sessionHandle, inputNames, outputNames];\n  } catch (e) {\n    inputNamesUTF8Encoded.forEach(buf => wasm._OrtFree(buf));\n    outputNamesUTF8Encoded.forEach(buf => wasm._OrtFree(buf));\n\n    if (ioBindingHandle !== 0) {\n      wasm._OrtReleaseBinding(ioBindingHandle);\n    }\n\n    if (sessionHandle !== 0) {\n      wasm._OrtReleaseSession(sessionHandle);\n    }\n    throw e;\n  } finally {\n    wasm._free(modelDataOffset);\n    if (sessionOptionsHandle !== 0) {\n      wasm._OrtReleaseSessionOptions(sessionOptionsHandle);\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      wasm._OrtClearBoundOutputs(ioBindingState.handle);\n    }\n    wasm._OrtReleaseBinding(ioBindingState.handle);\n  }\n\n  wasm.jsepOnReleaseSession?.(sessionId);\n\n  inputNamesUTF8Encoded.forEach(buf => wasm._OrtFree(buf));\n  outputNamesUTF8Encoded.forEach(buf => wasm._OrtFree(buf));\n  wasm._OrtReleaseSession(sessionHandle);\n  activeSessions.delete(sessionId);\n};\n\nexport const prepareInputOutputTensor =\n    (tensor: TensorMetadata|null, tensorHandles: number[], allocs: number[], sessionId: number, index: number,\n     enableGraphCapture = false): void => {\n      if (!tensor) {\n        tensorHandles.push(0);\n        return;\n      }\n\n      const wasm = getInstance();\n\n      const dataType = tensor[0];\n      const dims = tensor[1];\n      const location = tensor[3];\n\n      let rawData: number;\n      let dataByteLength: number;\n\n      if (dataType === 'string' && location === 'gpu-buffer') {\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      if (location === 'gpu-buffer') {\n        const gpuBuffer = tensor[2].gpuBuffer as GPUBuffer;\n        const elementSizeInBytes = getTensorElementSize(tensorDataTypeStringToEnum(dataType))!;\n        dataByteLength = dims.reduce((a, b) => a * b, 1) * elementSizeInBytes;\n\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      } else {\n        const data = tensor[2];\n\n        if (Array.isArray(data)) {\n          // string tensor\n          dataByteLength = 4 * data.length;\n          rawData = wasm._malloc(dataByteLength);\n          allocs.push(rawData);\n          let dataIndex = rawData / 4;\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.HEAPU32[dataIndex++] = allocWasmString(data[i], allocs);\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      const stack = wasm.stackSave();\n      const dimsOffset = wasm.stackAlloc(4 * dims.length);\n      try {\n        let dimIndex = dimsOffset / 4;\n        dims.forEach(d => wasm.HEAP32[dimIndex++] = d);\n        const tensor = wasm._OrtCreateTensor(\n            tensorDataTypeStringToEnum(dataType), rawData, dataByteLength, dimsOffset, dims.length,\n            dataLocationStringToEnum(location));\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, inputIndices: number[], inputTensors: TensorMetadata[], outputIndices: number[],\n    outputTensors: Array<TensorMetadata|null>, options: InferenceSession.RunOptions): Promise<TensorMetadata[]> => {\n  const wasm = getInstance();\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 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\n  const beforeRunStack = wasm.stackSave();\n  const inputValuesOffset = wasm.stackAlloc(inputCount * 4);\n  const inputNamesOffset = wasm.stackAlloc(inputCount * 4);\n  const outputValuesOffset = wasm.stackAlloc(outputCount * 4);\n  const outputNamesOffset = wasm.stackAlloc(outputCount * 4);\n\n  try {\n    [runOptionsHandle, runOptionsAllocs] = setRunOptions(options);\n\n    // create input tensors\n    for (let i = 0; i < inputCount; i++) {\n      prepareInputOutputTensor(\n          inputTensors[i], inputTensorHandles, inputOutputAllocs, sessionId, inputIndices[i], enableGraphCapture);\n    }\n\n    // create output tensors\n    for (let i = 0; i < outputCount; i++) {\n      prepareInputOutputTensor(\n          outputTensors[i], outputTensorHandles, inputOutputAllocs, sessionId, inputCount + outputIndices[i],\n          enableGraphCapture);\n    }\n\n    let inputValuesIndex = inputValuesOffset / 4;\n    let inputNamesIndex = inputNamesOffset / 4;\n    let outputValuesIndex = outputValuesOffset / 4;\n    let outputNamesIndex = outputNamesOffset / 4;\n    for (let i = 0; i < inputCount; i++) {\n      wasm.HEAPU32[inputValuesIndex++] = inputTensorHandles[i];\n      wasm.HEAPU32[inputNamesIndex++] = inputNamesUTF8Encoded[inputIndices[i]];\n    }\n    for (let i = 0; i < outputCount; i++) {\n      wasm.HEAPU32[outputValuesIndex++] = outputTensorHandles[i];\n      wasm.HEAPU32[outputNamesIndex++] = outputNamesUTF8Encoded[outputIndices[i]];\n    }\n\n    if (!BUILD_DEFS.DISABLE_JSEP && ioBindingState && !inputOutputBound) {\n      const {handle, outputPreferredLocations, outputPreferredLocationsEncoded} = ioBindingState;\n\n      if (inputNamesUTF8Encoded.length !== inputCount) {\n        throw new Error(`input count from feeds (${\n            inputCount}) is expected to be always equal to model's input count (${inputNamesUTF8Encoded.length}).`);\n      }\n\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. bind the tensor.\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 =\n              wasm._OrtBindOutput(handle, outputNamesUTF8Encoded[index], 0, outputPreferredLocationsEncoded[index]);\n          if (errorCode !== 0) {\n            checkLastError(`Can't bind output[${i}] to ${outputPreferredLocations[i]} for session=${sessionId}.`);\n          }\n        }\n      }\n      activeSessions.set(\n          sessionId,\n          [sessionHandle, inputNamesUTF8Encoded, outputNamesUTF8Encoded, ioBindingState, enableGraphCapture, true]);\n    }\n\n    wasm.jsepOnRunStart?.(sessionHandle);\n    let errorCode: number;\n    if (!BUILD_DEFS.DISABLE_JSEP && ioBindingState) {\n      errorCode = await wasm._OrtRunWithBinding(\n          sessionHandle, ioBindingState.handle, outputCount, outputValuesOffset, runOptionsHandle);\n    } else {\n      errorCode = await wasm._OrtRun(\n          sessionHandle, inputNamesOffset, inputValuesOffset, inputCount, outputNamesOffset, outputCount,\n          outputValuesOffset, runOptionsHandle);\n    }\n\n    if (errorCode !== 0) {\n      checkLastError('failed to call OrtRun().');\n    }\n\n    const output: TensorMetadata[] = [];\n\n    for (let i = 0; i < outputCount; i++) {\n      const tensor = wasm.HEAPU32[outputValuesOffset / 4 + i];\n      if (tensor === outputTensorHandles[i]) {\n        // output tensor is pre-allocated. no need to copy data.\n        output.push(outputTensors[i]!);\n        continue;\n      }\n\n      const beforeGetTensorDataStack = wasm.stackSave();\n      // stack allocate 4 pointer value\n      const tensorDataOffset = wasm.stackAlloc(4 * 4);\n\n      let keepOutputTensor = false;\n      let type: Tensor.Type|undefined, dataOffset = 0;\n      try {\n        const errorCode = wasm._OrtGetTensorData(\n            tensor, tensorDataOffset, tensorDataOffset + 4, tensorDataOffset + 8, tensorDataOffset + 12);\n        if (errorCode !== 0) {\n          checkLastError(`Can't access output tensor data on index ${i}.`);\n        }\n        let tensorDataIndex = tensorDataOffset / 4;\n        const dataType = wasm.HEAPU32[tensorDataIndex++];\n        dataOffset = wasm.HEAPU32[tensorDataIndex++];\n        const dimsOffset = wasm.HEAPU32[tensorDataIndex++];\n        const dimsLength = wasm.HEAPU32[tensorDataIndex++];\n        const dims = [];\n        for (let i = 0; i < dimsLength; i++) {\n          dims.push(wasm.HEAPU32[dimsOffset / 4 + i]);\n        }\n        wasm._OrtFree(dimsOffset);\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') {\n            throw new Error('String tensor is not supported on GPU.');\n          }\n          const stringData: string[] = [];\n          let dataIndex = dataOffset / 4;\n          for (let i = 0; i < size; i++) {\n            const offset = wasm.HEAPU32[dataIndex++];\n            const maxBytesToRead = i === size - 1 ? undefined : wasm.HEAPU32[dataIndex] - 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 = 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 elementSize = getTensorElementSize(dataType);\n            if (elementSize === 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            output.push([\n              type, dims, {\n                gpuBuffer,\n                download: wasm.jsepCreateDownloader!(gpuBuffer, size * elementSize, type),\n                dispose: () => {\n                  wasm._OrtReleaseTensor(tensor);\n                }\n              },\n              'gpu-buffer'\n            ]);\n          } else {\n            const typedArrayConstructor = tensorTypeToTypedArrayConstructor(type);\n            const data = new typedArrayConstructor(size);\n            new Uint8Array(data.buffer, data.byteOffset, data.byteLength)\n                .set(wasm.HEAPU8.subarray(dataOffset, dataOffset + data.byteLength));\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      wasm._OrtClearBoundOutputs(ioBindingState.handle);\n      activeSessions.set(\n          sessionId,\n          [sessionHandle, inputNamesUTF8Encoded, outputNamesUTF8Encoded, ioBindingState, enableGraphCapture, false]);\n    }\n    return output;\n  } finally {\n    wasm.stackRestore(beforeRunStack);\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};\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 {OrtWasmMessage, SerializableInternalBuffer, SerializableSessionMetadata, SerializableTensorMetadata, TensorMetadata} from './proxy-messages';\nimport * as core from './wasm-core-impl';\nimport {initializeWebAssembly} from './wasm-factory';\nimport {importProxyWorker} from './wasm-utils-import';\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\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          proxyWorker.postMessage(message);\n          temporaryObjectUrl = objectUrl;\n        } catch (e) {\n          reject(e);\n        }\n      }, reject);\n    });\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 =\n    async(model: SerializableInternalBuffer|Uint8Array, 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 run = async(\n    sessionId: number, inputIndices: number[], inputs: TensorMetadata[], outputIndices: number[],\n    outputs: Array<TensorMetadata|null>, options: InferenceSession.RunOptions): Promise<TensorMetadata[]> => {\n  if (!BUILD_DEFS.DISABLE_WASM_PROXY && isProxy()) {\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', in : {sessionId, inputIndices, inputs: serializableInputs, outputIndices, options}};\n      proxyWorker!.postMessage(message, core.extractTransferableBuffers(serializableInputs));\n    });\n  } else {\n    return core.run(sessionId, inputIndices, inputs, outputIndices, outputs, options);\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 {InferenceSession, InferenceSessionHandler, SessionHandler, Tensor, TRACE_FUNC_BEGIN, TRACE_FUNC_END} from 'onnxruntime-common';\n\nimport {SerializableInternalBuffer, TensorMetadata} from './proxy-messages';\nimport {copyFromExternalBuffer, createSession, endProfiling, releaseSession, run} from './proxy-wrapper';\nimport {isGpuBufferSupportedType} 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    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    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: string[];\n  outputNames: string[];\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] = await createSession(model, options);\n    TRACE_FUNC_END();\n  }\n\n  async dispose(): Promise<void> {\n    return releaseSession(this.sessionId);\n  }\n\n  async run(feeds: SessionHandler.FeedsType, fetches: SessionHandler.FetchesType, options: InferenceSession.RunOptions):\n      Promise<SessionHandler.ReturnType> {\n    TRACE_FUNC_BEGIN();\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 =\n        inputArray.map((t, i) => encodeTensorMetadata(t, () => `input \"${this.inputNames[inputIndices[i]]}\"`));\n    const outputs = outputArray.map(\n        (t, i) => t ? encodeTensorMetadata(t, () => `output \"${this.outputNames[outputIndices[i]]}\"`) : null);\n\n    const results = await run(this.sessionId, inputIndices, inputs, outputIndices, outputs, options);\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 {Backend, env, InferenceSession, InferenceSessionHandler} from 'onnxruntime-common';\n\nimport {initializeOrtEp, initializeWebAssemblyAndOrtRuntime} from './wasm/proxy-wrapper';\nimport {OnnxruntimeWebAssemblySessionHandler} from './wasm/session-handler-inference';\nimport {scriptSrc} from './wasm/wasm-utils-import';\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  if (env.wasm.simd === false) {\n    // eslint-disable-next-line no-console\n    console.warn(\n        'Deprecated property \"env.wasm.simd\" is set to false. ' +\n        'non-SIMD build is no longer provided, and this setting will be ignored.');\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  if (!BUILD_DEFS.DISABLE_DYNAMIC_IMPORT) {\n    // overwrite wasm paths override if not set\n    if (env.wasm.wasmPaths === undefined && scriptSrc && scriptSrc.indexOf('blob:') !== 0) {\n      env.wasm.wasmPaths = scriptSrc.substring(0, scriptSrc.lastIndexOf('/') + 1);\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(path: string, options?: InferenceSession.SessionOptions):\n      Promise<InferenceSessionHandler>;\n  createInferenceSessionHandler(buffer: Uint8Array, options?: InferenceSession.SessionOptions):\n      Promise<InferenceSessionHandler>;\n  async createInferenceSessionHandler(pathOrBuffer: string|Uint8Array, options?: InferenceSession.SessionOptions):\n      Promise<InferenceSessionHandler> {\n    const handler = new OnnxruntimeWebAssemblySessionHandler();\n    await handler.loadModel(pathOrBuffer, options);\n    return Promise.resolve(handler);\n  }\n}\n","// Copyright (c) Microsoft Corporation. All rights reserved.\n// Licensed under the MIT License.\n\nimport {OnnxruntimeWebAssemblyBackend} from './backend-wasm';\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_WASM) {\n  const wasmBackend = BUILD_DEFS.DISABLE_TRAINING ? require('./backend-wasm-inference').wasmBackend :\n                                                    require('./backend-wasm-training').wasmBackend;\n  if (!BUILD_DEFS.DISABLE_JSEP) {\n    registerBackend('webgpu', wasmBackend, 5);\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.19.2';\n"]}