{"version":3,"sources":["../../common/lib/backend-impl.ts","../../common/lib/backend.ts","../../common/lib/version.ts","../../common/lib/env-impl.ts","../../common/lib/env.ts","../../common/lib/tensor-conversion-impl.ts","../../common/lib/tensor-factory-impl.ts","../../common/lib/tensor-impl-type-mapping.ts","../../common/lib/tensor-utils-impl.ts","../../common/lib/tensor-impl.ts","../../common/lib/tensor.ts","../../common/lib/trace.ts","../../common/lib/inference-session-impl.ts","../../common/lib/inference-session.ts","../../common/lib/tensor-conversion.ts","../../common/lib/tensor-factory.ts","../../common/lib/onnx-model.ts","../../common/lib/onnx-value.ts","../../common/lib/training-session-impl.ts","../../common/lib/training-session.ts","../../common/lib/index.ts","../lib/wasm/wasm-utils-env.ts","../lib/wasm/proxy-worker/main.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/wasm/wasm-training-core-impl.ts","../lib/wasm/session-handler-training.ts","../lib/backend-wasm-training.ts","../lib/index.ts","../lib/version.ts"],"names":["backends","backendsSortedByPriority","registerBackend","tryResolveAndInitializeBackend","resolveBackendAndExecutionProviders","init_backend_impl","__esmMin","name","backend","priority","currentBackend","i","backendName","backendInfo","isInitializing","e","options","eps","backendHints","backendNames","errors","availableBackendNames","resolveResult","err","filteredEps","target","prop","init_backend","version","init_version","logLevelValue","env","init_env_impl","value","init_env","tensorToDataURL","tensorToImageData","init_tensor_conversion_impl","tensor","canvas","pixels2DContext","width","height","inputformat","norm","normMean","normBias","stride","rTensorPointer","gTensorPointer","bTensorPointer","aTensorPointer","j","R","G","B","A","image","channels","step","rImagePointer","gImagePointer","bImagePointer","aImagePointer","bufferToTensor","tensorFromImage","tensorFromTexture","tensorFromGpuBuffer","tensorFromPinnedBuffer","init_tensor_factory_impl","init_tensor_impl","buffer","outputformat","float32Data","Tensor","isHTMLImageEle","isImageDataEle","isImageBitmap","isString","data","bufferToTensorOptions","createCanvas","createCanvasContext","tempCanvas","resolve","reject","context","newImage","img","texture","download","dispose","dims","gpuBuffer","dataType","type","NUMERIC_TENSOR_TYPE_TO_TYPEDARRAY_MAP","NUMERIC_TENSOR_TYPEDARRAY_TO_TYPE_MAP","isTypedArrayChecked","checkTypedArray","init_tensor_impl_type_mapping","isBigInt64ArrayAvailable","isBigUint64ArrayAvailable","isFloat16ArrayAvailable","calculateSize","tensorReshape","init_tensor_utils_impl","size","dim","arg0","arg1","arg2","expectedTypedArrayConstructor","maybeDims","typedArrayConstructor","firstElementType","mappedType","releaseData","init_tensor","TRACE","TRACE_FUNC","TRACE_FUNC_BEGIN","TRACE_FUNC_END","init_trace","deviceType","label","msg","extraMsg","stack","hasTraceFunc","InferenceSession","init_inference_session_impl","_InferenceSession","handler","feeds","fetches","isFetchesEmpty","isFetches","arg1Keys","v","results","returnValue","key","result","arg3","filePathOrUint8Array","byteOffset","byteLength","optionsWithValidatedEPs","init_inference_session","init_tensor_conversion","init_tensor_factory","init_onnx_model","init_onnx_value","noBackendErrMsg","TrainingSession","init_training_session_impl","_TrainingSession","hasOptimizerModel","hasEvalModel","trainingOptions","sessionOptions","evalModel","optimizerModel","inputNames","outputNames","trainableOnly","array","paramsSize","init_training_session","esm_exports","__export","init_esm","init_wasm_utils_env","main_exports","main_default","WORKER_NAME","isProxyWorker","init_main","init_wasm_core_impl","init_wasm_factory","init_wasm_utils_import","ev","message","initializeWebAssembly","initRuntime","epName","initEp","bufferData","copyFromExternalBuffer","model","createSession","sessionMetadata","releaseSession","sessionId","inputIndices","inputs","outputIndices","run","outputs","o","extractTransferableBuffers","endProfiling","urlOverride","scriptSrc","origin","isSameOrigin","normalizeUrl","fallbackUrl","preload","dynamicImportDefault","createProxyWorker","importProxyWorker","importWasmModule","filename","prefixOverride","baseUrl","absoluteUrl","blob","url","isMultiThreaded","wasmModuleFilename","wasmModuleUrl","needPreload","wasm","initialized","initializing","aborted","isMultiThreadSupported","isSimdSupported","getInstance","flags","timeout","numThreads","multiThreadSupported","wasmPaths","wasmPrefixOverride","mjsPathOverrideFlag","mjsPathOverride","wasmPathOverrideFlag","wasmPathOverride","wasmBinaryOverride","objectUrl","ortWasmFactory","isTimeout","tasks","config","fileName","scriptDirectory","module","what","allocWasmString","iterateExtraOptions","checkLastError","init_wasm_utils","allocs","dataLength","dataOffset","prefix","seen","paramsOffset","errorCode","errorMessagePointer","errorMessage","setRunOptions","init_run_options","runOptionsHandle","runOptions","tagDataOffset","keyDataOffset","valueDataOffset","alloc","getGraphOptimzationLevel","getExecutionMode","appendDefaultOptions","setExecutionProviders","setSessionOptions","init_session_options","graphOptimizationLevel","executionMode","session","ep","sessionOptionsHandle","executionProviders","webgpuOptions","epNameDataOffset","logIdDataOffset","logSeverityLevel","logVerbosityLevel","optimizedModelFilePathOffset","nameOffset","tensorDataTypeStringToEnum","tensorDataTypeEnumToString","getTensorElementSize","tensorTypeToTypedArrayConstructor","logLevelStringToEnum","isGpuBufferSupportedType","dataLocationStringToEnum","init_wasm_common","typeProto","dateType","logLevel","location","loadFile","init_wasm_utils_load_file","file","readFile","createReadStream","stream","chunks","chunk","response","contentLengthHeader","fileSize","reader","pages","offset","done","chunkSize","initOrt","activeSessions","getSessionInputOutputCount","prepareInputOutputTensor","loggingLevel","sessionHandle","modelDataOffset","modelData","modelDataLength","ioBindingHandle","inputNamesUTF8Encoded","outputNamesUTF8Encoded","loadingPromises","path","provider","webnnOptions","gpuDevice","powerPreference","inputCount","outputCount","enableGraphCapture","outputPreferredLocations","nameString","bindingState","buf","ioBindingState","tensorHandles","index","rawData","dataByteLength","elementSizeInBytes","a","b","registerBuffer","dataIndex","dimsOffset","dimIndex","d","inputTensors","outputTensors","inputOutputBound","runOptionsAllocs","inputTensorHandles","outputTensorHandles","inputOutputAllocs","beforeRunStack","inputValuesOffset","inputNamesOffset","outputValuesOffset","outputNamesOffset","inputValuesIndex","inputNamesIndex","outputValuesIndex","outputNamesIndex","output","beforeGetTensorDataStack","tensorDataOffset","keepOutputTensor","tensorDataIndex","dimsLength","preferredLocation","stringData","maxBytesToRead","getBuffer","elementSize","p","profileFileName","tensors","buffers","isProxy","proxyWorker","temporaryObjectUrl","initWasmCallbacks","queuedCallbacks","enqueueCallbacks","ensureWorker","onProxyWorkerMessage","initializeWebAssemblyAndOrtRuntime","initializeOrtEp","init_proxy_wrapper","callbacks","queue","worker","transferable","t","serializableInputs","encodeTensorMetadata","decodeTensorMetadata","OnnxruntimeWebAssemblySessionHandler","init_session_handler_inference","getName","pathOrBuffer","inputArray","kvp","outputArray","resultMap","initializeFlags","OnnxruntimeWebAssemblyBackend","init_backend_wasm","numCpuLogicalCores","NO_TRAIN_FUNCS_MSG","ifErrCodeCheckLastError","createCheckpointHandle","getModelInputOutputCount","getModelInputOutputNamesLoop","getModelInputOutputNames","createTrainingSessionHandle","createAndAllocateTensors","moveOutputToTensorMetadataArr","lazyResetGrad","runTrainStep","runOptimizerStep","runEvalStep","getParametersSize","getContiguousParameters","loadParametersBuffer","releaseTrainingSessionAndCheckpoint","init_wasm_training_core_impl","errCode","checkNeqZero","checkpointData","checkpointDataOffset","checkpointDataLength","checkpointHandle","trainingSessionId","isEvalModel","count","isInput","names","trainModelData","evalModelData","optimizerModelData","trainingSessionHandle","indices","indexAdd","valuesOffset","valuesIndex","sizeOffset","tensorTypeAsString","locationAsString","parametersSize","paramsByteLength","dimsIndex","bufferByteLength","bufferCount","bufferOffset","checkpointId","OnnxruntimeWebAssemblyTrainingSessionHandler","init_session_handler_training","uriOrBuffer","arrayBuffer","checkpointStateUriOrBuffer","trainModelUriOrBuffer","evalModelUriOrBuffer","optimizerModelUriOrBuffer","mapFunc","values","uList","tensorResult","backend_wasm_training_exports","wasmBackend","OnnxruntimeTrainingWebAssemblyBackend","init_backend_wasm_training","lib_default"],"mappings":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EAAE,EACtC7d,GAAgB,OAAQ6d,EAAa,EAAE,CACzC,CAEA,OAAO,eAAehc,EAAI,SAAU,MAAO,CAAC,MAAOH,GAAS,WAAY,EAAI,CAAC","sourcesContent":["// Copyright (c) Microsoft Corporation. All rights reserved.\n// Licensed under the MIT License.\n\nimport {Backend} from './backend.js';\nimport {InferenceSession} from './inference-session.js';\n\ninterface BackendInfo {\n  backend: Backend;\n  priority: number;\n\n  initPromise?: Promise<void>;\n  initialized?: boolean;\n  aborted?: boolean;\n  error?: string;\n}\n\nconst backends: Map<string, BackendInfo> = new Map();\nconst backendsSortedByPriority: string[] = [];\n\n/**\n * Register a backend.\n *\n * @param name - the name as a key to lookup as an execution provider.\n * @param backend - the backend object.\n * @param priority - an integer indicating the priority of the backend. Higher number means higher priority. if priority\n * < 0, it will be considered as a 'beta' version and will not be used as a fallback backend by default.\n *\n * @ignore\n */\nexport const registerBackend = (name: string, backend: Backend, priority: number): void => {\n  if (backend && typeof backend.init === 'function' && typeof backend.createInferenceSessionHandler === 'function') {\n    const currentBackend = backends.get(name);\n    if (currentBackend === undefined) {\n      backends.set(name, {backend, priority});\n    } else if (currentBackend.priority > priority) {\n      // same name is already registered with a higher priority. skip registeration.\n      return;\n    } else if (currentBackend.priority === priority) {\n      if (currentBackend.backend !== backend) {\n        throw new Error(`cannot register backend \"${name}\" using priority ${priority}`);\n      }\n    }\n\n    if (priority >= 0) {\n      const i = backendsSortedByPriority.indexOf(name);\n      if (i !== -1) {\n        backendsSortedByPriority.splice(i, 1);\n      }\n\n      for (let i = 0; i < backendsSortedByPriority.length; i++) {\n        if (backends.get(backendsSortedByPriority[i])!.priority <= priority) {\n          backendsSortedByPriority.splice(i, 0, name);\n          return;\n        }\n      }\n      backendsSortedByPriority.push(name);\n    }\n    return;\n  }\n\n  throw new TypeError('not a valid backend');\n};\n\n/**\n * Try to resolve and initialize a backend.\n *\n * @param backendName - the name of the backend.\n * @returns the backend instance if resolved and initialized successfully, or an error message if failed.\n */\nconst tryResolveAndInitializeBackend = async(backendName: string): Promise<Backend|string> => {\n  const backendInfo = backends.get(backendName);\n  if (!backendInfo) {\n    return 'backend not found.';\n  }\n\n  if (backendInfo.initialized) {\n    return backendInfo.backend;\n  } else if (backendInfo.aborted) {\n    return backendInfo.error!;\n  } else {\n    const isInitializing = !!backendInfo.initPromise;\n    try {\n      if (!isInitializing) {\n        backendInfo.initPromise = backendInfo.backend.init(backendName);\n      }\n      await backendInfo.initPromise;\n      backendInfo.initialized = true;\n      return backendInfo.backend;\n    } catch (e) {\n      if (!isInitializing) {\n        backendInfo.error = `${e}`;\n        backendInfo.aborted = true;\n      }\n      return backendInfo.error!;\n    } finally {\n      delete backendInfo.initPromise;\n    }\n  }\n};\n\n/**\n * Resolve execution providers from the specific session options.\n *\n * @param options - the session options object.\n * @returns a promise that resolves to a tuple of an initialized backend instance and a session options object with\n * filtered EP list.\n *\n * @ignore\n */\nexport const resolveBackendAndExecutionProviders = async(options: InferenceSession.SessionOptions):\n    Promise<[backend: Backend, options: InferenceSession.SessionOptions]> => {\n      // extract backend hints from session options\n      const eps = options.executionProviders || [];\n      const backendHints = eps.map(i => typeof i === 'string' ? i : i.name);\n      const backendNames = backendHints.length === 0 ? backendsSortedByPriority : backendHints;\n\n      // try to resolve and initialize all requested backends\n      let backend: Backend|undefined;\n      const errors = [];\n      const availableBackendNames = new Set<string>();\n      for (const backendName of backendNames) {\n        const resolveResult = await tryResolveAndInitializeBackend(backendName);\n        if (typeof resolveResult === 'string') {\n          errors.push({name: backendName, err: resolveResult});\n        } else {\n          if (!backend) {\n            backend = resolveResult;\n          }\n          if (backend === resolveResult) {\n            availableBackendNames.add(backendName);\n          }\n        }\n      }\n\n      // if no backend is available, throw error.\n      if (!backend) {\n        throw new Error(`no available backend found. ERR: ${errors.map(e => `[${e.name}] ${e.err}`).join(', ')}`);\n      }\n\n      // for each explicitly requested backend, if it's not available, output warning message.\n      for (const {name, err} of errors) {\n        if (backendHints.includes(name)) {\n          // eslint-disable-next-line no-console\n          console.warn(`removing requested execution provider \"${\n              name}\" from session options because it is not available: ${err}`);\n        }\n      }\n\n      const filteredEps = eps.filter(i => availableBackendNames.has(typeof i === 'string' ? i : i.name));\n\n      return [\n        backend, new Proxy(options, {\n          get: (target, prop) => {\n            if (prop === 'executionProviders') {\n              return filteredEps;\n            }\n            return Reflect.get(target, prop);\n          }\n        })\n      ];\n    };\n","// Copyright (c) Microsoft Corporation. All rights reserved.\n// Licensed under the MIT License.\n\nimport {InferenceSession} from './inference-session.js';\nimport {OnnxValue} from './onnx-value.js';\nimport {TrainingSession} from './training-session.js';\n\n/**\n * @ignore\n */\nexport declare namespace SessionHandler {\n  type FeedsType = {[name: string]: OnnxValue};\n  type FetchesType = {[name: string]: OnnxValue | null};\n  type ReturnType = {[name: string]: OnnxValue};\n}\n\n/**\n * Represents shared SessionHandler functionality\n *\n * @ignore\n */\ninterface SessionHandler {\n  dispose(): Promise<void>;\n\n  readonly inputNames: readonly string[];\n  readonly outputNames: readonly string[];\n}\n\n/**\n * Represent a handler instance of an inference session.\n *\n * @ignore\n */\nexport interface InferenceSessionHandler extends SessionHandler {\n  startProfiling(): void;\n  endProfiling(): void;\n\n  run(feeds: SessionHandler.FeedsType, fetches: SessionHandler.FetchesType,\n      options: InferenceSession.RunOptions): Promise<SessionHandler.ReturnType>;\n}\n\n/**\n * Represent a handler instance of a training inference session.\n *\n * @ignore\n */\nexport interface TrainingSessionHandler extends SessionHandler {\n  readonly evalInputNames: readonly string[];\n  readonly evalOutputNames: readonly string[];\n\n  lazyResetGrad(): Promise<void>;\n  runTrainStep(\n      feeds: SessionHandler.FeedsType, fetches: SessionHandler.FetchesType,\n      options: InferenceSession.RunOptions): Promise<SessionHandler.ReturnType>;\n  runOptimizerStep(options: InferenceSession.RunOptions): Promise<void>;\n  runEvalStep(\n      feeds: SessionHandler.FeedsType, fetches: SessionHandler.FetchesType,\n      options: InferenceSession.RunOptions): Promise<SessionHandler.ReturnType>;\n\n  getParametersSize(trainableOnly: boolean): Promise<number>;\n  loadParametersBuffer(buffer: Uint8Array, trainableOnly: boolean): Promise<void>;\n  getContiguousParameters(trainableOnly: boolean): Promise<OnnxValue>;\n}\n\n/**\n * Represent a backend that provides implementation of model inferencing.\n *\n * @ignore\n */\nexport interface Backend {\n  /**\n   * Initialize the backend asynchronously. Should throw when failed.\n   */\n  init(backendName: string): Promise<void>;\n\n  createInferenceSessionHandler(uriOrBuffer: string|Uint8Array, options?: InferenceSession.SessionOptions):\n      Promise<InferenceSessionHandler>;\n\n  createTrainingSessionHandler?\n      (checkpointStateUriOrBuffer: TrainingSession.UriOrBuffer, trainModelUriOrBuffer: TrainingSession.UriOrBuffer,\n       evalModelUriOrBuffer: TrainingSession.UriOrBuffer, optimizerModelUriOrBuffer: TrainingSession.UriOrBuffer,\n       options: InferenceSession.SessionOptions): Promise<TrainingSessionHandler>;\n}\n\nexport {registerBackend} from './backend-impl.js';\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","// Copyright (c) Microsoft Corporation. All rights reserved.\n// Licensed under the MIT License.\n\nimport {Env} from './env.js';\nimport {version} from './version.js';\n\ntype LogLevelType = Env['logLevel'];\n\nlet logLevelValue: Required<LogLevelType> = 'warning';\n\nexport const env: Env = {\n  wasm: {} as Env.WebAssemblyFlags,\n  webgl: {} as Env.WebGLFlags,\n  webgpu: {} as Env.WebGpuFlags,\n  versions: {common: version},\n\n  set logLevel(value: LogLevelType) {\n    if (value === undefined) {\n      return;\n    }\n    if (typeof value !== 'string' || ['verbose', 'info', 'warning', 'error', 'fatal'].indexOf(value) === -1) {\n      throw new Error(`Unsupported logging level: ${value}`);\n    }\n    logLevelValue = value;\n  },\n  get logLevel(): Required<LogLevelType> {\n    return logLevelValue;\n  },\n};\n\n// set property 'logLevel' so that they can be correctly transferred to worker by `postMessage()`.\nObject.defineProperty(env, 'logLevel', {enumerable: true});\n","// Copyright (c) Microsoft Corporation. All rights reserved.\n// Licensed under the MIT License.\n\nimport {env as envImpl} from './env-impl.js';\n\nexport declare namespace Env {\n  export type WasmPathPrefix = string;\n  export interface WasmFilePaths {\n    /**\n     * Specify the override path for the main .wasm file.\n     *\n     * This path should be an absolute path.\n     *\n     * If not modified, the filename of the .wasm file is:\n     * - `ort-wasm-simd-threaded.wasm` for default build\n     * - `ort-wasm-simd-threaded.jsep.wasm` for JSEP build (with WebGPU and WebNN)\n     * - `ort-training-wasm-simd-threaded.wasm` for training build\n     */\n    wasm?: URL|string;\n    /**\n     * Specify the override path for the main .mjs file.\n     *\n     * This path should be an absolute path.\n     *\n     * If not modified, the filename of the .mjs file is:\n     * - `ort-wasm-simd-threaded.mjs` for default build\n     * - `ort-wasm-simd-threaded.jsep.mjs` for JSEP build (with WebGPU and WebNN)\n     * - `ort-training-wasm-simd-threaded.mjs` for training build\n     */\n    mjs?: URL|string;\n  }\n  export type WasmPrefixOrFilePaths = WasmPathPrefix|WasmFilePaths;\n  export interface WebAssemblyFlags {\n    /**\n     * set or get number of thread(s). If omitted or set to 0, number of thread(s) will be determined by system. If set\n     * to 1, no worker thread will be spawned.\n     *\n     * This setting is available only when WebAssembly multithread feature is available in current context.\n     *\n     * @defaultValue `0`\n     */\n    numThreads?: number;\n\n    /**\n     * set or get a boolean value indicating whether to enable SIMD. If set to false, SIMD will be forcely disabled.\n     *\n     * This setting is available only when WebAssembly SIMD feature is available in current context.\n     *\n     * @deprecated This property is deprecated. Since SIMD is supported by all major JavaScript engines, non-SIMD\n     * build is no longer provided. This property will be removed in future release.\n     * @defaultValue `true`\n     */\n    simd?: boolean;\n\n    /**\n     * set or get a boolean value indicating whether to enable trace.\n     *\n     * @deprecated Use `env.trace` instead. If `env.trace` is set, this property will be ignored.\n     * @defaultValue `false`\n     */\n    trace?: boolean;\n\n    /**\n     * Set or get a number specifying the timeout for initialization of WebAssembly backend, in milliseconds. A zero\n     * value indicates no timeout is set.\n     *\n     * @defaultValue `0`\n     */\n    initTimeout?: number;\n\n    /**\n     * Set a custom URL prefix to the .wasm/.mjs files, or an object of overrides for both .wasm/.mjs file. The override\n     * path should be an absolute path.\n     */\n    wasmPaths?: WasmPrefixOrFilePaths;\n\n    /**\n     * Set a custom buffer which contains the WebAssembly binary. If this property is set, the `wasmPaths` property will\n     * be ignored.\n     */\n    wasmBinary?: ArrayBufferLike|Uint8Array;\n\n    /**\n     * Set or get a boolean value indicating whether to proxy the execution of main thread to a worker thread.\n     *\n     * @defaultValue `false`\n     */\n    proxy?: boolean;\n  }\n\n  export interface WebGLFlags {\n    /**\n     * Set or get the WebGL Context ID (webgl or webgl2).\n     *\n     * @defaultValue `'webgl2'`\n     */\n    contextId?: 'webgl'|'webgl2';\n    /**\n     * Get the WebGL rendering context.\n     */\n    readonly context: WebGLRenderingContext;\n    /**\n     * Set or get the maximum batch size for matmul. 0 means to disable batching.\n     *\n     * @deprecated\n     */\n    matmulMaxBatchSize?: number;\n    /**\n     * Set or get the texture cache mode.\n     *\n     * @defaultValue `'full'`\n     */\n    textureCacheMode?: 'initializerOnly'|'full';\n    /**\n     * Set or get the packed texture mode\n     *\n     * @defaultValue `false`\n     */\n    pack?: boolean;\n    /**\n     * Set or get whether enable async download.\n     *\n     * @defaultValue `false`\n     */\n    async?: boolean;\n  }\n\n  export interface WebGpuProfilingDataV1TensorMetadata {\n    dims: readonly number[];\n    dataType: string;\n  }\n  export interface WebGpuProfilingDataV1 {\n    version: 1;\n    inputsMetadata: readonly WebGpuProfilingDataV1TensorMetadata[];\n    outputsMetadata: readonly WebGpuProfilingDataV1TensorMetadata[];\n    kernelId: number;\n    kernelType: string;\n    kernelName: string;\n    programName: string;\n    startTime: number;\n    endTime: number;\n  }\n\n  export type WebGpuProfilingData = WebGpuProfilingDataV1;\n\n  export interface WebGpuFlags {\n    /**\n     * Set or get the profiling mode.\n     *\n     * @deprecated Use `env.webgpu.profiling.mode` instead. If `env.webgpu.profiling.mode` is set, this property will be\n     * ignored.\n     */\n    profilingMode?: 'off'|'default';\n    /**\n     * Set or get the profiling configuration.\n     */\n    profiling?: {\n      /**\n       * Set or get the profiling mode.\n       *\n       * @defaultValue `'off'`\n       */\n      mode?: 'off'|'default';\n\n      /**\n       * Set or get a callback function when a profiling data is received. If not set, the profiling data will be\n       * printed to console.\n       */\n      ondata?: (data: WebGpuProfilingData) => void;\n    };\n    /**\n     * Set or get the power preference.\n     *\n     * Setting this property only has effect before the first WebGPU inference session is created. The value will be\n     * used as options for `navigator.gpu.requestAdapter()`.\n     *\n     * See {@link https://gpuweb.github.io/gpuweb/#dictdef-gpurequestadapteroptions} for more details.\n     *\n     * @defaultValue `undefined`\n     */\n    powerPreference?: 'low-power'|'high-performance';\n    /**\n     * Set or get the force fallback adapter flag.\n     *\n     * Setting this property only has effect before the first WebGPU inference session is created. The value will be\n     * used as options for `navigator.gpu.requestAdapter()`.\n     *\n     * See {@link https://gpuweb.github.io/gpuweb/#dictdef-gpurequestadapteroptions} for more details.\n     *\n     * @defaultValue `undefined`\n     */\n    forceFallbackAdapter?: boolean;\n    /**\n     * Set or get the adapter for WebGPU.\n     *\n     * Setting this property only has effect before the first WebGPU inference session is created. The value will be\n     * used as the GPU adapter for the underlying WebGPU backend to create GPU device.\n     *\n     * If this property is not set, it will be available to get after the first WebGPU inference session is created. The\n     * value will be the GPU adapter that created by the underlying WebGPU backend.\n     *\n     * When use with TypeScript, the type of this property is `GPUAdapter` defined in \"@webgpu/types\".\n     * Use `const adapter = env.webgpu.adapter as GPUAdapter;` in TypeScript to access this property with correct type.\n     *\n     * see comments on {@link Tensor.GpuBufferType}\n     */\n    adapter: unknown;\n    /**\n     * Get the device for WebGPU.\n     *\n     * This property is only available after the first WebGPU inference session is created.\n     *\n     * When use with TypeScript, the type of this property is `GPUDevice` defined in \"@webgpu/types\".\n     * Use `const device = env.webgpu.device as GPUDevice;` in TypeScript to access this property with correct type.\n     *\n     * see comments on {@link Tensor.GpuBufferType} for more details about why not use types defined in \"@webgpu/types\".\n     */\n    readonly device: unknown;\n    /**\n     * Set or get whether validate input content.\n     *\n     * @defaultValue `false`\n     */\n    validateInputContent?: boolean;\n  }\n}\n\nexport interface Env {\n  /**\n   * set the severity level for logging.\n   *\n   * @defaultValue `'warning'`\n   */\n  logLevel?: 'verbose'|'info'|'warning'|'error'|'fatal';\n\n  /**\n   * Indicate whether run in debug mode.\n   *\n   * @defaultValue `false`\n   */\n  debug?: boolean;\n\n  /**\n   * set or get a boolean value indicating whether to enable trace.\n   *\n   * @defaultValue `false`\n   */\n  trace?: boolean;\n\n  /**\n   * Get version of the current package.\n   */\n  readonly versions: {\n    readonly common: string;\n    readonly web?: string;\n    readonly node?: string;\n    // eslint-disable-next-line @typescript-eslint/naming-convention\n    readonly 'react-native'?: string;\n  };\n\n  /**\n   * Represent a set of flags for WebAssembly\n   */\n  readonly wasm: Env.WebAssemblyFlags;\n\n  /**\n   * Represent a set of flags for WebGL\n   */\n  readonly webgl: Env.WebGLFlags;\n\n  /**\n   * Represent a set of flags for WebGPU\n   */\n  readonly webgpu: Env.WebGpuFlags;\n\n  [name: string]: unknown;\n}\n\n/**\n * Represent a set of flags as a global singleton.\n */\nexport const env: Env = envImpl;\n","// Copyright (c) Microsoft Corporation. All rights reserved.\n// Licensed under the MIT License.\n\nimport {TensorToDataUrlOptions, TensorToImageDataOptions} from './tensor-conversion.js';\nimport {Tensor} from './tensor.js';\n\n/**\n * implementation of Tensor.toDataURL()\n */\nexport const tensorToDataURL = (tensor: Tensor, options?: TensorToDataUrlOptions): string => {\n  const canvas = typeof document !== 'undefined' ? document.createElement('canvas') : (new OffscreenCanvas(1, 1));\n  canvas.width = tensor.dims[3];\n  canvas.height = tensor.dims[2];\n  const pixels2DContext =\n      canvas.getContext('2d') as (CanvasRenderingContext2D | OffscreenCanvasRenderingContext2D | null);\n\n  if (pixels2DContext != null) {\n    // Default values for height and width & format\n    let width: number;\n    let height: number;\n    if (options?.tensorLayout !== undefined && options.tensorLayout === 'NHWC') {\n      width = tensor.dims[2];\n      height = tensor.dims[3];\n    } else {  // Default layout is NCWH\n      width = tensor.dims[3];\n      height = tensor.dims[2];\n    }\n\n    const inputformat = options?.format !== undefined ? options.format : 'RGB';\n\n    const norm = options?.norm;\n    let normMean: [number, number, number, number];\n    let normBias: [number, number, number, number];\n    if (norm === undefined || norm.mean === undefined) {\n      normMean = [255, 255, 255, 255];\n    } else {\n      if (typeof (norm.mean) === 'number') {\n        normMean = [norm.mean, norm.mean, norm.mean, norm.mean];\n      } else {\n        normMean = [norm.mean[0], norm.mean[1], norm.mean[2], 0];\n        if (norm.mean[3] !== undefined) {\n          normMean[3] = norm.mean[3];\n        }\n      }\n    }\n    if (norm === undefined || norm.bias === undefined) {\n      normBias = [0, 0, 0, 0];\n    } else {\n      if (typeof (norm.bias) === 'number') {\n        normBias = [norm.bias, norm.bias, norm.bias, norm.bias];\n      } else {\n        normBias = [norm.bias[0], norm.bias[1], norm.bias[2], 0];\n        if (norm.bias[3] !== undefined) {\n          normBias[3] = norm.bias[3];\n        }\n      }\n    }\n\n    const stride = height * width;\n    // Default pointer assignments\n    let rTensorPointer = 0, gTensorPointer = stride, bTensorPointer = stride * 2, aTensorPointer = -1;\n\n    // Updating the pointer assignments based on the input image format\n    if (inputformat === 'RGBA') {\n      rTensorPointer = 0;\n      gTensorPointer = stride;\n      bTensorPointer = stride * 2;\n      aTensorPointer = stride * 3;\n    } else if (inputformat === 'RGB') {\n      rTensorPointer = 0;\n      gTensorPointer = stride;\n      bTensorPointer = stride * 2;\n    } else if (inputformat === 'RBG') {\n      rTensorPointer = 0;\n      bTensorPointer = stride;\n      gTensorPointer = stride * 2;\n    }\n\n    for (let i = 0; i < height; i++) {\n      for (let j = 0; j < width; j++) {\n        const R = ((tensor.data[rTensorPointer++] as number) - normBias[0]) * normMean[0];  // R value\n        const G = ((tensor.data[gTensorPointer++] as number) - normBias[1]) * normMean[1];  // G value\n        const B = ((tensor.data[bTensorPointer++] as number) - normBias[2]) * normMean[2];  // B value\n        const A = aTensorPointer === -1 ?\n            255 :\n            ((tensor.data[aTensorPointer++] as number) - normBias[3]) * normMean[3];  // A value\n        // eslint-disable-next-line @typescript-eslint/restrict-plus-operands\n        pixels2DContext.fillStyle = 'rgba(' + R + ',' + G + ',' + B + ',' + A + ')';\n        pixels2DContext.fillRect(j, i, 1, 1);\n      }\n    }\n    if ('toDataURL' in canvas) {\n      return canvas.toDataURL();\n    } else {\n      throw new Error('toDataURL is not supported');\n    }\n  } else {\n    throw new Error('Can not access image data');\n  }\n};\n\n/**\n * implementation of Tensor.toImageData()\n */\nexport const tensorToImageData = (tensor: Tensor, options?: TensorToImageDataOptions): ImageData => {\n  const pixels2DContext = typeof document !== 'undefined' ?\n      document.createElement('canvas').getContext('2d') :\n      new OffscreenCanvas(1, 1).getContext('2d') as OffscreenCanvasRenderingContext2D;\n  let image: ImageData;\n  if (pixels2DContext != null) {\n    // Default values for height and width & format\n    let width: number;\n    let height: number;\n    let channels: number;\n    if (options?.tensorLayout !== undefined && options.tensorLayout === 'NHWC') {\n      width = tensor.dims[2];\n      height = tensor.dims[1];\n      channels = tensor.dims[3];\n    } else {  // Default layout is NCWH\n      width = tensor.dims[3];\n      height = tensor.dims[2];\n      channels = tensor.dims[1];\n    }\n    const inputformat = options !== undefined ? (options.format !== undefined ? options.format : 'RGB') : 'RGB';\n\n    const norm = options?.norm;\n    let normMean: [number, number, number, number];\n    let normBias: [number, number, number, number];\n    if (norm === undefined || norm.mean === undefined) {\n      normMean = [255, 255, 255, 255];\n    } else {\n      if (typeof (norm.mean) === 'number') {\n        normMean = [norm.mean, norm.mean, norm.mean, norm.mean];\n      } else {\n        normMean = [norm.mean[0], norm.mean[1], norm.mean[2], 255];\n        if (norm.mean[3] !== undefined) {\n          normMean[3] = norm.mean[3];\n        }\n      }\n    }\n    if (norm === undefined || norm.bias === undefined) {\n      normBias = [0, 0, 0, 0];\n    } else {\n      if (typeof (norm.bias) === 'number') {\n        normBias = [norm.bias, norm.bias, norm.bias, norm.bias];\n      } else {\n        normBias = [norm.bias[0], norm.bias[1], norm.bias[2], 0];\n        if (norm.bias[3] !== undefined) {\n          normBias[3] = norm.bias[3];\n        }\n      }\n    }\n\n    const stride = height * width;\n    if (options !== undefined) {\n      if (options.format !== undefined && (channels === 4 && options.format !== 'RGBA') ||\n          (channels === 3 && (options.format !== 'RGB' && options.format !== 'BGR'))) {\n        throw new Error('Tensor format doesn\\'t match input tensor dims');\n      }\n    }\n\n    // Default pointer assignments\n    const step = 4;\n    let rImagePointer = 0, gImagePointer = 1, bImagePointer = 2, aImagePointer = 3;\n    let rTensorPointer = 0, gTensorPointer = stride, bTensorPointer = stride * 2, aTensorPointer = -1;\n\n    // Updating the pointer assignments based on the input image format\n    if (inputformat === 'RGBA') {\n      rTensorPointer = 0;\n      gTensorPointer = stride;\n      bTensorPointer = stride * 2;\n      aTensorPointer = stride * 3;\n    } else if (inputformat === 'RGB') {\n      rTensorPointer = 0;\n      gTensorPointer = stride;\n      bTensorPointer = stride * 2;\n    } else if (inputformat === 'RBG') {\n      rTensorPointer = 0;\n      bTensorPointer = stride;\n      gTensorPointer = stride * 2;\n    }\n\n    image = pixels2DContext.createImageData(width, height);\n\n    for (let i = 0; i < height * width;\n         rImagePointer += step, gImagePointer += step, bImagePointer += step, aImagePointer += step, i++) {\n      image.data[rImagePointer] = ((tensor.data[rTensorPointer++] as number) - normBias[0]) * normMean[0];  // R value\n      image.data[gImagePointer] = ((tensor.data[gTensorPointer++] as number) - normBias[1]) * normMean[1];  // G value\n      image.data[bImagePointer] = ((tensor.data[bTensorPointer++] as number) - normBias[2]) * normMean[2];  // B value\n      image.data[aImagePointer] = aTensorPointer === -1 ?\n          255 :\n          ((tensor.data[aTensorPointer++] as number) - normBias[3]) * normMean[3];  // A value\n    }\n\n  } else {\n    throw new Error('Can not access image data');\n  }\n  return image;\n};\n","// Copyright (c) Microsoft Corporation. All rights reserved.\n// Licensed under the MIT License.\n\nimport {OptionsDimensions, OptionsFormat, OptionsNormalizationParameters, OptionsTensorFormat, OptionsTensorLayout, TensorFromGpuBufferOptions, TensorFromImageBitmapOptions, TensorFromImageDataOptions, TensorFromImageElementOptions, TensorFromTextureOptions, TensorFromUrlOptions} from './tensor-factory.js';\nimport {Tensor} from './tensor-impl.js';\nimport {Tensor as TensorInterface} from './tensor.js';\n\ninterface BufferToTensorOptions extends OptionsDimensions, OptionsTensorLayout, OptionsNormalizationParameters,\n                                        OptionsFormat, OptionsTensorFormat {}\n\n/**\n * Create a new tensor object from image object\n *\n * @param buffer - Extracted image buffer data - assuming RGBA format\n * @param imageFormat - input image configuration - required configurations height, width, format\n * @param tensorFormat - output tensor configuration - Default is RGB format\n */\nexport const bufferToTensor = (buffer: Uint8ClampedArray|undefined, options: BufferToTensorOptions): Tensor => {\n  if (buffer === undefined) {\n    throw new Error('Image buffer must be defined');\n  }\n  if (options.height === undefined || options.width === undefined) {\n    throw new Error('Image height and width must be defined');\n  }\n  if (options.tensorLayout === 'NHWC') {\n    throw new Error('NHWC Tensor layout is not supported yet');\n  }\n\n  const {height, width} = options;\n\n  const norm = options.norm ?? {mean: 255, bias: 0};\n  let normMean: [number, number, number, number];\n  let normBias: [number, number, number, number];\n\n  if (typeof (norm.mean) === 'number') {\n    normMean = [norm.mean, norm.mean, norm.mean, norm.mean];\n  } else {\n    normMean = [norm.mean![0], norm.mean![1], norm.mean![2], norm.mean![3] ?? 255];\n  }\n\n  if (typeof (norm.bias) === 'number') {\n    normBias = [norm.bias, norm.bias, norm.bias, norm.bias];\n  } else {\n    normBias = [norm.bias![0], norm.bias![1], norm.bias![2], norm.bias![3] ?? 0];\n  }\n\n  const inputformat = options.format !== undefined ? options.format : 'RGBA';\n  // default value is RGBA since imagedata and HTMLImageElement uses it\n\n  const outputformat =\n      options.tensorFormat !== undefined ? (options.tensorFormat !== undefined ? options.tensorFormat : 'RGB') : 'RGB';\n  const stride = height * width;\n  const float32Data = outputformat === 'RGBA' ? new Float32Array(stride * 4) : new Float32Array(stride * 3);\n\n  // Default pointer assignments\n  let step = 4, rImagePointer = 0, gImagePointer = 1, bImagePointer = 2, aImagePointer = 3;\n  let rTensorPointer = 0, gTensorPointer = stride, bTensorPointer = stride * 2, aTensorPointer = -1;\n\n  // Updating the pointer assignments based on the input image format\n  if (inputformat === 'RGB') {\n    step = 3;\n    rImagePointer = 0;\n    gImagePointer = 1;\n    bImagePointer = 2;\n    aImagePointer = -1;\n  }\n\n  // Updating the pointer assignments based on the output tensor format\n  if (outputformat === 'RGBA') {\n    aTensorPointer = stride * 3;\n  } else if (outputformat === 'RBG') {\n    rTensorPointer = 0;\n    bTensorPointer = stride;\n    gTensorPointer = stride * 2;\n  } else if (outputformat === 'BGR') {\n    bTensorPointer = 0;\n    gTensorPointer = stride;\n    rTensorPointer = stride * 2;\n  }\n\n  for (let i = 0; i < stride;\n       i++, rImagePointer += step, bImagePointer += step, gImagePointer += step, aImagePointer += step) {\n    float32Data[rTensorPointer++] = (buffer[rImagePointer] + normBias[0]) / normMean[0];\n    float32Data[gTensorPointer++] = (buffer[gImagePointer] + normBias[1]) / normMean[1];\n    float32Data[bTensorPointer++] = (buffer[bImagePointer] + normBias[2]) / normMean[2];\n    if (aTensorPointer !== -1 && aImagePointer !== -1) {\n      float32Data[aTensorPointer++] = (buffer[aImagePointer] + normBias[3]) / normMean[3];\n    }\n  }\n\n  // Float32Array -> ort.Tensor\n  const outputTensor = outputformat === 'RGBA' ? new Tensor('float32', float32Data, [1, 4, height, width]) :\n                                                 new Tensor('float32', float32Data, [1, 3, height, width]);\n  return outputTensor;\n};\n\n/**\n * implementation of Tensor.fromImage().\n */\nexport const tensorFromImage = async(\n    image: ImageData|HTMLImageElement|ImageBitmap|string,\n    options?: TensorFromImageDataOptions|TensorFromImageElementOptions|TensorFromImageBitmapOptions|\n    TensorFromUrlOptions): Promise<Tensor> => {\n  // checking the type of image object\n  const isHTMLImageEle = typeof (HTMLImageElement) !== 'undefined' && image instanceof HTMLImageElement;\n  const isImageDataEle = typeof (ImageData) !== 'undefined' && image instanceof ImageData;\n  const isImageBitmap = typeof (ImageBitmap) !== 'undefined' && image instanceof ImageBitmap;\n  const isString = typeof image === 'string';\n\n  let data: Uint8ClampedArray|undefined;\n  let bufferToTensorOptions: BufferToTensorOptions = options ?? {};\n\n  const createCanvas = () => {\n    if (typeof document !== 'undefined') {\n      return document.createElement('canvas');\n    } else if (typeof OffscreenCanvas !== 'undefined') {\n      return new OffscreenCanvas(1, 1);\n    } else {\n      throw new Error('Canvas is not supported');\n    }\n  };\n  const createCanvasContext = (canvas: HTMLCanvasElement|OffscreenCanvas) => {\n    if (canvas instanceof HTMLCanvasElement) {\n      return canvas.getContext('2d');\n    } else if (canvas instanceof OffscreenCanvas) {\n      return canvas.getContext('2d') as OffscreenCanvasRenderingContext2D;\n    } else {\n      return null;\n    }\n  };\n  // filling and checking image configuration options\n  if (isHTMLImageEle) {\n    // HTMLImageElement - image object - format is RGBA by default\n    const canvas = createCanvas();\n    canvas.width = image.width;\n    canvas.height = image.height;\n    const pixels2DContext = createCanvasContext(canvas);\n\n    if (pixels2DContext != null) {\n      let height = image.height;\n      let width = image.width;\n      if (options !== undefined && options.resizedHeight !== undefined && options.resizedWidth !== undefined) {\n        height = options.resizedHeight;\n        width = options.resizedWidth;\n      }\n\n      if (options !== undefined) {\n        bufferToTensorOptions = options;\n        if (options.tensorFormat !== undefined) {\n          throw new Error('Image input config format must be RGBA for HTMLImageElement');\n        } else {\n          bufferToTensorOptions.tensorFormat = 'RGBA';\n        }\n        bufferToTensorOptions.height = height;\n        bufferToTensorOptions.width = width;\n      } else {\n        bufferToTensorOptions.tensorFormat = 'RGBA';\n        bufferToTensorOptions.height = height;\n        bufferToTensorOptions.width = width;\n      }\n\n      pixels2DContext.drawImage(image, 0, 0);\n      data = pixels2DContext.getImageData(0, 0, width, height).data;\n    } else {\n      throw new Error('Can not access image data');\n    }\n  } else if (isImageDataEle) {\n    let height: number;\n    let width: number;\n\n    if (options !== undefined && options.resizedWidth !== undefined && options.resizedHeight !== undefined) {\n      height = options.resizedHeight;\n      width = options.resizedWidth;\n    } else {\n      height = image.height;\n      width = image.width;\n    }\n\n    if (options !== undefined) {\n      bufferToTensorOptions = options;\n    }\n    bufferToTensorOptions.format = 'RGBA';\n    bufferToTensorOptions.height = height;\n    bufferToTensorOptions.width = width;\n\n    if (options !== undefined) {\n      const tempCanvas = createCanvas();\n\n      tempCanvas.width = width;\n      tempCanvas.height = height;\n\n      const pixels2DContext = createCanvasContext(tempCanvas);\n\n      if (pixels2DContext != null) {\n        pixels2DContext.putImageData(image, 0, 0);\n        data = pixels2DContext.getImageData(0, 0, width, height).data;\n      } else {\n        throw new Error('Can not access image data');\n      }\n    } else {\n      data = image.data;\n    }\n  } else if (isImageBitmap) {\n    // ImageBitmap - image object - format must be provided by user\n    if (options === undefined) {\n      throw new Error('Please provide image config with format for Imagebitmap');\n    }\n\n    const canvas = createCanvas();\n    canvas.width = image.width;\n    canvas.height = image.height;\n    const pixels2DContext = createCanvasContext(canvas);\n\n    if (pixels2DContext != null) {\n      const height = image.height;\n      const width = image.width;\n      pixels2DContext.drawImage(image, 0, 0, width, height);\n      data = pixels2DContext.getImageData(0, 0, width, height).data;\n      bufferToTensorOptions.height = height;\n      bufferToTensorOptions.width = width;\n      return bufferToTensor(data, bufferToTensorOptions);\n    } else {\n      throw new Error('Can not access image data');\n    }\n  } else if (isString) {\n    return new Promise((resolve, reject) => {\n      const canvas = createCanvas();\n      const context = createCanvasContext(canvas);\n      if (!image || !context) {\n        return reject();\n      }\n      const newImage = new Image();\n      newImage.crossOrigin = 'Anonymous';\n      newImage.src = image;\n      newImage.onload = () => {\n        canvas.width = newImage.width;\n        canvas.height = newImage.height;\n        context.drawImage(newImage, 0, 0, canvas.width, canvas.height);\n        const img = context.getImageData(0, 0, canvas.width, canvas.height);\n\n        bufferToTensorOptions.height = canvas.height;\n        bufferToTensorOptions.width = canvas.width;\n        resolve(bufferToTensor(img.data, bufferToTensorOptions));\n      };\n    });\n  } else {\n    throw new Error('Input data provided is not supported - aborted tensor creation');\n  }\n\n  if (data !== undefined) {\n    return bufferToTensor(data, bufferToTensorOptions);\n  } else {\n    throw new Error('Input data provided is not supported - aborted tensor creation');\n  }\n};\n\n/**\n * implementation of Tensor.fromTexture().\n */\nexport const tensorFromTexture = <T extends TensorInterface.TextureDataTypes>(\n    texture: TensorInterface.TextureType, options: TensorFromTextureOptions<T>): Tensor => {\n  const {width, height, download, dispose} = options;\n  // Always assume RGBAF32. TODO: support different texture format\n  const dims = [1, height, width, 4];\n  return new Tensor({location: 'texture', type: 'float32', texture, dims, download, dispose});\n};\n\n/**\n * implementation of Tensor.fromGpuBuffer().\n */\nexport const tensorFromGpuBuffer = <T extends TensorInterface.GpuBufferDataTypes>(\n    gpuBuffer: TensorInterface.GpuBufferType, options: TensorFromGpuBufferOptions<T>): Tensor => {\n  const {dataType, dims, download, dispose} = options;\n  return new Tensor({location: 'gpu-buffer', type: dataType ?? 'float32', gpuBuffer, dims, download, dispose});\n};\n\n/**\n * implementation of Tensor.fromPinnedBuffer().\n */\nexport const tensorFromPinnedBuffer = <T extends TensorInterface.CpuPinnedDataTypes>(\n    type: T, buffer: TensorInterface.DataTypeMap[T], dims?: readonly number[]): Tensor =>\n    new Tensor({location: 'cpu-pinned', type, data: buffer, dims: dims ?? [buffer.length]});\n","// Copyright (c) Microsoft Corporation. All rights reserved.\n// Licensed under the MIT License.\n\nimport {Tensor} from './tensor.js';\n\nexport type SupportedTypedArrayConstructors = Float32ArrayConstructor|Uint8ArrayConstructor|Int8ArrayConstructor|\n    Uint16ArrayConstructor|Int16ArrayConstructor|Int32ArrayConstructor|BigInt64ArrayConstructor|Uint8ArrayConstructor|\n    Float64ArrayConstructor|Uint32ArrayConstructor|BigUint64ArrayConstructor;\nexport type SupportedTypedArray = InstanceType<SupportedTypedArrayConstructors>;\n\n// a runtime map that maps type string to TypedArray constructor. Should match Tensor.DataTypeMap.\nexport const NUMERIC_TENSOR_TYPE_TO_TYPEDARRAY_MAP = new Map<string, SupportedTypedArrayConstructors>([\n  ['float32', Float32Array],\n  ['uint8', Uint8Array],\n  ['int8', Int8Array],\n  ['uint16', Uint16Array],\n  ['int16', Int16Array],\n  ['int32', Int32Array],\n  ['bool', Uint8Array],\n  ['float64', Float64Array],\n  ['uint32', Uint32Array],\n]);\n\n// a runtime map that maps type string to TypedArray constructor. Should match Tensor.DataTypeMap.\nexport const NUMERIC_TENSOR_TYPEDARRAY_TO_TYPE_MAP = new Map<SupportedTypedArrayConstructors, Tensor.Type>([\n  [Float32Array, 'float32'],\n  [Uint8Array, 'uint8'],\n  [Int8Array, 'int8'],\n  [Uint16Array, 'uint16'],\n  [Int16Array, 'int16'],\n  [Int32Array, 'int32'],\n  [Float64Array, 'float64'],\n  [Uint32Array, 'uint32'],\n]);\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// the following code allows delaying execution of BigInt/Float16Array checking. This allows lazy initialization for\n// NUMERIC_TENSOR_TYPE_TO_TYPEDARRAY_MAP and NUMERIC_TENSOR_TYPEDARRAY_TO_TYPE_MAP, which allows BigInt/Float16Array\n// polyfill if available.\nlet isTypedArrayChecked = false;\nexport const checkTypedArray = () => {\n  if (!isTypedArrayChecked) {\n    isTypedArrayChecked = true;\n    const isBigInt64ArrayAvailable = typeof BigInt64Array !== 'undefined' && BigInt64Array.from;\n    const isBigUint64ArrayAvailable = typeof BigUint64Array !== 'undefined' && BigUint64Array.from;\n    const isFloat16ArrayAvailable = typeof Float16Array !== 'undefined' && Float16Array.from;\n\n    if (isBigInt64ArrayAvailable) {\n      NUMERIC_TENSOR_TYPE_TO_TYPEDARRAY_MAP.set('int64', BigInt64Array);\n      NUMERIC_TENSOR_TYPEDARRAY_TO_TYPE_MAP.set(BigInt64Array, 'int64');\n    }\n    if (isBigUint64ArrayAvailable) {\n      NUMERIC_TENSOR_TYPE_TO_TYPEDARRAY_MAP.set('uint64', BigUint64Array);\n      NUMERIC_TENSOR_TYPEDARRAY_TO_TYPE_MAP.set(BigUint64Array, 'uint64');\n    }\n    if (isFloat16ArrayAvailable) {\n      NUMERIC_TENSOR_TYPE_TO_TYPEDARRAY_MAP.set('float16', Float16Array);\n      NUMERIC_TENSOR_TYPEDARRAY_TO_TYPE_MAP.set(Float16Array, 'float16');\n    } else {\n      // if Float16Array is not available, use 'Uint16Array' to store the data.\n      NUMERIC_TENSOR_TYPE_TO_TYPEDARRAY_MAP.set('float16', Uint16Array);\n    }\n  }\n};\n","// Copyright (c) Microsoft Corporation. All rights reserved.\n// Licensed under the MIT License.\n\nimport {CpuPinnedConstructorParameters, GpuBufferConstructorParameters, TextureConstructorParameters} from './tensor-factory.js';\nimport {Tensor} from './tensor-impl.js';\n\n/**\n * calculate size from dims.\n *\n * @param dims the dims array. May be an illegal input.\n */\nexport const calculateSize = (dims: readonly unknown[]): number => {\n  let size = 1;\n  for (let i = 0; i < dims.length; i++) {\n    const dim = dims[i];\n    if (typeof dim !== 'number' || !Number.isSafeInteger(dim)) {\n      throw new TypeError(`dims[${i}] must be an integer, got: ${dim}`);\n    }\n    if (dim < 0) {\n      throw new RangeError(`dims[${i}] must be a non-negative integer, got: ${dim}`);\n    }\n    size *= dim;\n  }\n  return size;\n};\n\n/**\n * implementation of Tensor.reshape()\n */\nexport const tensorReshape = (tensor: Tensor, dims: readonly number[]): Tensor => {\n  switch (tensor.location) {\n    case 'cpu':\n      return new Tensor(tensor.type, tensor.data, dims);\n    case 'cpu-pinned':\n      return new Tensor({\n        location: 'cpu-pinned',\n        data: tensor.data as CpuPinnedConstructorParameters['data'],\n        type: tensor.type as CpuPinnedConstructorParameters['type'],\n        dims,\n      });\n    case 'texture':\n      return new Tensor({\n        location: 'texture',\n        texture: tensor.texture,\n        type: tensor.type as TextureConstructorParameters['type'],\n        dims,\n      });\n    case 'gpu-buffer':\n      return new Tensor({\n        location: 'gpu-buffer',\n        gpuBuffer: tensor.gpuBuffer,\n        type: tensor.type as GpuBufferConstructorParameters['type'],\n        dims,\n      });\n    default:\n      throw new Error(`tensorReshape: tensor location ${tensor.location} is not supported`);\n  }\n};\n","// Copyright (c) Microsoft Corporation. All rights reserved.\n// Licensed under the MIT License.\n\nimport {tensorToDataURL, tensorToImageData} from './tensor-conversion-impl.js';\nimport {TensorToDataUrlOptions, TensorToImageDataOptions} from './tensor-conversion.js';\nimport {tensorFromGpuBuffer, tensorFromImage, tensorFromPinnedBuffer, tensorFromTexture} from './tensor-factory-impl.js';\nimport {CpuPinnedConstructorParameters, GpuBufferConstructorParameters, TensorFromGpuBufferOptions, TensorFromImageBitmapOptions, TensorFromImageDataOptions, TensorFromImageElementOptions, TensorFromTextureOptions, TensorFromUrlOptions, TextureConstructorParameters} from './tensor-factory.js';\nimport {checkTypedArray, NUMERIC_TENSOR_TYPE_TO_TYPEDARRAY_MAP, NUMERIC_TENSOR_TYPEDARRAY_TO_TYPE_MAP, SupportedTypedArray, SupportedTypedArrayConstructors} from './tensor-impl-type-mapping.js';\nimport {calculateSize, tensorReshape} from './tensor-utils-impl.js';\nimport {Tensor as TensorInterface} from './tensor.js';\n\n// type aliases for those exported from Tensor interface\n\ntype TensorType = TensorInterface.Type;\ntype TensorDataType = TensorInterface.DataType;\ntype TensorDataLocation = TensorInterface.DataLocation;\ntype TensorTextureType = TensorInterface.TextureType;\ntype TensorGpuBufferType = TensorInterface.GpuBufferType;\n\n/**\n * the implementation of Tensor interface.\n *\n * @ignore\n */\nexport class Tensor implements TensorInterface {\n  // #region constructors\n\n  /**\n   * Construct a new CPU tensor object from the given type, data and dims.\n   */\n  constructor(\n      type: TensorType, data: TensorDataType|readonly string[]|readonly number[]|readonly boolean[],\n      dims?: readonly number[]);\n  /**\n   * Construct a new CPU tensor object from the given data and dims. Type is inferred from data.\n   */\n  constructor(data: TensorDataType|readonly string[]|readonly boolean[], dims?: readonly number[]);\n  /**\n   * Construct a new tensor object from the pinned CPU data with the given type and dims.\n   *\n   * Tensor's location will be set to 'cpu-pinned'.\n   *\n   * @param params - Specify the parameters to construct the tensor.\n   */\n  constructor(params: CpuPinnedConstructorParameters);\n  /**\n   * Construct a new tensor object from the WebGL texture with the given type and dims.\n   *\n   * Tensor's location will be set to 'texture'.\n   *\n   * @param params - Specify the parameters to construct the tensor.\n   */\n  constructor(params: TextureConstructorParameters);\n  /**\n   * Construct a new tensor object from the WebGPU buffer with the given type and dims.\n   *\n   * Tensor's location will be set to 'gpu-buffer'.\n   *\n   * @param params - Specify the parameters to construct the tensor.\n   */\n  constructor(params: GpuBufferConstructorParameters);\n\n  /**\n   * implementation.\n   */\n  constructor(\n      arg0: TensorType|TensorDataType|readonly string[]|readonly boolean[]|CpuPinnedConstructorParameters|\n      TextureConstructorParameters|GpuBufferConstructorParameters,\n      arg1?: TensorDataType|readonly number[]|readonly string[]|readonly boolean[], arg2?: readonly number[]) {\n    // perform one-time check for BigInt/Float16Array support\n    checkTypedArray();\n\n    let type: TensorType;\n    let dims: readonly number[];\n\n    if (typeof arg0 === 'object' && 'location' in arg0) {\n      //\n      // constructing tensor from specific location\n      //\n      this.dataLocation = arg0.location;\n      type = arg0.type;\n      dims = arg0.dims;\n      switch (arg0.location) {\n        case 'cpu-pinned': {\n          const expectedTypedArrayConstructor = NUMERIC_TENSOR_TYPE_TO_TYPEDARRAY_MAP.get(type);\n          if (!expectedTypedArrayConstructor) {\n            throw new TypeError(`unsupported type \"${type}\" to create tensor from pinned buffer`);\n          }\n          if (!(arg0.data instanceof expectedTypedArrayConstructor)) {\n            throw new TypeError(`buffer should be of type ${expectedTypedArrayConstructor.name}`);\n          }\n          this.cpuData = arg0.data;\n          break;\n        }\n        case 'texture': {\n          if (type !== 'float32') {\n            throw new TypeError(`unsupported type \"${type}\" to create tensor from texture`);\n          }\n          this.gpuTextureData = arg0.texture;\n          this.downloader = arg0.download;\n          this.disposer = arg0.dispose;\n          break;\n        }\n        case 'gpu-buffer': {\n          if ((type !== 'float32' && type !== 'float16' && type !== 'int32' && type !== 'int64' && type !== 'uint32' &&\n               type !== 'uint8' && type !== 'bool')) {\n            throw new TypeError(`unsupported type \"${type}\" to create tensor from gpu buffer`);\n          }\n          this.gpuBufferData = arg0.gpuBuffer;\n          this.downloader = arg0.download;\n          this.disposer = arg0.dispose;\n          break;\n        }\n        default:\n          throw new Error(`Tensor constructor: unsupported location '${this.dataLocation}'`);\n      }\n    } else {\n      //\n      // constructing tensor of location 'cpu'\n      //\n      let data: TensorDataType;\n      let maybeDims: typeof arg1|typeof arg2;\n      // check whether arg0 is type or data\n      if (typeof arg0 === 'string') {\n        //\n        // Override: constructor(type, data, ...)\n        //\n        type = arg0;\n        maybeDims = arg2;\n        if (arg0 === 'string') {\n          // string tensor\n          if (!Array.isArray(arg1)) {\n            throw new TypeError('A string tensor\\'s data must be a string array.');\n          }\n          // we don't check whether every element in the array is string; this is too slow. we assume it's correct and\n          // error will be populated at inference\n          data = arg1;\n        } else {\n          // numeric tensor\n          const typedArrayConstructor = NUMERIC_TENSOR_TYPE_TO_TYPEDARRAY_MAP.get(arg0);\n          if (typedArrayConstructor === undefined) {\n            throw new TypeError(`Unsupported tensor type: ${arg0}.`);\n          }\n          if (Array.isArray(arg1)) {\n            if (arg0 === 'float16' && typedArrayConstructor === Uint16Array) {\n              // When no Float16Array polyfill is used, we cannot create 'float16' tensor from number array.\n              //\n              // Throw error here because when user try to use number array as data,\n              // e.g. new Tensor('float16', [1, 2, 3, 4], dims)), it will actually call\n              // Uint16Array.from(arg1) which generates wrong data.\n              throw new TypeError(\n                  'Creating a float16 tensor from number array is not supported. Please use Uint16Array as data.');\n            } else if (arg0 === 'uint64' || arg0 === 'int64') {\n              // use 'as any' here because:\n              // 1. TypeScript's check on type of 'Array.isArray()' does not work with readonly arrays.\n              // see https://github.com/microsoft/TypeScript/issues/17002\n              // 2. TypeScript's check on union type of '(BigInt64ArrayConstructor|BigUint64ArrayConstructor).from()'\n              // does not accept parameter mapFn.\n              // 3. parameters of 'SupportedTypedArrayConstructors.from()' does not match the requirement of the union\n              // type.\n\n              // assume 'arg1' is of type \"readonly number[]|readonly bigint[]\" here.\n\n              // eslint-disable-next-line @typescript-eslint/no-explicit-any\n              data = (typedArrayConstructor as any).from(arg1, BigInt);\n            } else {\n              // assume 'arg1' is of type \"readonly number[]\" here.\n              // eslint-disable-next-line @typescript-eslint/no-explicit-any\n              data = (typedArrayConstructor as any).from(arg1);\n            }\n          } else if (arg1 instanceof typedArrayConstructor) {\n            data = arg1;\n          } else {\n            throw new TypeError(`A ${type} tensor's data must be type of ${typedArrayConstructor}`);\n          }\n        }\n      } else {\n        //\n        // Override: constructor(data, ...)\n        //\n        maybeDims = arg1;\n        if (Array.isArray(arg0)) {\n          // only boolean[] and string[] is supported\n          if (arg0.length === 0) {\n            throw new TypeError('Tensor type cannot be inferred from an empty array.');\n          }\n          const firstElementType = typeof arg0[0];\n          if (firstElementType === 'string') {\n            type = 'string';\n            data = arg0;\n          } else if (firstElementType === 'boolean') {\n            type = 'bool';\n            // 'arg0' is of type 'boolean[]'. Uint8Array.from(boolean[]) actually works, but typescript thinks this is\n            // wrong type. We use 'as any' to make it happy.\n            // eslint-disable-next-line @typescript-eslint/no-explicit-any\n            data = Uint8Array.from(arg0 as any[]);\n          } else {\n            throw new TypeError(`Invalid element type of data array: ${firstElementType}.`);\n          }\n        } else {\n          // get tensor type from TypedArray\n          const mappedType =\n              NUMERIC_TENSOR_TYPEDARRAY_TO_TYPE_MAP.get(arg0.constructor as SupportedTypedArrayConstructors);\n          if (mappedType === undefined) {\n            throw new TypeError(`Unsupported type for tensor data: ${arg0.constructor}.`);\n          }\n          type = mappedType;\n          data = arg0 as SupportedTypedArray;\n        }\n      }\n\n      // type and data is processed, now processing dims\n      if (maybeDims === undefined) {\n        // assume 1-D tensor if dims omitted\n        maybeDims = [data.length];\n      } else if (!Array.isArray(maybeDims)) {\n        throw new TypeError('A tensor\\'s dims must be a number array');\n      }\n      dims = maybeDims as readonly number[];\n\n      this.cpuData = data;\n      this.dataLocation = 'cpu';\n    }\n\n    // perform check on dims\n    const size = calculateSize(dims);\n    // if data is on CPU, check whether data length matches tensor size\n    if (this.cpuData && size !== this.cpuData.length) {\n      throw new Error(`Tensor's size(${size}) does not match data length(${this.cpuData.length}).`);\n    }\n\n    this.type = type;\n    this.dims = dims;\n    this.size = size;\n  }\n  // #endregion\n\n  // #region factory\n  static async fromImage(\n      image: ImageData|HTMLImageElement|ImageBitmap|string,\n      options?: TensorFromImageDataOptions|TensorFromImageElementOptions|TensorFromImageBitmapOptions|\n      TensorFromUrlOptions): Promise<TensorInterface> {\n    return tensorFromImage(image, options);\n  }\n\n  static fromTexture<T extends TensorInterface.TextureDataTypes>(\n      texture: TensorTextureType, options: TensorFromTextureOptions<T>): TensorInterface {\n    return tensorFromTexture(texture, options);\n  }\n\n  static fromGpuBuffer<T extends TensorInterface.GpuBufferDataTypes>(\n      gpuBuffer: TensorGpuBufferType, options: TensorFromGpuBufferOptions<T>): TensorInterface {\n    return tensorFromGpuBuffer(gpuBuffer, options);\n  }\n\n  static fromPinnedBuffer<T extends TensorInterface.CpuPinnedDataTypes>(\n      type: T, buffer: TensorInterface.DataTypeMap[T], dims?: readonly number[]): Tensor {\n    return tensorFromPinnedBuffer(type, buffer, dims);\n  }\n\n  // #endregion\n\n  // #region conversions\n  toDataURL(options?: TensorToDataUrlOptions): string {\n    return tensorToDataURL(this, options);\n  }\n\n  toImageData(options?: TensorToImageDataOptions): ImageData {\n    return tensorToImageData(this, options);\n  }\n  // #endregion\n\n  // #region public fields\n  readonly dims: readonly number[];\n  readonly type: TensorType;\n  readonly size: number;\n  // #endregion\n\n  // #region private fields\n\n  /**\n   * stores the location of the data.\n   */\n  private dataLocation: TensorDataLocation;\n\n  /**\n   * stores the data on CPU, if location is 'cpu' or 'cpu-pinned'. otherwise empty.\n   */\n  private cpuData?: TensorDataType;\n\n  /**\n   * stores the underlying texture when location is 'texture'. otherwise empty.\n   */\n  private gpuTextureData?: TensorTextureType;\n\n  /**\n   * stores the underlying GPU buffer when location is 'gpu-buffer'. otherwise empty.\n   */\n  private gpuBufferData?: TensorGpuBufferType;\n\n  /**\n   * stores an optional downloader function to download data from GPU to CPU.\n   */\n  private downloader?(): Promise<TensorDataType>;\n\n  /**\n   * a flag indicating whether the data is being downloaded from GPU to CPU.\n   */\n  private isDownloading?: boolean;\n\n  /**\n   * stores an optional disposer function to dispose the underlying data.\n   */\n  private disposer?(): void;\n  // #endregion\n\n  // #region properties\n  get data(): TensorDataType {\n    this.ensureValid();\n    if (!this.cpuData) {\n      throw new Error(\n          'The data is not on CPU. Use `getData()` to download GPU data to CPU, ' +\n          'or use `texture` or `gpuBuffer` property to access the GPU data directly.');\n    }\n    return this.cpuData;\n  }\n\n  get location(): TensorDataLocation {\n    return this.dataLocation;\n  }\n\n  get texture(): TensorTextureType {\n    this.ensureValid();\n    if (!this.gpuTextureData) {\n      throw new Error('The data is not stored as a WebGL texture.');\n    }\n    return this.gpuTextureData;\n  }\n\n  get gpuBuffer(): TensorGpuBufferType {\n    this.ensureValid();\n    if (!this.gpuBufferData) {\n      throw new Error('The data is not stored as a WebGPU buffer.');\n    }\n    return this.gpuBufferData;\n  }\n  // #endregion\n\n  // #region methods\n\n  async getData(releaseData?: boolean): Promise<TensorDataType> {\n    this.ensureValid();\n    switch (this.dataLocation) {\n      case 'cpu':\n      case 'cpu-pinned':\n        return this.data;\n      case 'texture':\n      case 'gpu-buffer': {\n        if (!this.downloader) {\n          throw new Error('The current tensor is not created with a specified data downloader.');\n        }\n        if (this.isDownloading) {\n          throw new Error('The current tensor is being downloaded.');\n        }\n        try {\n          this.isDownloading = true;\n          const data = await this.downloader();\n          this.downloader = undefined;\n          this.dataLocation = 'cpu';\n          this.cpuData = data;\n\n          if (releaseData && this.disposer) {\n            this.disposer();\n            this.disposer = undefined;\n          }\n\n          return data;\n\n        } finally {\n          this.isDownloading = false;\n        }\n      }\n      default:\n        throw new Error(`cannot get data from location: ${this.dataLocation}`);\n    }\n  }\n\n  dispose(): void {\n    if (this.isDownloading) {\n      throw new Error('The current tensor is being downloaded.');\n    }\n\n    if (this.disposer) {\n      this.disposer();\n      this.disposer = undefined;\n    }\n    this.cpuData = undefined;\n    this.gpuTextureData = undefined;\n    this.gpuBufferData = undefined;\n    this.downloader = undefined;\n    this.isDownloading = undefined;\n\n    this.dataLocation = 'none';\n  }\n\n  // #endregion\n\n  // #region tensor utilities\n  private ensureValid(): void {\n    if (this.dataLocation === 'none') {\n      throw new Error('The tensor is disposed.');\n    }\n  }\n\n  reshape(dims: readonly number[]): TensorInterface {\n    this.ensureValid();\n    if (this.downloader || this.disposer) {\n      throw new Error('Cannot reshape a tensor that owns GPU resource.');\n    }\n    return tensorReshape(this, dims);\n  }\n  // #endregion\n}\n","// Copyright (c) Microsoft Corporation. All rights reserved.\n// Licensed under the MIT License.\n\nimport {TensorFactory} from './tensor-factory.js';\nimport {Tensor as TensorImpl} from './tensor-impl.js';\nimport {TypedTensorUtils} from './tensor-utils.js';\n\n/* eslint-disable @typescript-eslint/no-redeclare */\n\n/**\n * represent a basic tensor with specified dimensions and data type.\n */\ninterface TypedTensorBase<T extends Tensor.Type> {\n  /**\n   * Get the dimensions of the tensor.\n   */\n  readonly dims: readonly number[];\n  /**\n   * Get the data type of the tensor.\n   */\n  readonly type: T;\n  /**\n   * Get the buffer data of the tensor.\n   *\n   * If the data is not on CPU (eg. it's in the form of WebGL texture or WebGPU buffer), throw error.\n   */\n  readonly data: Tensor.DataTypeMap[T];\n  /**\n   * Get the location of the data.\n   */\n  readonly location: Tensor.DataLocation;\n  /**\n   * Get the WebGL texture that holds the tensor data.\n   *\n   * If the data is not on GPU as WebGL texture, throw error.\n   */\n  readonly texture: Tensor.TextureType;\n  /**\n   * Get the WebGPU buffer that holds the tensor data.\n   *\n   * If the data is not on GPU as WebGPU buffer, throw error.\n   */\n  readonly gpuBuffer: Tensor.GpuBufferType;\n\n  /**\n   * Get the buffer data of the tensor.\n   *\n   * If the data is on CPU, returns the data immediately.\n   * If the data is on GPU, downloads the data and returns the promise.\n   *\n   * @param releaseData - whether release the data on GPU. Ignore if data is already on CPU.\n   */\n  getData(releaseData?: boolean): Promise<Tensor.DataTypeMap[T]>;\n\n  /**\n   * Dispose the tensor data.\n   *\n   * If the data is on CPU, remove its internal reference to the underlying data.\n   * If the data is on GPU, release the data on GPU.\n   *\n   * After calling this function, the tensor is considered no longer valid. Its location will be set to 'none'.\n   */\n  dispose(): void;\n}\n\nexport declare namespace Tensor {\n  interface DataTypeMap {\n    float32: Float32Array;\n    uint8: Uint8Array;\n    int8: Int8Array;\n    uint16: Uint16Array;\n    int16: Int16Array;\n    int32: Int32Array;\n    int64: BigInt64Array;\n    string: string[];\n    bool: Uint8Array;\n    float16: Uint16Array;  // Keep using Uint16Array until we have a concrete solution for float 16.\n    float64: Float64Array;\n    uint32: Uint32Array;\n    uint64: BigUint64Array;\n    // complex64: never;\n    // complex128: never;\n    // bfloat16: never;\n  }\n\n  interface ElementTypeMap {\n    float32: number;\n    uint8: number;\n    int8: number;\n    uint16: number;\n    int16: number;\n    int32: number;\n    int64: bigint;\n    string: string;\n    bool: boolean;\n    float16: number;  // Keep using Uint16Array until we have a concrete solution for float 16.\n    float64: number;\n    uint32: number;\n    uint64: bigint;\n    // complex64: never;\n    // complex128: never;\n    // bfloat16: never;\n  }\n\n  type DataType = DataTypeMap[Type];\n  type ElementType = ElementTypeMap[Type];\n\n  /**\n   * supported data types for constructing a tensor from a pinned CPU buffer\n   */\n  export type CpuPinnedDataTypes = Exclude<Tensor.Type, 'string'>;\n\n  /**\n   * type alias for WebGL texture\n   */\n  export type TextureType = WebGLTexture;\n\n  /**\n   * supported data types for constructing a tensor from a WebGL texture\n   */\n  export type TextureDataTypes = 'float32';\n\n  /**\n   * type alias for WebGPU buffer\n   *\n   * The reason why we don't use type \"GPUBuffer\" defined in webgpu.d.ts from @webgpu/types is because \"@webgpu/types\"\n   * requires \"@types/dom-webcodecs\" as peer dependency when using TypeScript < v5.1 and its version need to be chosen\n   * carefully according to the TypeScript version being used. This means so far there is not a way to keep every\n   * TypeScript version happy. It turns out that we will easily broke users on some TypeScript version.\n   *\n   * for more info see https://github.com/gpuweb/types/issues/127\n   */\n  export type GpuBufferType = {size: number; mapState: 'unmapped' | 'pending' | 'mapped'};\n\n  /**\n   * supported data types for constructing a tensor from a WebGPU buffer\n   */\n  export type GpuBufferDataTypes = 'float32'|'float16'|'int32'|'int64'|'uint32'|'uint8'|'bool';\n\n  /**\n   * represent where the tensor data is stored\n   */\n  export type DataLocation = 'none'|'cpu'|'cpu-pinned'|'texture'|'gpu-buffer';\n\n  /**\n   * represent the data type of a tensor\n   */\n  export type Type = keyof DataTypeMap;\n}\n\n/**\n * Represent multi-dimensional arrays to feed to or fetch from model inferencing.\n */\nexport interface TypedTensor<T extends Tensor.Type> extends TypedTensorBase<T>, TypedTensorUtils<T> {}\n/**\n * Represent multi-dimensional arrays to feed to or fetch from model inferencing.\n */\nexport interface Tensor extends TypedTensorBase<Tensor.Type>, TypedTensorUtils<Tensor.Type> {}\n\n/**\n * type TensorConstructor defines the constructors of 'Tensor' to create CPU tensor instances.\n */\nexport interface TensorConstructor extends TensorFactory {\n  // #region CPU tensor - specify element type\n  /**\n   * Construct a new string tensor object from the given type, data and dims.\n   *\n   * @param type - Specify the element type.\n   * @param data - Specify the CPU tensor data.\n   * @param dims - Specify the dimension of the tensor. If omitted, a 1-D tensor is assumed.\n   */\n  new(type: 'string', data: Tensor.DataTypeMap['string']|readonly string[],\n      dims?: readonly number[]): TypedTensor<'string'>;\n\n  /**\n   * Construct a new bool tensor object from the given type, data and dims.\n   *\n   * @param type - Specify the element type.\n   * @param data - Specify the CPU tensor data.\n   * @param dims - Specify the dimension of the tensor. If omitted, a 1-D tensor is assumed.\n   */\n  new(type: 'bool', data: Tensor.DataTypeMap['bool']|readonly boolean[], dims?: readonly number[]): TypedTensor<'bool'>;\n\n  /**\n   * Construct a new 64-bit integer typed tensor object from the given type, data and dims.\n   *\n   * @param type - Specify the element type.\n   * @param data - Specify the CPU tensor data.\n   * @param dims - Specify the dimension of the tensor. If omitted, a 1-D tensor is assumed.\n   */\n  new<T extends 'uint64'|'int64'>(\n      type: T, data: Tensor.DataTypeMap[T]|readonly bigint[]|readonly number[],\n      dims?: readonly number[]): TypedTensor<T>;\n\n  /**\n   * Construct a new numeric tensor object from the given type, data and dims.\n   *\n   * @param type - Specify the element type.\n   * @param data - Specify the CPU tensor data.\n   * @param dims - Specify the dimension of the tensor. If omitted, a 1-D tensor is assumed.\n   */\n  new<T extends Exclude<Tensor.Type, 'string'|'bool'|'uint64'|'int64'>>(\n      type: T, data: Tensor.DataTypeMap[T]|readonly number[], dims?: readonly number[]): TypedTensor<T>;\n  // #endregion\n\n  // #region CPU tensor - infer element types\n\n  /**\n   * Construct a new float32 tensor object from the given data and dims.\n   *\n   * @param data - Specify the CPU tensor data.\n   * @param dims - Specify the dimension of the tensor. If omitted, a 1-D tensor is assumed.\n   */\n  new(data: Float32Array, dims?: readonly number[]): TypedTensor<'float32'>;\n\n  /**\n   * Construct a new int8 tensor object from the given data and dims.\n   *\n   * @param data - Specify the CPU tensor data.\n   * @param dims - Specify the dimension of the tensor. If omitted, a 1-D tensor is assumed.\n   */\n  new(data: Int8Array, dims?: readonly number[]): TypedTensor<'int8'>;\n\n  /**\n   * Construct a new uint8 tensor object from the given data and dims.\n   *\n   * @param data - Specify the CPU tensor data.\n   * @param dims - Specify the dimension of the tensor. If omitted, a 1-D tensor is assumed.\n   */\n  new(data: Uint8Array, dims?: readonly number[]): TypedTensor<'uint8'>;\n\n  /**\n   * Construct a new uint16 tensor object from the given data and dims.\n   *\n   * @param data - Specify the CPU tensor data.\n   * @param dims - Specify the dimension of the tensor. If omitted, a 1-D tensor is assumed.\n   */\n  new(data: Uint16Array, dims?: readonly number[]): TypedTensor<'uint16'>;\n\n  /**\n   * Construct a new int16 tensor object from the given data and dims.\n   *\n   * @param data - Specify the CPU tensor data.\n   * @param dims - Specify the dimension of the tensor. If omitted, a 1-D tensor is assumed.\n   */\n  new(data: Int16Array, dims?: readonly number[]): TypedTensor<'int16'>;\n\n  /**\n   * Construct a new int32 tensor object from the given data and dims.\n   *\n   * @param data - Specify the CPU tensor data.\n   * @param dims - Specify the dimension of the tensor. If omitted, a 1-D tensor is assumed.\n   */\n  new(data: Int32Array, dims?: readonly number[]): TypedTensor<'int32'>;\n\n  /**\n   * Construct a new int64 tensor object from the given data and dims.\n   *\n   * @param data - Specify the CPU tensor data.\n   * @param dims - Specify the dimension of the tensor. If omitted, a 1-D tensor is assumed.\n   */\n  new(data: BigInt64Array, dims?: readonly number[]): TypedTensor<'int64'>;\n\n  /**\n   * Construct a new string tensor object from the given data and dims.\n   *\n   * @param data - Specify the CPU tensor data.\n   * @param dims - Specify the dimension of the tensor. If omitted, a 1-D tensor is assumed.\n   */\n  new(data: readonly string[], dims?: readonly number[]): TypedTensor<'string'>;\n\n  /**\n   * Construct a new bool tensor object from the given data and dims.\n   *\n   * @param data - Specify the CPU tensor data.\n   * @param dims - Specify the dimension of the tensor. If omitted, a 1-D tensor is assumed.\n   */\n  new(data: readonly boolean[], dims?: readonly number[]): TypedTensor<'bool'>;\n\n  /**\n   * Construct a new float64 tensor object from the given data and dims.\n   *\n   * @param data - Specify the CPU tensor data.\n   * @param dims - Specify the dimension of the tensor. If omitted, a 1-D tensor is assumed.\n   */\n  new(data: Float64Array, dims?: readonly number[]): TypedTensor<'float64'>;\n\n  /**\n   * Construct a new uint32 tensor object from the given data and dims.\n   *\n   * @param data - Specify the CPU tensor data.\n   * @param dims - Specify the dimension of the tensor. If omitted, a 1-D tensor is assumed.\n   */\n  new(data: Uint32Array, dims?: readonly number[]): TypedTensor<'uint32'>;\n\n  /**\n   * Construct a new uint64 tensor object from the given data and dims.\n   *\n   * @param data - Specify the CPU tensor data.\n   * @param dims - Specify the dimension of the tensor. If omitted, a 1-D tensor is assumed.\n   */\n  new(data: BigUint64Array, dims?: readonly number[]): TypedTensor<'uint64'>;\n\n  // #endregion\n\n  // #region CPU tensor - fall back to non-generic tensor type declaration\n\n  /**\n   * Construct a new tensor object from the given type, data and dims.\n   *\n   * @param type - Specify the element type.\n   * @param data - Specify the CPU tensor data.\n   * @param dims - Specify the dimension of the tensor. If omitted, a 1-D tensor is assumed.\n   */\n  new(type: Tensor.Type, data: Tensor.DataType|readonly number[]|readonly string[]|readonly bigint[]|readonly boolean[],\n      dims?: readonly number[]): Tensor;\n\n  /**\n   * Construct a new tensor object from the given data and dims.\n   *\n   * @param data - Specify the CPU tensor data.\n   * @param dims - Specify the dimension of the tensor. If omitted, a 1-D tensor is assumed.\n   */\n  new(data: Tensor.DataType, dims?: readonly number[]): Tensor;\n  // #endregion\n}\n\n// eslint-disable-next-line @typescript-eslint/naming-convention\nexport const Tensor = TensorImpl as TensorConstructor;\n","// Copyright (c) Microsoft Corporation. All rights reserved.\n// Licensed under the MIT License.\n\nimport {env} from './env-impl.js';\n\n/**\n * @ignore\n */\nexport const TRACE = (deviceType: string, label: string) => {\n  if (typeof env.trace === 'undefined' ? !env.wasm.trace : !env.trace) {\n    return;\n  }\n  // eslint-disable-next-line no-console\n  console.timeStamp(`${deviceType}::ORT::${label}`);\n};\n\nconst TRACE_FUNC = (msg: string, extraMsg?: string) => {\n  const stack = new Error().stack?.split(/\\r\\n|\\r|\\n/g) || [];\n  let hasTraceFunc = false;\n  for (let i = 0; i < stack.length; i++) {\n    if (hasTraceFunc && !stack[i].includes('TRACE_FUNC')) {\n      let label = `FUNC_${msg}::${stack[i].trim().split(' ')[1]}`;\n      if (extraMsg) {\n        label += `::${extraMsg}`;\n      }\n      TRACE('CPU', label);\n      return;\n    }\n    if (stack[i].includes('TRACE_FUNC')) {\n      hasTraceFunc = true;\n    }\n  }\n};\n\n/**\n * @ignore\n */\nexport const TRACE_FUNC_BEGIN = (extraMsg?: string) => {\n  if (typeof env.trace === 'undefined' ? !env.wasm.trace : !env.trace) {\n    return;\n  }\n  TRACE_FUNC('BEGIN', extraMsg);\n};\n\n/**\n * @ignore\n */\nexport const TRACE_FUNC_END = (extraMsg?: string) => {\n  if (typeof env.trace === 'undefined' ? !env.wasm.trace : !env.trace) {\n    return;\n  }\n  TRACE_FUNC('END', extraMsg);\n};\n","// Copyright (c) Microsoft Corporation. All rights reserved.\n// Licensed under the MIT License.\n\nimport {resolveBackendAndExecutionProviders} from './backend-impl.js';\nimport {InferenceSessionHandler} from './backend.js';\nimport {InferenceSession as InferenceSessionInterface} from './inference-session.js';\nimport {OnnxValue} from './onnx-value.js';\nimport {Tensor} from './tensor.js';\nimport {TRACE_FUNC_BEGIN, TRACE_FUNC_END} from './trace.js';\n\ntype SessionOptions = InferenceSessionInterface.SessionOptions;\ntype RunOptions = InferenceSessionInterface.RunOptions;\ntype FeedsType = InferenceSessionInterface.FeedsType;\ntype FetchesType = InferenceSessionInterface.FetchesType;\ntype ReturnType = InferenceSessionInterface.ReturnType;\n\nexport class InferenceSession implements InferenceSessionInterface {\n  private constructor(handler: InferenceSessionHandler) {\n    this.handler = handler;\n  }\n  run(feeds: FeedsType, options?: RunOptions): Promise<ReturnType>;\n  run(feeds: FeedsType, fetches: FetchesType, options?: RunOptions): Promise<ReturnType>;\n  async run(feeds: FeedsType, arg1?: FetchesType|RunOptions, arg2?: RunOptions): Promise<ReturnType> {\n    TRACE_FUNC_BEGIN();\n    const fetches: {[name: string]: OnnxValue|null} = {};\n    let options: RunOptions = {};\n    // check inputs\n    if (typeof feeds !== 'object' || feeds === null || feeds instanceof Tensor || Array.isArray(feeds)) {\n      throw new TypeError(\n          '\\'feeds\\' must be an object that use input names as keys and OnnxValue as corresponding values.');\n    }\n\n    let isFetchesEmpty = true;\n    // determine which override is being used\n    if (typeof arg1 === 'object') {\n      if (arg1 === null) {\n        throw new TypeError('Unexpected argument[1]: cannot be null.');\n      }\n      if (arg1 instanceof Tensor) {\n        throw new TypeError('\\'fetches\\' cannot be a Tensor');\n      }\n\n      if (Array.isArray(arg1)) {\n        if (arg1.length === 0) {\n          throw new TypeError('\\'fetches\\' cannot be an empty array.');\n        }\n        isFetchesEmpty = false;\n        // output names\n        for (const name of arg1) {\n          if (typeof name !== 'string') {\n            throw new TypeError('\\'fetches\\' must be a string array or an object.');\n          }\n          if (this.outputNames.indexOf(name) === -1) {\n            throw new RangeError(`'fetches' contains invalid output name: ${name}.`);\n          }\n          fetches[name] = null;\n        }\n\n        if (typeof arg2 === 'object' && arg2 !== null) {\n          options = arg2;\n        } else if (typeof arg2 !== 'undefined') {\n          throw new TypeError('\\'options\\' must be an object.');\n        }\n      } else {\n        // decide whether arg1 is fetches or options\n        // if any output name is present and its value is valid OnnxValue, we consider it fetches\n        let isFetches = false;\n        const arg1Keys = Object.getOwnPropertyNames(arg1);\n        for (const name of this.outputNames) {\n          if (arg1Keys.indexOf(name) !== -1) {\n            const v = (arg1 as InferenceSessionInterface.NullableOnnxValueMapType)[name];\n            if (v === null || v instanceof Tensor) {\n              isFetches = true;\n              isFetchesEmpty = false;\n              fetches[name] = v;\n            }\n          }\n        }\n\n        if (isFetches) {\n          if (typeof arg2 === 'object' && arg2 !== null) {\n            options = arg2;\n          } else if (typeof arg2 !== 'undefined') {\n            throw new TypeError('\\'options\\' must be an object.');\n          }\n        } else {\n          options = arg1 as RunOptions;\n        }\n      }\n    } else if (typeof arg1 !== 'undefined') {\n      throw new TypeError('Unexpected argument[1]: must be \\'fetches\\' or \\'options\\'.');\n    }\n\n    // check if all inputs are in feed\n    for (const name of this.inputNames) {\n      if (typeof feeds[name] === 'undefined') {\n        throw new Error(`input '${name}' is missing in 'feeds'.`);\n      }\n    }\n\n    // if no fetches is specified, we use the full output names list\n    if (isFetchesEmpty) {\n      for (const name of this.outputNames) {\n        fetches[name] = null;\n      }\n    }\n\n    // feeds, fetches and options are prepared\n\n    const results = await this.handler.run(feeds, fetches, options);\n    const returnValue: {[name: string]: OnnxValue} = {};\n    for (const key in results) {\n      if (Object.hasOwnProperty.call(results, key)) {\n        const result = results[key];\n        if (result instanceof Tensor) {\n          returnValue[key] = result;\n        } else {\n          returnValue[key] = new Tensor(result.type, result.data, result.dims);\n        }\n      }\n    }\n    TRACE_FUNC_END();\n    return returnValue;\n  }\n\n  async release(): Promise<void> {\n    return this.handler.dispose();\n  }\n\n  static create(path: string, options?: SessionOptions): Promise<InferenceSessionInterface>;\n  static create(buffer: ArrayBufferLike, options?: SessionOptions): Promise<InferenceSessionInterface>;\n  static create(buffer: ArrayBufferLike, byteOffset: number, byteLength?: number, options?: SessionOptions):\n      Promise<InferenceSessionInterface>;\n  static create(buffer: Uint8Array, options?: SessionOptions): Promise<InferenceSessionInterface>;\n  static async create(\n      arg0: string|ArrayBufferLike|Uint8Array, arg1?: SessionOptions|number, arg2?: number,\n      arg3?: SessionOptions): Promise<InferenceSessionInterface> {\n    TRACE_FUNC_BEGIN();\n    // either load from a file or buffer\n    let filePathOrUint8Array: string|Uint8Array;\n    let options: SessionOptions = {};\n\n    if (typeof arg0 === 'string') {\n      filePathOrUint8Array = arg0;\n      if (typeof arg1 === 'object' && arg1 !== null) {\n        options = arg1;\n      } else if (typeof arg1 !== 'undefined') {\n        throw new TypeError('\\'options\\' must be an object.');\n      }\n    } else if (arg0 instanceof Uint8Array) {\n      filePathOrUint8Array = arg0;\n      if (typeof arg1 === 'object' && arg1 !== null) {\n        options = arg1;\n      } else if (typeof arg1 !== 'undefined') {\n        throw new TypeError('\\'options\\' must be an object.');\n      }\n    } else if (\n        arg0 instanceof ArrayBuffer ||\n        (typeof SharedArrayBuffer !== 'undefined' && arg0 instanceof SharedArrayBuffer)) {\n      const buffer = arg0;\n      let byteOffset = 0;\n      let byteLength = arg0.byteLength;\n      if (typeof arg1 === 'object' && arg1 !== null) {\n        options = arg1;\n      } else if (typeof arg1 === 'number') {\n        byteOffset = arg1;\n        if (!Number.isSafeInteger(byteOffset)) {\n          throw new RangeError('\\'byteOffset\\' must be an integer.');\n        }\n        if (byteOffset < 0 || byteOffset >= buffer.byteLength) {\n          throw new RangeError(`'byteOffset' is out of range [0, ${buffer.byteLength}).`);\n        }\n        byteLength = arg0.byteLength - byteOffset;\n        if (typeof arg2 === 'number') {\n          byteLength = arg2;\n          if (!Number.isSafeInteger(byteLength)) {\n            throw new RangeError('\\'byteLength\\' must be an integer.');\n          }\n          if (byteLength <= 0 || byteOffset + byteLength > buffer.byteLength) {\n            throw new RangeError(`'byteLength' is out of range (0, ${buffer.byteLength - byteOffset}].`);\n          }\n          if (typeof arg3 === 'object' && arg3 !== null) {\n            options = arg3;\n          } else if (typeof arg3 !== 'undefined') {\n            throw new TypeError('\\'options\\' must be an object.');\n          }\n        } else if (typeof arg2 !== 'undefined') {\n          throw new TypeError('\\'byteLength\\' must be a number.');\n        }\n      } else if (typeof arg1 !== 'undefined') {\n        throw new TypeError('\\'options\\' must be an object.');\n      }\n      filePathOrUint8Array = new Uint8Array(buffer, byteOffset, byteLength);\n    } else {\n      throw new TypeError('Unexpected argument[0]: must be \\'path\\' or \\'buffer\\'.');\n    }\n\n    // resolve backend, update session options with validated EPs, and create session handler\n    const [backend, optionsWithValidatedEPs] = await resolveBackendAndExecutionProviders(options);\n    const handler = await backend.createInferenceSessionHandler(filePathOrUint8Array, optionsWithValidatedEPs);\n    TRACE_FUNC_END();\n    return new InferenceSession(handler);\n  }\n\n  startProfiling(): void {\n    this.handler.startProfiling();\n  }\n  endProfiling(): void {\n    this.handler.endProfiling();\n  }\n\n  get inputNames(): readonly string[] {\n    return this.handler.inputNames;\n  }\n  get outputNames(): readonly string[] {\n    return this.handler.outputNames;\n  }\n\n  private handler: InferenceSessionHandler;\n}\n","// Copyright (c) Microsoft Corporation. All rights reserved.\n// Licensed under the MIT License.\n\nimport {InferenceSession as InferenceSessionImpl} from './inference-session-impl.js';\nimport {OnnxModelOptions} from './onnx-model.js';\nimport {OnnxValue, OnnxValueDataLocation} from './onnx-value.js';\n\n/* eslint-disable @typescript-eslint/no-redeclare */\n\nexport declare namespace InferenceSession {\n  // #region input/output types\n\n  type OnnxValueMapType = {readonly [name: string]: OnnxValue};\n  type NullableOnnxValueMapType = {readonly [name: string]: OnnxValue | null};\n\n  /**\n   * A feeds (model inputs) is an object that uses input names as keys and OnnxValue as corresponding values.\n   */\n  type FeedsType = OnnxValueMapType;\n\n  /**\n   * A fetches (model outputs) could be one of the following:\n   *\n   * - Omitted. Use model's output names definition.\n   * - An array of string indicating the output names.\n   * - An object that use output names as keys and OnnxValue or null as corresponding values.\n   *\n   * @remark\n   * different from input argument, in output, OnnxValue is optional. If an OnnxValue is present it will be\n   * used as a pre-allocated value by the inference engine; if omitted, inference engine will allocate buffer\n   * internally.\n   */\n  type FetchesType = readonly string[]|NullableOnnxValueMapType;\n\n  /**\n   * A inferencing return type is an object that uses output names as keys and OnnxValue as corresponding values.\n   */\n  type ReturnType = OnnxValueMapType;\n\n  // #endregion\n\n  // #region session options\n\n  /**\n   * A set of configurations for session behavior.\n   */\n  export interface SessionOptions extends OnnxModelOptions {\n    /**\n     * An array of execution provider options.\n     *\n     * An execution provider option can be a string indicating the name of the execution provider,\n     * or an object of corresponding type.\n     */\n    executionProviders?: readonly ExecutionProviderConfig[];\n\n    /**\n     * The intra OP threads number.\n     *\n     * This setting is available only in ONNXRuntime (Node.js binding and react-native).\n     */\n    intraOpNumThreads?: number;\n\n    /**\n     * The inter OP threads number.\n     *\n     * This setting is available only in ONNXRuntime (Node.js binding and react-native).\n     */\n    interOpNumThreads?: number;\n\n    /**\n     * The free dimension override.\n     *\n     * This setting is available only in ONNXRuntime (Node.js binding and react-native) or WebAssembly backend\n     */\n    freeDimensionOverrides?: {readonly [dimensionName: string]: number};\n\n    /**\n     * The optimization level.\n     *\n     * This setting is available only in ONNXRuntime (Node.js binding and react-native) or WebAssembly backend\n     */\n    graphOptimizationLevel?: 'disabled'|'basic'|'extended'|'all';\n\n    /**\n     * Whether enable CPU memory arena.\n     *\n     * This setting is available only in ONNXRuntime (Node.js binding and react-native) or WebAssembly backend\n     */\n    enableCpuMemArena?: boolean;\n\n    /**\n     * Whether enable memory pattern.\n     *\n     * This setting is available only in ONNXRuntime (Node.js binding and react-native) or WebAssembly backend\n     */\n    enableMemPattern?: boolean;\n\n    /**\n     * Execution mode.\n     *\n     * This setting is available only in ONNXRuntime (Node.js binding and react-native) or WebAssembly backend\n     */\n    executionMode?: 'sequential'|'parallel';\n\n    /**\n     * Optimized model file path.\n     *\n     * If this setting is specified, the optimized model will be dumped. In browser, a blob will be created\n     * with a pop-up window.\n     */\n    optimizedModelFilePath?: string;\n\n    /**\n     * Whether enable profiling.\n     *\n     * This setting is a placeholder for a future use.\n     */\n    enableProfiling?: boolean;\n\n    /**\n     * File prefix for profiling.\n     *\n     * This setting is a placeholder for a future use.\n     */\n    profileFilePrefix?: string;\n\n    /**\n     * Log ID.\n     *\n     * This setting is available only in ONNXRuntime (Node.js binding and react-native) or WebAssembly backend\n     */\n    logId?: string;\n\n    /**\n     * Log severity level. See\n     * https://github.com/microsoft/onnxruntime/blob/main/include/onnxruntime/core/common/logging/severity.h\n     *\n     * This setting is available only in ONNXRuntime (Node.js binding and react-native) or WebAssembly backend\n     */\n    logSeverityLevel?: 0|1|2|3|4;\n\n    /**\n     * Log verbosity level.\n     *\n     * This setting is available only in WebAssembly backend. Will support Node.js binding and react-native later\n     */\n    logVerbosityLevel?: number;\n\n    /**\n     * Specify string as a preferred data location for all outputs, or an object that use output names as keys and a\n     * preferred data location as corresponding values.\n     *\n     * This setting is available only in ONNXRuntime Web for WebGL and WebGPU EP.\n     */\n    preferredOutputLocation?: OnnxValueDataLocation|{readonly [outputName: string]: OnnxValueDataLocation};\n\n    /**\n     * Whether enable graph capture.\n     * This setting is available only in ONNXRuntime Web for WebGPU EP.\n     */\n    enableGraphCapture?: boolean;\n\n    /**\n     * Store configurations for a session. See\n     * https://github.com/microsoft/onnxruntime/blob/main/include/onnxruntime/core/session/\n     * onnxruntime_session_options_config_keys.h\n     *\n     * This setting is available only in WebAssembly backend. Will support Node.js binding and react-native later\n     *\n     * @example\n     * ```js\n     * extra: {\n     *   session: {\n     *     set_denormal_as_zero: \"1\",\n     *     disable_prepacking: \"1\"\n     *   },\n     *   optimization: {\n     *     enable_gelu_approximation: \"1\"\n     *   }\n     * }\n     * ```\n     */\n    extra?: Record<string, unknown>;\n  }\n\n  // #region execution providers\n\n  // Currently, we have the following backends to support execution providers:\n  // Backend Node.js binding: supports 'cpu', 'dml' (win32), 'coreml' (macOS) and 'cuda' (linux).\n  // Backend WebAssembly: supports 'cpu', 'wasm', 'webgpu' and 'webnn'.\n  // Backend ONNX.js: supports 'webgl'.\n  // Backend React Native: supports 'cpu', 'xnnpack', 'coreml' (iOS), 'nnapi' (Android).\n  interface ExecutionProviderOptionMap {\n    coreml: CoreMLExecutionProviderOption;\n    cpu: CpuExecutionProviderOption;\n    cuda: CudaExecutionProviderOption;\n    dml: DmlExecutionProviderOption;\n    nnapi: NnapiExecutionProviderOption;\n    tensorrt: TensorRtExecutionProviderOption;\n    wasm: WebAssemblyExecutionProviderOption;\n    webgl: WebGLExecutionProviderOption;\n    webgpu: WebGpuExecutionProviderOption;\n    webnn: WebNNExecutionProviderOption;\n    qnn: QnnExecutionProviderOption;\n    xnnpack: XnnpackExecutionProviderOption;\n  }\n\n  type ExecutionProviderName = keyof ExecutionProviderOptionMap;\n  type ExecutionProviderConfig =\n      ExecutionProviderOptionMap[ExecutionProviderName]|ExecutionProviderOption|ExecutionProviderName|string;\n\n  export interface ExecutionProviderOption {\n    readonly name: string;\n  }\n  export interface CpuExecutionProviderOption extends ExecutionProviderOption {\n    readonly name: 'cpu';\n    useArena?: boolean;\n  }\n  export interface CudaExecutionProviderOption extends ExecutionProviderOption {\n    readonly name: 'cuda';\n    deviceId?: number;\n  }\n  export interface DmlExecutionProviderOption extends ExecutionProviderOption {\n    readonly name: 'dml';\n    deviceId?: number;\n  }\n  export interface TensorRtExecutionProviderOption extends ExecutionProviderOption {\n    readonly name: 'tensorrt';\n    deviceId?: number;\n  }\n  export interface WebAssemblyExecutionProviderOption extends ExecutionProviderOption {\n    readonly name: 'wasm';\n  }\n  export interface WebGLExecutionProviderOption extends ExecutionProviderOption {\n    readonly name: 'webgl';\n    // TODO: add flags\n  }\n  export interface XnnpackExecutionProviderOption extends ExecutionProviderOption {\n    readonly name: 'xnnpack';\n  }\n  export interface WebGpuExecutionProviderOption extends ExecutionProviderOption {\n    readonly name: 'webgpu';\n    preferredLayout?: 'NCHW'|'NHWC';\n  }\n\n  // #region WebNN options\n\n  interface WebNNExecutionProviderName extends ExecutionProviderOption {\n    readonly name: 'webnn';\n  }\n\n  /**\n   * Represents a set of options for creating a WebNN MLContext.\n   *\n   * @see https://www.w3.org/TR/webnn/#dictdef-mlcontextoptions\n   */\n  export interface WebNNContextOptions {\n    deviceType?: 'cpu'|'gpu'|'npu';\n    numThreads?: number;\n    powerPreference?: 'default'|'low-power'|'high-performance';\n  }\n\n  /**\n   * Represents a set of options for WebNN execution provider without MLContext.\n   */\n  export interface WebNNOptionsWithoutMLContext extends WebNNExecutionProviderName, WebNNContextOptions {\n    context?: never;\n  }\n\n  /**\n   * Represents a set of options for WebNN execution provider with MLContext.\n   *\n   * When MLContext is provided, the deviceType is also required so that the WebNN EP can determine the preferred\n   * channel layout.\n   *\n   * @see https://www.w3.org/TR/webnn/#dom-ml-createcontext\n   */\n  export interface WebNNOptionsWithMLContext extends WebNNExecutionProviderName,\n                                                     Omit<WebNNContextOptions, 'deviceType'>,\n                                                     Required<Pick<WebNNContextOptions, 'deviceType'>> {\n    context: unknown /* MLContext */;\n  }\n\n  /**\n   * Represents a set of options for WebNN execution provider with MLContext which is created from GPUDevice.\n   *\n   * @see https://www.w3.org/TR/webnn/#dom-ml-createcontext-gpudevice\n   */\n  export interface WebNNOptionsWebGpu extends WebNNExecutionProviderName {\n    context: unknown /* MLContext */;\n    gpuDevice: unknown /* GPUDevice */;\n  }\n\n  /**\n   * Options for WebNN execution provider.\n   */\n  export type WebNNExecutionProviderOption = WebNNOptionsWithoutMLContext|WebNNOptionsWithMLContext|WebNNOptionsWebGpu;\n\n  // #endregion\n\n  export interface QnnExecutionProviderOption extends ExecutionProviderOption {\n    readonly name: 'qnn';\n    // TODO add flags\n  }\n  export interface CoreMLExecutionProviderOption extends ExecutionProviderOption {\n    readonly name: 'coreml';\n    /**\n     * The bit flags for CoreML execution provider.\n     *\n     * ```\n     * COREML_FLAG_USE_CPU_ONLY = 0x001\n     * COREML_FLAG_ENABLE_ON_SUBGRAPH = 0x002\n     * COREML_FLAG_ONLY_ENABLE_DEVICE_WITH_ANE = 0x004\n     * COREML_FLAG_ONLY_ALLOW_STATIC_INPUT_SHAPES = 0x008\n     * COREML_FLAG_CREATE_MLPROGRAM = 0x010\n     * ```\n     *\n     * See include/onnxruntime/core/providers/coreml/coreml_provider_factory.h for more details.\n     *\n     * This flag is available only in ONNXRuntime (Node.js binding).\n     */\n    coreMlFlags?: number;\n    /**\n     * Specify whether to use CPU only in CoreML EP.\n     *\n     * This setting is available only in ONNXRuntime (react-native).\n     */\n    useCPUOnly?: boolean;\n    /**\n     * Specify whether to enable CoreML EP on subgraph.\n     *\n     * This setting is available only in ONNXRuntime (react-native).\n     */\n    enableOnSubgraph?: boolean;\n    /**\n     * Specify whether to only enable CoreML EP for Apple devices with ANE (Apple Neural Engine).\n     *\n     * This setting is available only in ONNXRuntime (react-native).\n     */\n    onlyEnableDeviceWithANE?: boolean;\n  }\n  export interface NnapiExecutionProviderOption extends ExecutionProviderOption {\n    readonly name: 'nnapi';\n    useFP16?: boolean;\n    useNCHW?: boolean;\n    cpuDisabled?: boolean;\n    cpuOnly?: boolean;\n  }\n  // #endregion\n\n  // #endregion\n\n  // #region run options\n\n  /**\n   * A set of configurations for inference run behavior\n   */\n  export interface RunOptions {\n    /**\n     * Log severity level. See\n     * https://github.com/microsoft/onnxruntime/blob/main/include/onnxruntime/core/common/logging/severity.h\n     *\n     * This setting is available only in ONNXRuntime (Node.js binding and react-native) or WebAssembly backend\n     */\n    logSeverityLevel?: 0|1|2|3|4;\n\n    /**\n     * Log verbosity level.\n     *\n     * This setting is available only in WebAssembly backend. Will support Node.js binding and react-native later\n     */\n    logVerbosityLevel?: number;\n\n    /**\n     * Terminate all incomplete OrtRun calls as soon as possible if true\n     *\n     * This setting is available only in WebAssembly backend. Will support Node.js binding and react-native later\n     */\n    terminate?: boolean;\n\n    /**\n     * A tag for the Run() calls using this\n     *\n     * This setting is available only in ONNXRuntime (Node.js binding and react-native) or WebAssembly backend\n     */\n    tag?: string;\n\n    /**\n     * Set a single run configuration entry. See\n     * https://github.com/microsoft/onnxruntime/blob/main/include/onnxruntime/core/session/\n     * onnxruntime_run_options_config_keys.h\n     *\n     * This setting is available only in WebAssembly backend. Will support Node.js binding and react-native later\n     *\n     * @example\n     *\n     * ```js\n     * extra: {\n     *   memory: {\n     *     enable_memory_arena_shrinkage: \"1\",\n     *   }\n     * }\n     * ```\n     */\n    extra?: Record<string, unknown>;\n  }\n\n  // #endregion\n\n  // #region value metadata\n\n  // eslint-disable-next-line @typescript-eslint/no-empty-interface\n  interface ValueMetadata {\n    // TBD\n  }\n\n  // #endregion\n}\n\n/**\n * Represent a runtime instance of an ONNX model.\n */\nexport interface InferenceSession {\n  // #region run()\n\n  /**\n   * Execute the model asynchronously with the given feeds and options.\n   *\n   * @param feeds - Representation of the model input. See type description of `InferenceSession.InputType` for detail.\n   * @param options - Optional. A set of options that controls the behavior of model inference.\n   * @returns A promise that resolves to a map, which uses output names as keys and OnnxValue as corresponding values.\n   */\n  run(feeds: InferenceSession.FeedsType, options?: InferenceSession.RunOptions): Promise<InferenceSession.ReturnType>;\n\n  /**\n   * Execute the model asynchronously with the given feeds, fetches and options.\n   *\n   * @param feeds - Representation of the model input. See type description of `InferenceSession.InputType` for detail.\n   * @param fetches - Representation of the model output. See type description of `InferenceSession.OutputType` for\n   * detail.\n   * @param options - Optional. A set of options that controls the behavior of model inference.\n   * @returns A promise that resolves to a map, which uses output names as keys and OnnxValue as corresponding values.\n   */\n  run(feeds: InferenceSession.FeedsType, fetches: InferenceSession.FetchesType,\n      options?: InferenceSession.RunOptions): Promise<InferenceSession.ReturnType>;\n\n  // #endregion\n\n  // #region release()\n\n  /**\n   * Release the inference session and the underlying resources.\n   */\n  release(): Promise<void>;\n\n  // #endregion\n\n  // #region profiling\n\n  /**\n   * Start profiling.\n   */\n  startProfiling(): void;\n\n  /**\n   * End profiling.\n   */\n  endProfiling(): void;\n\n  // #endregion\n\n  // #region metadata\n\n  /**\n   * Get input names of the loaded model.\n   */\n  readonly inputNames: readonly string[];\n\n  /**\n   * Get output names of the loaded model.\n   */\n  readonly outputNames: readonly string[];\n\n  // /**\n  //  * Get input metadata of the loaded model.\n  //  */\n  // readonly inputMetadata: ReadonlyArray<Readonly<InferenceSession.ValueMetadata>>;\n\n  // /**\n  //  * Get output metadata of the loaded model.\n  //  */\n  // readonly outputMetadata: ReadonlyArray<Readonly<InferenceSession.ValueMetadata>>;\n\n  // #endregion\n}\n\nexport interface InferenceSessionFactory {\n  // #region create()\n\n  /**\n   * Create a new inference session and load model asynchronously from an ONNX model file.\n   *\n   * @param uri - The URI or file path of the model to load.\n   * @param options - specify configuration for creating a new inference session.\n   * @returns A promise that resolves to an InferenceSession object.\n   */\n  create(uri: string, options?: InferenceSession.SessionOptions): Promise<InferenceSession>;\n\n  /**\n   * Create a new inference session and load model asynchronously from an array bufer.\n   *\n   * @param buffer - An ArrayBuffer representation of an ONNX model.\n   * @param options - specify configuration for creating a new inference session.\n   * @returns A promise that resolves to an InferenceSession object.\n   */\n  create(buffer: ArrayBufferLike, options?: InferenceSession.SessionOptions): Promise<InferenceSession>;\n\n  /**\n   * Create a new inference session and load model asynchronously from segment of an array bufer.\n   *\n   * @param buffer - An ArrayBuffer representation of an ONNX model.\n   * @param byteOffset - The beginning of the specified portion of the array buffer.\n   * @param byteLength - The length in bytes of the array buffer.\n   * @param options - specify configuration for creating a new inference session.\n   * @returns A promise that resolves to an InferenceSession object.\n   */\n  create(buffer: ArrayBufferLike, byteOffset: number, byteLength?: number, options?: InferenceSession.SessionOptions):\n      Promise<InferenceSession>;\n\n  /**\n   * Create a new inference session and load model asynchronously from a Uint8Array.\n   *\n   * @param buffer - A Uint8Array representation of an ONNX model.\n   * @param options - specify configuration for creating a new inference session.\n   * @returns A promise that resolves to an InferenceSession object.\n   */\n  create(buffer: Uint8Array, options?: InferenceSession.SessionOptions): Promise<InferenceSession>;\n\n  // #endregion\n}\n\n// eslint-disable-next-line @typescript-eslint/naming-convention\nexport const InferenceSession: InferenceSessionFactory = InferenceSessionImpl;\n","// Copyright (c) Microsoft Corporation. All rights reserved.\n// Licensed under the MIT License.\n\nimport {OptionsFormat, OptionsNormalizationParameters, OptionsTensorLayout} from './tensor-factory.js';\n\nexport interface TensorToDataUrlOptions extends OptionsTensorLayout, OptionsFormat, OptionsNormalizationParameters {}\n\nexport interface TensorToImageDataOptions extends OptionsTensorLayout, OptionsFormat, OptionsNormalizationParameters {}\n\nexport interface ConversionUtils {\n  /**\n   * creates a DataURL instance from tensor\n   *\n   * @param options - An optional object representing options for creating a DataURL instance from the tensor.\n   *\n   * The following default settings will be applied:\n   * - `format`: `'RGB'`\n   * - `tensorLayout`: `'NCHW'`\n   * @returns a DataURL string representing the image converted from tensor data\n   */\n  toDataURL(options?: TensorToDataUrlOptions): string;\n\n  /**\n   * creates an ImageData instance from tensor\n   *\n   * @param options - An optional object representing options for creating an ImageData instance from the tensor.\n   *\n   * The following default settings will be applied:\n   * - `format`: `'RGB'`\n   * - `tensorLayout`: `'NCHW'`\n   * @returns an ImageData instance representing the image converted from tensor data\n   */\n  toImageData(options?: TensorToImageDataOptions): ImageData;\n}\n","// Copyright (c) Microsoft Corporation. All rights reserved.\n// Licensed under the MIT License.\n\nimport {Tensor, TypedTensor} from './tensor.js';\n\nexport type ImageFormat = 'RGB'|'RGBA'|'BGR'|'RBG';\nexport type ImageTensorLayout = 'NHWC'|'NCHW';\n\n// the following region contains type definitions for constructing tensor from a specific location.\n\n// #region types for constructing a tensor from a specific location\n\n/**\n * represent common properties of the parameter for constructing a tensor from a specific location.\n */\ninterface CommonConstructorParameters<T> extends Pick<Tensor, 'dims'> {\n  /**\n   * Specify the data type of the tensor.\n   */\n  readonly type: T;\n}\n\n/**\n * represent the parameter for constructing a tensor from a GPU resource.\n */\ninterface GpuResourceConstructorParameters<T extends Tensor.Type> {\n  /**\n   * an optional callback function to download data from GPU to CPU.\n   *\n   * If not provided, the tensor treat the GPU data as external resource.\n   */\n  download?(): Promise<Tensor.DataTypeMap[T]>;\n\n  /**\n   * an optional callback function that will be called when the tensor is disposed.\n   *\n   * If not provided, the tensor treat the GPU data as external resource.\n   */\n  dispose?(): void;\n}\n\n/**\n * represent the parameter for constructing a tensor from a pinned CPU buffer\n */\nexport interface CpuPinnedConstructorParameters<T extends Tensor.CpuPinnedDataTypes = Tensor.CpuPinnedDataTypes> extends\n    CommonConstructorParameters<T> {\n  /**\n   * Specify the location of the data to be 'cpu-pinned'.\n   */\n  readonly location: 'cpu-pinned';\n  /**\n   * Specify the CPU pinned buffer that holds the tensor data.\n   */\n  readonly data: Tensor.DataTypeMap[T];\n}\n\n/**\n * represent the parameter for constructing a tensor from a WebGL texture\n */\nexport interface TextureConstructorParameters<T extends Tensor.TextureDataTypes = Tensor.TextureDataTypes> extends\n    CommonConstructorParameters<T>, GpuResourceConstructorParameters<T> {\n  /**\n   * Specify the location of the data to be 'texture'.\n   */\n  readonly location: 'texture';\n  /**\n   * Specify the WebGL texture that holds the tensor data.\n   */\n  readonly texture: Tensor.TextureType;\n}\n\n/**\n * represent the parameter for constructing a tensor from a WebGPU buffer\n */\nexport interface GpuBufferConstructorParameters<T extends Tensor.GpuBufferDataTypes = Tensor.GpuBufferDataTypes> extends\n    CommonConstructorParameters<T>, GpuResourceConstructorParameters<T> {\n  /**\n   * Specify the location of the data to be 'gpu-buffer'.\n   */\n  readonly location: 'gpu-buffer';\n  /**\n   * Specify the WebGPU buffer that holds the tensor data.\n   */\n  readonly gpuBuffer: Tensor.GpuBufferType;\n}\n\n// #endregion\n\n// the following region contains type definitions of each individual options.\n// the tensor factory functions use a composition of those options as the parameter type.\n\n// #region Options fields\n\nexport interface OptionsFormat {\n  /**\n   * Describes the image format represented in RGBA color space.\n   */\n  format?: ImageFormat;\n}\n\nexport interface OptionsTensorFormat {\n  /**\n   * Describes the image format of the tensor.\n   *\n   * NOTE: this is different from option 'format'. While option 'format' represents the original image, 'tensorFormat'\n   * represents the target format of the tensor. A transpose will be performed if they are different.\n   */\n  tensorFormat?: ImageFormat;\n}\n\nexport interface OptionsTensorDataType {\n  /**\n   * Describes the data type of the tensor.\n   */\n  dataType?: 'float32'|'uint8';\n}\n\nexport interface OptionsTensorLayout {\n  /**\n   * Describes the tensor layout when representing data of one or more image(s).\n   */\n  tensorLayout?: ImageTensorLayout;\n}\n\nexport interface OptionsDimensions {\n  /**\n   * Describes the image height in pixel\n   */\n  height?: number;\n  /**\n   * Describes the image width in pixel\n   */\n  width?: number;\n}\n\nexport interface OptionResizedDimensions {\n  /**\n   * Describes the resized height. If omitted, original height will be used.\n   */\n  resizedHeight?: number;\n  /**\n   * Describes resized width - can be accessed via tensor dimensions as well\n   */\n  resizedWidth?: number;\n}\n\nexport interface OptionsNormalizationParameters {\n  /**\n   * Describes normalization parameters when preprocessing the image as model input.\n   *\n   * Data element are ranged from 0 to 255.\n   */\n  norm?: {\n    /**\n     * The 'bias' value for image normalization.\n     * - If omitted, use default value 0.\n     * - If it's a single number, apply to each channel\n     * - If it's an array of 3 or 4 numbers, apply element-wise. Number of elements need to match the number of channels\n     * for the corresponding image format\n     */\n    bias?: number|[number, number, number]|[number, number, number, number];\n    /**\n     * The 'mean' value for image normalization.\n     * - If omitted, use default value 255.\n     * - If it's a single number, apply to each channel\n     * - If it's an array of 3 or 4 numbers, apply element-wise. Number of elements need to match the number of channels\n     * for the corresponding image format\n     */\n    mean?: number | [number, number, number] | [number, number, number, number];\n  };\n}\n\n// #endregion\n\n// #region Options composition\n\nexport interface TensorFromImageDataOptions extends OptionResizedDimensions, OptionsTensorFormat, OptionsTensorLayout,\n                                                    OptionsTensorDataType, OptionsNormalizationParameters {}\n\nexport interface TensorFromImageElementOptions extends OptionResizedDimensions, OptionsTensorFormat,\n                                                       OptionsTensorLayout, OptionsTensorDataType,\n                                                       OptionsNormalizationParameters {}\n\nexport interface TensorFromUrlOptions extends OptionsDimensions, OptionResizedDimensions, OptionsTensorFormat,\n                                              OptionsTensorLayout, OptionsTensorDataType,\n                                              OptionsNormalizationParameters {}\n\nexport interface TensorFromImageBitmapOptions extends OptionResizedDimensions, OptionsTensorFormat, OptionsTensorLayout,\n                                                      OptionsTensorDataType, OptionsNormalizationParameters {}\n\nexport interface TensorFromTextureOptions<T extends Tensor.TextureDataTypes> extends\n    Required<OptionsDimensions>, OptionsFormat, GpuResourceConstructorParameters<T>/* TODO: add more */ {}\n\nexport interface TensorFromGpuBufferOptions<T extends Tensor.GpuBufferDataTypes> extends\n    Pick<Tensor, 'dims'>, GpuResourceConstructorParameters<T> {\n  /**\n   * Describes the data type of the tensor.\n   */\n  dataType?: T;\n}\n\n// #endregion\n\n/**\n * type TensorFactory defines the factory functions of 'Tensor' to create tensor instances from existing data or\n * resources.\n */\nexport interface TensorFactory {\n  /**\n   * create a tensor from an ImageData object\n   *\n   * @param imageData - the ImageData object to create tensor from\n   * @param options - An optional object representing options for creating tensor from ImageData.\n   *\n   * The following default settings will be applied:\n   * - `tensorFormat`: `'RGB'`\n   * - `tensorLayout`: `'NCHW'`\n   * - `dataType`: `'float32'`\n   * @returns A promise that resolves to a tensor object\n   */\n  fromImage(imageData: ImageData, options?: TensorFromImageDataOptions):\n      Promise<TypedTensor<'float32'>|TypedTensor<'uint8'>>;\n\n  /**\n   * create a tensor from a HTMLImageElement object\n   *\n   * @param imageElement - the HTMLImageElement object to create tensor from\n   * @param options - An optional object representing options for creating tensor from HTMLImageElement.\n   *\n   * The following default settings will be applied:\n   * - `tensorFormat`: `'RGB'`\n   * - `tensorLayout`: `'NCHW'`\n   * - `dataType`: `'float32'`\n   * @returns A promise that resolves to a tensor object\n   */\n  fromImage(imageElement: HTMLImageElement, options?: TensorFromImageElementOptions):\n      Promise<TypedTensor<'float32'>|TypedTensor<'uint8'>>;\n\n  /**\n   * create a tensor from URL\n   *\n   * @param urlSource - a string as a URL to the image or a data URL containing the image data.\n   * @param options - An optional object representing options for creating tensor from URL.\n   *\n   * The following default settings will be applied:\n   * - `tensorFormat`: `'RGB'`\n   * - `tensorLayout`: `'NCHW'`\n   * - `dataType`: `'float32'`\n   * @returns A promise that resolves to a tensor object\n   */\n  fromImage(urlSource: string, options?: TensorFromUrlOptions): Promise<TypedTensor<'float32'>|TypedTensor<'uint8'>>;\n\n  /**\n   * create a tensor from an ImageBitmap object\n   *\n   * @param bitmap - the ImageBitmap object to create tensor from\n   * @param options - An optional object representing options for creating tensor from URL.\n   *\n   * The following default settings will be applied:\n   * - `tensorFormat`: `'RGB'`\n   * - `tensorLayout`: `'NCHW'`\n   * - `dataType`: `'float32'`\n   * @returns A promise that resolves to a tensor object\n   */\n  fromImage(bitmap: ImageBitmap, options: TensorFromImageBitmapOptions):\n      Promise<TypedTensor<'float32'>|TypedTensor<'uint8'>>;\n\n  /**\n   * create a tensor from a WebGL texture\n   *\n   * @param texture - the WebGLTexture object to create tensor from\n   * @param options - An optional object representing options for creating tensor from WebGL texture.\n   *\n   * The options include following properties:\n   * - `width`: the width of the texture. Required.\n   * - `height`: the height of the texture. Required.\n   * - `format`: the format of the texture. If omitted, assume 'RGBA'.\n   * - `download`: an optional function to download the tensor data from GPU to CPU. If omitted, the GPU data\n   * will not be able to download. Usually, this is provided by a GPU backend for the inference outputs. Users don't\n   * need to provide this function.\n   * - `dispose`: an optional function to dispose the tensor data on GPU. If omitted, the GPU data will not be disposed.\n   * Usually, this is provided by a GPU backend for the inference outputs. Users don't need to provide this function.\n   *\n   * @returns a tensor object\n   */\n  fromTexture<T extends Tensor.TextureDataTypes = 'float32'>(\n      texture: Tensor.TextureType, options: TensorFromTextureOptions<T>): TypedTensor<'float32'>;\n\n  /**\n   * create a tensor from a WebGPU buffer\n   *\n   * @param buffer - the GPUBuffer object to create tensor from\n   * @param options - An optional object representing options for creating tensor from WebGPU buffer.\n   *\n   * The options include following properties:\n   * - `dataType`: the data type of the tensor. If omitted, assume 'float32'.\n   * - `dims`: the dimension of the tensor. Required.\n   * - `download`: an optional function to download the tensor data from GPU to CPU. If omitted, the GPU data\n   * will not be able to download. Usually, this is provided by a GPU backend for the inference outputs. Users don't\n   * need to provide this function.\n   * - `dispose`: an optional function to dispose the tensor data on GPU. If omitted, the GPU data will not be disposed.\n   * Usually, this is provided by a GPU backend for the inference outputs. Users don't need to provide this function.\n   *\n   * @returns a tensor object\n   */\n  fromGpuBuffer<T extends Tensor.GpuBufferDataTypes>(\n      buffer: Tensor.GpuBufferType, options: TensorFromGpuBufferOptions<T>): TypedTensor<T>;\n\n  /**\n   * create a tensor from a pre-allocated buffer. The buffer will be used as a pinned buffer.\n   *\n   * @param type - the tensor element type.\n   * @param buffer - a TypedArray corresponding to the type.\n   * @param dims - specify the dimension of the tensor. If omitted, a 1-D tensor is assumed.\n   *\n   * @returns a tensor object\n   */\n  fromPinnedBuffer<T extends Exclude<Tensor.Type, 'string'>>(\n      type: T, buffer: Tensor.DataTypeMap[T], dims?: readonly number[]): TypedTensor<T>;\n}\n","// Copyright (c) Microsoft Corporation. All rights reserved.\n// Licensed under the MIT License.\n\n/**\n * A string that represents a file's URL or path.\n *\n * Path is vailable only in onnxruntime-node or onnxruntime-web running in Node.js.\n */\nexport type FileUrlOrPath = string;\n\n/**\n * A Blob object that represents a file.\n */\nexport type FileBlob = Blob;\n\n/**\n * A Uint8Array, ArrayBuffer or SharedArrayBuffer object that represents a file content.\n *\n * When it is an ArrayBuffer or SharedArrayBuffer, the whole buffer is assumed to be the file content.\n */\nexport type FileData = Uint8Array|ArrayBufferLike;\n\n/**\n * Represents a file that can be loaded by the ONNX Runtime JavaScript API.\n */\nexport type FileType = FileUrlOrPath|FileBlob|FileData;\n\n/**\n * Represents an external data file.\n */\nexport interface ExternalDataFileDescription {\n  /**\n   * Specify the external data file.\n   */\n  data: FileType;\n  /**\n   * Specify the file path.\n   */\n  path: string;\n}\n\n/**\n * Represents an external data file.\n *\n * When using a string, it should be a file URL or path that in the same directory as the model file.\n */\nexport type ExternalDataFileType = ExternalDataFileDescription|FileUrlOrPath;\n\n/**\n * Options for model loading.\n */\nexport interface OnnxModelOptions {\n  /**\n   * Specifying a list of files that represents the external data.\n   */\n  externalData?: readonly ExternalDataFileType[];\n}\n","// Copyright (c) Microsoft Corporation. All rights reserved.\n// Licensed under the MIT License.\n\nimport {Tensor} from './tensor.js';\n\nexport type NonTensorType = never;\n\n/**\n * Type OnnxValue Represents both tensors and non-tensors value for model's inputs/outputs.\n *\n * NOTE: currently not support non-tensor\n */\nexport type OnnxValue = Tensor|NonTensorType;\n\n/**\n * Type OnnxValueDataLocation represents the location of the data of an OnnxValue.\n */\nexport type OnnxValueDataLocation = Tensor.DataLocation;\n","// Copyright (c) Microsoft Corporation. All rights reserved.\n// Licensed under the MIT License.\n\nimport {resolveBackendAndExecutionProviders} from './backend-impl.js';\nimport {SessionHandler, TrainingSessionHandler} from './backend.js';\nimport {InferenceSession as InferenceSession} from './inference-session.js';\nimport {OnnxValue} from './onnx-value.js';\nimport {Tensor} from './tensor.js';\nimport {TrainingSession as TrainingSessionInterface, TrainingSessionCreateOptions} from './training-session.js';\n\ntype SessionOptions = InferenceSession.SessionOptions;\ntype FeedsType = InferenceSession.FeedsType;\ntype FetchesType = InferenceSession.FetchesType;\ntype ReturnType = InferenceSession.ReturnType;\ntype RunOptions = InferenceSession.RunOptions;\n\nconst noBackendErrMsg: string = 'Training backend could not be resolved. ' +\n    'Make sure you\\'re using the correct configuration & WebAssembly files.';\n\nexport class TrainingSession implements TrainingSessionInterface {\n  private constructor(handler: TrainingSessionHandler, hasOptimizerModel: boolean, hasEvalModel: boolean) {\n    this.handler = handler;\n    this.hasOptimizerModel = hasOptimizerModel;\n    this.hasEvalModel = hasEvalModel;\n  }\n  private handler: TrainingSessionHandler;\n  private hasOptimizerModel: boolean;\n  private hasEvalModel: boolean;\n\n  get trainingInputNames(): readonly string[] {\n    return this.handler.inputNames;\n  }\n  get trainingOutputNames(): readonly string[] {\n    return this.handler.outputNames;\n  }\n\n  get evalInputNames(): readonly string[] {\n    if (this.hasEvalModel) {\n      return this.handler.evalInputNames;\n    } else {\n      throw new Error('This training session has no evalModel loaded.');\n    }\n  }\n  get evalOutputNames(): readonly string[] {\n    if (this.hasEvalModel) {\n      return this.handler.evalOutputNames;\n    } else {\n      throw new Error('This training session has no evalModel loaded.');\n    }\n  }\n\n  static async create(trainingOptions: TrainingSessionCreateOptions, sessionOptions?: SessionOptions):\n      Promise<TrainingSession> {\n    const evalModel: string|Uint8Array = trainingOptions.evalModel || '';\n    const optimizerModel: string|Uint8Array = trainingOptions.optimizerModel || '';\n    const options: SessionOptions = sessionOptions || {};\n\n    // resolve backend, update session options with validated EPs, and create session handler\n    const [backend, optionsWithValidatedEPs] = await resolveBackendAndExecutionProviders(options);\n    if (backend.createTrainingSessionHandler) {\n      const handler = await backend.createTrainingSessionHandler(\n          trainingOptions.checkpointState, trainingOptions.trainModel, evalModel, optimizerModel,\n          optionsWithValidatedEPs);\n      return new TrainingSession(handler, !!trainingOptions.optimizerModel, !!trainingOptions.evalModel);\n    } else {\n      throw new Error(noBackendErrMsg);\n    }\n  }\n\n  /**\n   * Helper function for runTrainStep and future runStep methods that handles the type-narrowing conversion from\n   * the given parameters to SessionHandler.FetchesType and RunOptions.\n   *\n   * @param inputNames the feeds object is checked that they contain all input names in the provided list of input\n   * names.\n   * @param outputNames the fetches object is checked that their keys match up with valid names in the list of output\n   * names.\n   * @param feeds the required input\n   * @param arg1 narrowed & converted into the SessionHandler.FetchesType or RunOptions object\n   * @param arg2 optional RunOptions object.\n   * @returns\n   */\n  typeNarrowingForRunStep(\n      inputNames: readonly string[], outputNames: readonly string[], feeds: FeedsType, arg1?: FetchesType|RunOptions,\n      arg2?: RunOptions): [SessionHandler.FetchesType, RunOptions] {\n    const fetches: {[name: string]: OnnxValue|null} = {};\n    let options: RunOptions = {};\n    // check inputs\n    if (typeof feeds !== 'object' || feeds === null || feeds instanceof Tensor || Array.isArray(feeds)) {\n      throw new TypeError(\n          '\\'feeds\\' must be an object that use input names as keys and OnnxValue as corresponding values.');\n    }\n\n    let isFetchesEmpty = true;\n    // determine which override is being used\n    if (typeof arg1 === 'object') {\n      if (arg1 === null) {\n        throw new TypeError('Unexpected argument[1]: cannot be null.');\n      }\n      if (arg1 instanceof Tensor) {\n        throw new TypeError('\\'fetches\\' cannot be a Tensor');\n      }\n\n      if (Array.isArray(arg1)) {\n        if (arg1.length === 0) {\n          throw new TypeError('\\'fetches\\' cannot be an empty array.');\n        }\n        isFetchesEmpty = false;\n        // output names\n        for (const name of arg1) {\n          if (typeof name !== 'string') {\n            throw new TypeError('\\'fetches\\' must be a string array or an object.');\n          }\n          if (outputNames.indexOf(name) === -1) {\n            throw new RangeError(`'fetches' contains invalid output name: ${name}.`);\n          }\n          fetches[name] = null;\n        }\n\n        if (typeof arg2 === 'object' && arg2 !== null) {\n          options = arg2;\n        } else if (typeof arg2 !== 'undefined') {\n          throw new TypeError('\\'options\\' must be an object.');\n        }\n      } else {\n        // decide whether arg1 is fetches or options\n        // if any output name is present and its value is valid OnnxValue, we consider it fetches\n        let isFetches = false;\n        const arg1Keys = Object.getOwnPropertyNames(arg1);\n        for (const name of outputNames) {\n          if (arg1Keys.indexOf(name) !== -1) {\n            const v = (arg1 as InferenceSession.NullableOnnxValueMapType)[name];\n            if (v === null || v instanceof Tensor) {\n              isFetches = true;\n              isFetchesEmpty = false;\n              fetches[name] = v;\n            }\n          }\n        }\n\n        if (isFetches) {\n          if (typeof arg2 === 'object' && arg2 !== null) {\n            options = arg2;\n          } else if (typeof arg2 !== 'undefined') {\n            throw new TypeError('\\'options\\' must be an object.');\n          }\n        } else {\n          options = arg1 as RunOptions;\n        }\n      }\n    } else if (typeof arg1 !== 'undefined') {\n      throw new TypeError('Unexpected argument[1]: must be \\'fetches\\' or \\'options\\'.');\n    }\n\n    // check if all inputs are in feed\n    for (const name of inputNames) {\n      if (typeof feeds[name] === 'undefined') {\n        throw new Error(`input '${name}' is missing in 'feeds'.`);\n      }\n    }\n\n    // if no fetches is specified, we use the full output names list\n    if (isFetchesEmpty) {\n      for (const name of outputNames) {\n        fetches[name] = null;\n      }\n    }\n\n    return [fetches, options];\n  }\n\n  /**\n   * Helper method for runTrainStep and any other runStep methods. Takes the ReturnType result from the SessionHandler\n   * and changes it into a map of Tensors.\n   *\n   * @param results\n   * @returns\n   */\n  convertHandlerReturnTypeToMapOfTensors(results: SessionHandler.ReturnType): ReturnType {\n    const returnValue: {[name: string]: OnnxValue} = {};\n    for (const key in results) {\n      if (Object.hasOwnProperty.call(results, key)) {\n        const result = results[key];\n        if (result instanceof Tensor) {\n          returnValue[key] = result;\n        } else {\n          returnValue[key] = new Tensor(result.type, result.data, result.dims);\n        }\n      }\n    }\n    return returnValue;\n  }\n\n  async lazyResetGrad(): Promise<void> {\n    await this.handler.lazyResetGrad();\n  }\n\n  runTrainStep(feeds: FeedsType, options?: RunOptions): Promise<ReturnType>;\n  runTrainStep(feeds: FeedsType, fetches: FetchesType, options?: RunOptions): Promise<ReturnType>;\n  async runTrainStep(feeds: FeedsType, arg1?: FetchesType|RunOptions, arg2?: RunOptions): Promise<ReturnType> {\n    const [fetches, options] =\n        this.typeNarrowingForRunStep(this.trainingInputNames, this.trainingOutputNames, feeds, arg1, arg2);\n    const results = await this.handler.runTrainStep(feeds, fetches, options);\n    return this.convertHandlerReturnTypeToMapOfTensors(results);\n  }\n\n  async runOptimizerStep(options?: InferenceSession.RunOptions|undefined): Promise<void> {\n    if (this.hasOptimizerModel) {\n      await this.handler.runOptimizerStep(options || {});\n    } else {\n      throw new Error('This TrainingSession has no OptimizerModel loaded.');\n    }\n  }\n\n  runEvalStep(feeds: FeedsType, options?: RunOptions|undefined): Promise<ReturnType>;\n  runEvalStep(feeds: FeedsType, fetches: FetchesType, options?: RunOptions|undefined): Promise<ReturnType>;\n  async runEvalStep(feeds: FeedsType, arg1?: FetchesType|RunOptions, arg2?: RunOptions): Promise<ReturnType> {\n    if (this.hasEvalModel) {\n      const [fetches, options] =\n          this.typeNarrowingForRunStep(this.evalInputNames, this.evalOutputNames, feeds, arg1, arg2);\n      const results = await this.handler.runEvalStep(feeds, fetches, options);\n      return this.convertHandlerReturnTypeToMapOfTensors(results);\n    } else {\n      throw new Error('This TrainingSession has no EvalModel loaded.');\n    }\n  }\n\n  async getParametersSize(trainableOnly = true): Promise<number> {\n    return this.handler.getParametersSize(trainableOnly);\n  }\n\n  async loadParametersBuffer(array: Uint8Array, trainableOnly = true): Promise<void> {\n    const paramsSize = await this.getParametersSize(trainableOnly);\n    // checking that the size of the Uint8Array is equivalent to the byte length of a Float32Array of the number\n    // of parameters\n    if (array.length !== 4 * paramsSize) {\n      throw new Error(\n          'Size of the buffer passed into loadParametersBuffer must match the number of parameters in ' +\n          'the model. Please use getParametersSize method to check.');\n    }\n    return this.handler.loadParametersBuffer(array, trainableOnly);\n  }\n\n  async getContiguousParameters(trainableOnly = true): Promise<OnnxValue> {\n    return this.handler.getContiguousParameters(trainableOnly);\n  }\n\n  async release(): Promise<void> {\n    return this.handler.dispose();\n  }\n}\n","// Copyright (c) Microsoft Corporation. All rights reserved.\n// Licensed under the MIT License.\n\nimport {InferenceSession} from './inference-session.js';\nimport {OnnxValue} from './onnx-value.js';\nimport {TrainingSession as TrainingSessionImpl} from './training-session-impl.js';\n\n/* eslint-disable @typescript-eslint/no-redeclare */\n\nexport declare namespace TrainingSession {\n  /**\n   * Either URI file path (string) or Uint8Array containing model or checkpoint information.\n   */\n  type UriOrBuffer = string|Uint8Array;\n}\n\n/**\n * Represent a runtime instance of an ONNX training session,\n * which contains a model that can be trained, and, optionally,\n * an eval and optimizer model.\n */\nexport interface TrainingSession {\n  // #region run()\n\n  /**\n   * Lazily resets the gradients of all trainable parameters to zero. Should happen after the invocation of\n   * runOptimizerStep.\n   */\n  lazyResetGrad(): Promise<void>;\n\n  /**\n   * Run TrainStep asynchronously with the given feeds and options.\n   *\n   * @param feeds - Representation of the model input. See type description of `InferenceSession.InputType` for\n   detail.\n   * @param options - Optional. A set of options that controls the behavior of model training.\n   * @returns A promise that resolves to a map, which uses output names as keys and OnnxValue as corresponding values.\n   */\n  runTrainStep(feeds: InferenceSession.FeedsType, options?: InferenceSession.RunOptions):\n      Promise<InferenceSession.ReturnType>;\n\n  /**\n   * Run a single train step with the given inputs and options.\n   *\n   * @param feeds - Representation of the model input.\n   * @param fetches - Representation of the model output.\n   * detail.\n   * @param options - Optional. A set of options that controls the behavior of model training.\n   * @returns A promise that resolves to a map, which uses output names as keys and OnnxValue as corresponding\n   values.\n   */\n  runTrainStep(\n      feeds: InferenceSession.FeedsType, fetches: InferenceSession.FetchesType,\n      options?: InferenceSession.RunOptions): Promise<InferenceSession.ReturnType>;\n\n  /**\n   * Runs a single optimizer step, which performs weight updates for the trainable parameters using the optimizer model.\n   *\n   * @param options - Optional. A set of options that controls the behavior of model optimizing.\n   */\n  runOptimizerStep(options?: InferenceSession.RunOptions): Promise<void>;\n\n  /**\n   * Run a single eval step with the given inputs and options using the eval model.\n   *\n   * @param feeds - Representation of the model input.\n   * @param options - Optional. A set of options that controls the behavior of model eval step.\n   * @returns A promise that resolves to a map, which uses output names as keys and OnnxValue as corresponding\n   values.\n   */\n  runEvalStep(feeds: InferenceSession.FeedsType, options?: InferenceSession.RunOptions):\n      Promise<InferenceSession.ReturnType>;\n\n  /**\n   * Run a single eval step with the given inputs and options using the eval model.\n   *\n   * @param feeds - Representation of the model input.\n   * @param fetches - Representation of the model output.\n   * detail.\n   * @param options - Optional. A set of options that controls the behavior of model eval step.\n   * @returns A promise that resolves to a map, which uses output names as keys and OnnxValue as corresponding\n   values.\n   */\n  runEvalStep(\n      feeds: InferenceSession.FeedsType, fetches: InferenceSession.FetchesType,\n      options?: InferenceSession.RunOptions): Promise<InferenceSession.ReturnType>;\n\n  // #endregion\n\n  // #region copy parameters\n\n  /**\n   * Retrieves the size of all parameters for the training state. Calculates the total number of primitive (datatype of\n   * the parameters) elements of all the parameters in the training state.\n   *\n   * @param trainableOnly - When set to true, the size is calculated for trainable params only. Default value is true.\n   */\n  getParametersSize(trainableOnly: boolean): Promise<number>;\n\n  /**\n   * Copies parameter values from the given buffer to the training state. Currently, only supporting models with\n   * parameters of type Float32.\n   *\n   * @param buffer - A Uint8Array representation of Float32 parameters.\n   * @param trainableOnly - True if trainable parameters only to be modified, false otherwise. Default value is true.\n   */\n  loadParametersBuffer(buffer: Uint8Array, trainableOnly: boolean): Promise<void>;\n\n  /**\n   * Copies the model parameters to a contiguous buffer. Usually used in the context of Federated Learning.\n   * Currently, only supporting models with parameters of type Float32.\n   *\n   * @param trainableOnly - When set to true, only trainable parameters are copied. Trainable parameters are parameters\n   * for which requires_grad is set to true. Default value is true.\n   * @returns A promise that resolves to a Float32 OnnxValue of the requested parameters.\n   */\n  getContiguousParameters(trainableOnly: boolean): Promise<OnnxValue>;\n  // #endregion\n\n  // #region release()\n\n  /**\n   * Release the inference session and the underlying resources.\n   */\n  release(): Promise<void>;\n  // #endregion\n\n  // #region metadata\n\n  /**\n   * Get input names of the loaded training model.\n   */\n  readonly trainingInputNames: readonly string[];\n\n  /**\n   * Get output names of the loaded training model.\n   */\n  readonly trainingOutputNames: readonly string[];\n\n  /**\n   * Get input names of the loaded eval model. Is an empty array if no eval model is loaded.\n   */\n  readonly evalInputNames: readonly string[];\n\n  /**\n   * Get output names of the loaded eval model. Is an empty array if no eval model is loaded.\n   */\n  readonly evalOutputNames: readonly string[];\n\n  // #endregion\n}\n\n/**\n * Represents the optional parameters that can be passed into the TrainingSessionFactory.\n */\nexport interface TrainingSessionCreateOptions {\n  /**\n   * URI or buffer for a .ckpt file that contains the checkpoint for the training model.\n   */\n  checkpointState: TrainingSession.UriOrBuffer;\n  /**\n   * URI or buffer for the .onnx training file.\n   */\n  trainModel: TrainingSession.UriOrBuffer;\n  /**\n   * Optional. URI or buffer for the .onnx optimizer model file.\n   */\n  optimizerModel?: TrainingSession.UriOrBuffer;\n  /**\n   * Optional. URI or buffer for the .onnx eval model file.\n   */\n  evalModel?: TrainingSession.UriOrBuffer;\n}\n\n/**\n * Defines method overload possibilities for creating a TrainingSession.\n */\nexport interface TrainingSessionFactory {\n  // #region create()\n\n  /**\n   * Creates a new TrainingSession and asynchronously loads any models passed in through trainingOptions\n   *\n   * @param trainingOptions specify models and checkpoints to load into the Training Session\n   * @param sessionOptions specify configuration for training session behavior\n   *\n   * @returns Promise that resolves to a TrainingSession object\n   */\n  create(trainingOptions: TrainingSessionCreateOptions, sessionOptions?: InferenceSession.SessionOptions):\n      Promise<TrainingSession>;\n\n  // #endregion\n}\n\n// eslint-disable-next-line @typescript-eslint/naming-convention\nexport const TrainingSession: TrainingSessionFactory = TrainingSessionImpl;\n","// Copyright (c) Microsoft Corporation. All rights reserved.\n// Licensed under the MIT License.\n\n/**\n * # ONNX Runtime JavaScript API\n *\n * ONNX Runtime JavaScript API is a unified API for all JavaScript usages, including the following NPM packages:\n *\n * - [onnxruntime-node](https://www.npmjs.com/package/onnxruntime-node)\n * - [onnxruntime-web](https://www.npmjs.com/package/onnxruntime-web)\n * - [onnxruntime-react-native](https://www.npmjs.com/package/onnxruntime-react-native)\n *\n * See also:\n * - [Get Started](https://onnxruntime.ai/docs/get-started/with-javascript/)\n * - [Inference examples](https://github.com/microsoft/onnxruntime-inference-examples/tree/main/js)\n *\n * @packageDocumentation\n */\n\nexport * from './backend.js';\nexport * from './env.js';\nexport * from './inference-session.js';\nexport * from './tensor.js';\nexport * from './tensor-conversion.js';\nexport * from './tensor-factory.js';\nexport * from './trace.js';\nexport * from './onnx-model.js';\nexport * from './onnx-value.js';\nexport * from './training-session.js';\n","// 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\n/// <reference lib=\"webworker\" />\n\n//\n// * type hack for \"HTMLImageElement\"\n//\n// in typescript, the type of \"HTMLImageElement\" is defined in lib.dom.d.ts, which is conflict with lib.webworker.d.ts.\n// when we use webworker, the lib.webworker.d.ts will be used, which does not have HTMLImageElement defined.\n//\n// we will get the following errors complaining that HTMLImageElement is not defined:\n//\n// ====================================================================================================================\n//\n// ../common/dist/cjs/tensor-factory.d.ts:187:29 - error TS2552: Cannot find name 'HTMLImageElement'. Did you mean\n// 'HTMLLIElement'?\n//\n// 187     fromImage(imageElement: HTMLImageElement, options?: TensorFromImageElementOptions):\n// Promise<TypedTensor<'float32'> | TypedTensor<'uint8'>>;\n//                                 ~~~~~~~~~~~~~~~~\n//\n// node_modules/@webgpu/types/dist/index.d.ts:83:7 - error TS2552: Cannot find name 'HTMLImageElement'. Did you mean\n// 'HTMLLIElement'?\n//\n// 83     | HTMLImageElement\n//          ~~~~~~~~~~~~~~~~\n//\n// ====================================================================================================================\n//\n// `HTMLImageElement` is only used in type declaration and not in real code. So we define it as `unknown` here to\n// bypass the type check.\n\n//\n// * type hack for \"document\"\n//\n// in typescript, the type of \"document\" is defined in lib.dom.d.ts, so it's not available in webworker.\n//\n// we will get the following errors complaining that document is not defined:\n//\n// ====================================================================================================================\n//\n// lib/wasm/wasm-utils-import.ts:7:33 - error TS2584: Cannot find name 'document'. Do you need to change your target\n// library? Try changing the 'lib' compiler option to include 'dom'.\n//\n// 7 export const scriptSrc = typeof document !== 'undefined' ? (document?.currentScript as HTMLScriptElement)?.src :\n//                                   ~~~~~~~~\n//\n// lib/wasm/wasm-utils-import.ts:7:61 - error TS2584: Cannot find name 'document'. Do you need to change your target\n// library? Try changing the 'lib' compiler option to include 'dom'.\n//\n// 7 export const scriptSrc = typeof document !== 'undefined' ? (document?.currentScript as HTMLScriptElement)?.src :\n//                                                               ~~~~~~~~\n//\n// lib/wasm/wasm-utils-import.ts:7:88 - error TS2552: Cannot find name 'HTMLScriptElement'. Did you mean\n// 'HTMLLIElement'?\n//\n// 7 export const scriptSrc = typeof document !== 'undefined' ? (document?.currentScript as HTMLScriptElement)?.src :\n//                                                                                          ~~~~~~~~~~~~~~~~~\n// ====================================================================================================================\n//\n// `document` is used to get the current script URL, which is not available in webworker. This file is served as a\n// \"dual\" file for entries of both webworker and the esm module.\n//\ndeclare global {\n  type HTMLImageElement = unknown;\n  type HTMLScriptElement = {src?: string};\n  const document: undefined|{currentScript?: HTMLScriptElement};\n}\n\n/**\n * @summary\n *\n * This file is served as a \"dual\" file for both entries of the following:\n * - The proxy worker itself.\n *   - When used as a worker, it listens to the messages from the main thread and performs the corresponding operations.\n *   - Should be imported directly using `new Worker()` in the main thread.\n *\n * - The ESM module that creates the proxy worker (as a worker launcher).\n *   - When used as a worker launcher, it creates the proxy worker and returns it.\n *   - Should be imported using `import()` in the main thread, with the query parameter `import=1`.\n *\n * This file will be always compiling into ESM format.\n */\n\nimport type {OrtWasmMessage, SerializableTensorMetadata} from '../proxy-messages.js';\nimport {createSession, copyFromExternalBuffer, endProfiling, extractTransferableBuffers, initEp, initRuntime, releaseSession, run} from '../wasm-core-impl.js';\nimport {initializeWebAssembly} from '../wasm-factory.js';\nimport {scriptSrc} from '../wasm-utils-import.js';\n\nconst WORKER_NAME = 'ort-wasm-proxy-worker';\nconst isProxyWorker = globalThis.self?.name === WORKER_NAME;\n\nif (isProxyWorker) {\n  // Worker thread\n  self.onmessage = (ev: MessageEvent<OrtWasmMessage>): void => {\n    const {type, in : message} = ev.data;\n    try {\n      switch (type) {\n        case 'init-wasm':\n          initializeWebAssembly(message!.wasm)\n              .then(\n                  () => {\n                    initRuntime(message!).then(\n                        () => {\n                          postMessage({type});\n                        },\n                        err => {\n                          postMessage({type, err});\n                        });\n                  },\n                  err => {\n                    postMessage({type, err});\n                  });\n          break;\n        case 'init-ep': {\n          const {epName, env} = message!;\n          initEp(env, epName)\n              .then(\n                  () => {\n                    postMessage({type});\n                  },\n                  err => {\n                    postMessage({type, err});\n                  });\n          break;\n        }\n        case 'copy-from': {\n          const {buffer} = message!;\n          const bufferData = copyFromExternalBuffer(buffer);\n          postMessage({type, out: bufferData} as OrtWasmMessage);\n          break;\n        }\n        case 'create': {\n          const {model, options} = message!;\n          createSession(model, options)\n              .then(\n                  sessionMetadata => {\n                    postMessage({type, out: sessionMetadata} as OrtWasmMessage);\n                  },\n                  err => {\n                    postMessage({type, err});\n                  });\n          break;\n        }\n        case 'release':\n          releaseSession(message!);\n          postMessage({type});\n          break;\n        case 'run': {\n          const {sessionId, inputIndices, inputs, outputIndices, options} = message!;\n          run(sessionId, inputIndices, inputs, outputIndices, new Array(outputIndices.length).fill(null), options)\n              .then(\n                  outputs => {\n                    if (outputs.some(o => o[3] !== 'cpu')) {\n                      postMessage({type, err: 'Proxy does not support non-cpu tensor location.'});\n                    } else {\n                      postMessage(\n                          {type, out: outputs} as OrtWasmMessage,\n                          extractTransferableBuffers([...inputs, ...outputs] as SerializableTensorMetadata[]));\n                    }\n                  },\n                  err => {\n                    postMessage({type, err});\n                  });\n          break;\n        }\n        case 'end-profiling':\n          endProfiling(message!);\n          postMessage({type});\n          break;\n        default:\n      }\n    } catch (err) {\n      postMessage({type, err} as OrtWasmMessage);\n    }\n  };\n}\n\nexport default isProxyWorker ?\n    null :\n    (urlOverride?: string) =>\n        new Worker(urlOverride ?? scriptSrc!, {type: BUILD_DEFS.IS_ESM ? 'module' : 'classic', name: WORKER_NAME});\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 {InferenceSession, Tensor} from 'onnxruntime-common';\n\nimport {SerializableInternalBuffer, TensorMetadata} from './proxy-messages';\nimport {setRunOptions} from './run-options';\nimport {setSessionOptions} from './session-options';\nimport {dataLocationStringToEnum, tensorDataTypeEnumToString, tensorDataTypeStringToEnum, tensorTypeToTypedArrayConstructor} from './wasm-common';\nimport {prepareInputOutputTensor} from './wasm-core-impl';\nimport {getInstance} from './wasm-factory';\nimport {checkLastError} from './wasm-utils';\n\nconst NO_TRAIN_FUNCS_MSG =\n    'Built without training API\\'s enabled. Use the onnxruntime-web/training import for training ' +\n    'functionality, and make sure that all the correct artifacts are built & moved to the correct folder if ' +\n    'using a custom build. Check https://onnxruntime.ai/docs/build/web.html for more information.';\n\n/**\n * Runs the checkLastError function which will throw an error, if the provided error code matches the specified\n * pattern for an error code.\n * @param errCode number to evaluated for if it's an error\n * @param message message to pass into checkLastError\n * @param checkNeqZero when true, treats not equal to zero as an error.\n *                     When false, treats equal to zero as an error.\n */\nconst ifErrCodeCheckLastError = (errCode: number, message: string, checkNeqZero = true) => {\n  if (checkNeqZero && errCode !== 0) {\n    checkLastError(message);\n  } else if (!checkNeqZero && errCode === 0) {\n    checkLastError(message);\n  }\n};\n\nexport const createCheckpointHandle = (checkpointData: SerializableInternalBuffer): number => {\n  const wasm = getInstance();\n\n  const [checkpointDataOffset, checkpointDataLength] = checkpointData;\n  let checkpointHandle = 0;\n\n  try {\n    if (wasm._OrtTrainingLoadCheckpoint) {\n      checkpointHandle = wasm._OrtTrainingLoadCheckpoint(checkpointDataOffset, checkpointDataLength);\n    } else {\n      throw new Error(NO_TRAIN_FUNCS_MSG);\n    }\n\n    ifErrCodeCheckLastError(checkpointHandle, 'Error occurred when trying to create a CheckpointState', false);\n    return checkpointHandle;\n  } catch (e) {\n    if (wasm._OrtTrainingReleaseCheckpoint && checkpointHandle !== 0) {\n      wasm._OrtTrainingReleaseCheckpoint(checkpointHandle);\n    }\n    throw e;\n  } finally {\n    // free buffer from wasm heap\n    wasm._OrtFree(checkpointData[0]);\n  }\n};\n\nconst getModelInputOutputCount = (trainingSessionId: number, isEvalModel: boolean): [number, number] => {\n  const wasm = getInstance();\n  const stack = wasm.stackSave();\n  try {\n    const dataOffset = wasm.stackAlloc(8);\n    if (wasm._OrtTrainingGetModelInputOutputCount) {\n      const errorCode =\n          wasm._OrtTrainingGetModelInputOutputCount(trainingSessionId, dataOffset, dataOffset + 4, isEvalModel);\n      ifErrCodeCheckLastError(errorCode, 'Can\\'t get session input/output count.');\n      return [wasm.HEAP32[dataOffset / 4], wasm.HEAP32[dataOffset / 4 + 1]];\n    } else {\n      throw new Error(NO_TRAIN_FUNCS_MSG);\n    }\n  } finally {\n    wasm.stackRestore(stack);\n  }\n};\n\nconst getModelInputOutputNamesLoop =\n    (trainingSessionId: number, count: number, isInput: boolean, isEvalModel: boolean): string[] => {\n      const names = [];\n      const wasm = getInstance();\n\n      for (let i = 0; i < count; i++) {\n        if (wasm._OrtTrainingGetModelInputOutputName) {\n          const name = wasm._OrtTrainingGetModelInputOutputName(trainingSessionId, i, isInput, isEvalModel);\n          ifErrCodeCheckLastError(name, `Can't get input or output name -- is input: ${isInput}, index ${i}`, false);\n\n          names.push(wasm.UTF8ToString(name));\n          wasm._free(name);\n        } else {\n          throw new Error(NO_TRAIN_FUNCS_MSG);\n        }\n      }\n      return names;\n    };\n\nexport const getModelInputOutputNames = (trainingSessionId: number, isEvalModel: boolean): [string[], string[]] => {\n  let inputNames: string[] = [];\n  let outputNames: string[] = [];\n\n  const [inputCount, outputCount] = getModelInputOutputCount(trainingSessionId, isEvalModel);\n\n  inputNames = getModelInputOutputNamesLoop(trainingSessionId, inputCount, true, isEvalModel);\n  outputNames = getModelInputOutputNamesLoop(trainingSessionId, outputCount, false, isEvalModel);\n\n  return [inputNames, outputNames];\n};\n\nexport const createTrainingSessionHandle =\n    (checkpointHandle: number, trainModelData: SerializableInternalBuffer, evalModelData: SerializableInternalBuffer,\n     optimizerModelData: SerializableInternalBuffer, options: InferenceSession.SessionOptions): number => {\n      const wasm = getInstance();\n\n      let trainingSessionHandle = 0;\n      let sessionOptionsHandle = 0;\n      let allocs: number[] = [];\n\n      try {\n        [sessionOptionsHandle, allocs] = setSessionOptions(options);\n        if (wasm._OrtTrainingCreateSession) {\n          trainingSessionHandle = wasm._OrtTrainingCreateSession(\n              sessionOptionsHandle, checkpointHandle, trainModelData[0], trainModelData[1], evalModelData[0],\n              evalModelData[1], optimizerModelData[0], optimizerModelData[1]);\n        } else {\n          throw new Error(NO_TRAIN_FUNCS_MSG);\n        }\n\n        ifErrCodeCheckLastError(trainingSessionHandle, 'Error occurred when trying to create a TrainingSession', false);\n        return trainingSessionHandle;\n      } catch (e) {\n        if (wasm._OrtTrainingReleaseSession && trainingSessionHandle !== 0) {\n          wasm._OrtTrainingReleaseSession(trainingSessionHandle);\n        }\n        throw e;\n      } finally {\n        wasm._free(trainModelData[0]);\n        wasm._free(evalModelData[0]);\n        wasm._free(optimizerModelData[0]);\n\n        if (sessionOptionsHandle !== 0) {\n          wasm._OrtReleaseSessionOptions(sessionOptionsHandle);\n        }\n        allocs.forEach(alloc => wasm._free(alloc));\n      }\n    };\n\n/**\n * Prepares input and output tensors by creating the tensors in the WASM side then creates a list of the handles of the\n * WASM tensors.\n *\n * @param trainingSessionId\n * @param indices for each tensor, the index of the input or output name that the tensor corresponds with\n * @param tensors list of TensorMetaData\n * @param tensorHandles should pass in an empty list of numbers; modified in-place by this method & stores the resulting\n *                      handles of the allocated tensors on the heap\n * @param inputOutputAllocs modified in-place by this method\n * @param indexAdd constant to add to the index that is passed to prepareInputOutputTensor\n */\nconst createAndAllocateTensors =\n    (trainingSessionId: number, indices: number[], tensors: Array<TensorMetadata|null>, tensorHandles: number[],\n     inputOutputAllocs: number[], indexAdd: number) => {\n      const count = indices.length;\n\n      // creates the tensors\n      for (let i = 0; i < count; i++) {\n        prepareInputOutputTensor(\n            tensors[i], tensorHandles, inputOutputAllocs, trainingSessionId, indexAdd + indices[i]);\n      }\n\n      // moves to heap\n      const wasm = getInstance();\n      const valuesOffset = wasm.stackAlloc(count * 4);\n      let valuesIndex = valuesOffset / 4;\n      for (let i = 0; i < count; i++) {\n        wasm.HEAPU32[valuesIndex++] = tensorHandles[i];\n      }\n\n      return valuesOffset;\n    };\n\n/**\n * Retrieves the information from the output tensor handles, copies to an array, and frees the WASM information\n * associated with the tensor handle.\n *\n * @param outputValuesOffset\n * @param outputCount\n * @returns list of TensorMetadata retrieved from the output handles.\n */\nconst moveOutputToTensorMetadataArr =\n    (outputValuesOffset: number, outputCount: number, outputTensorHandles: number[],\n     outputTensors: Array<TensorMetadata|null>) => {\n      const wasm = getInstance();\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 type: Tensor.Type|undefined, dataOffset = 0;\n        try {\n          const errorCode = wasm._OrtGetTensorData(\n              tensor, tensorDataOffset, tensorDataOffset + 4, tensorDataOffset + 8, tensorDataOffset + 12);\n          ifErrCodeCheckLastError(errorCode, `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          if (type === 'string') {\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            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        } finally {\n          wasm.stackRestore(beforeGetTensorDataStack);\n          if (type === 'string' && dataOffset) {\n            wasm._free(dataOffset);\n          }\n          wasm._OrtReleaseTensor(tensor);\n        }\n      }\n\n      return output;\n    };\n\nexport const lazyResetGrad = async(trainingSessionId: number): Promise<void> => {\n  const wasm = getInstance();\n\n  if (wasm._OrtTrainingLazyResetGrad) {\n    const errorCode = wasm._OrtTrainingLazyResetGrad(trainingSessionId);\n    ifErrCodeCheckLastError(errorCode, 'Can\\'t call lazyResetGrad.');\n  } else {\n    throw new Error(NO_TRAIN_FUNCS_MSG);\n  }\n};\n\nexport const runTrainStep = async(\n    trainingSessionId: number, inputIndices: number[], inputTensors: TensorMetadata[], outputIndices: number[],\n    outputTensors: Array<TensorMetadata|null>, options: InferenceSession.RunOptions): Promise<TensorMetadata[]> => {\n  const wasm = getInstance();\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\n  try {\n    // prepare parameters by moving them to heap\n    [runOptionsHandle, runOptionsAllocs] = setRunOptions(options);\n\n    // handle inputs -- you don't want anything added to the index\n    const inputValuesOffset = createAndAllocateTensors(\n        trainingSessionId, inputIndices, inputTensors, inputTensorHandles, inputOutputAllocs, 0);\n    // handle outputs\n    // you want inputCount to be added to the index of every output tensor passed to prepareInputOutputTensor\n    const outputValuesOffset = createAndAllocateTensors(\n        trainingSessionId, outputIndices, outputTensors, outputTensorHandles, inputOutputAllocs, inputCount);\n\n    if (wasm._OrtTrainingRunTrainStep) {\n      const errorCode = wasm._OrtTrainingRunTrainStep(\n          trainingSessionId, inputValuesOffset, inputCount, outputValuesOffset, outputCount, runOptionsHandle);\n      ifErrCodeCheckLastError(errorCode, 'failed to call OrtTrainingRunTrainStep in the WebAssembly layer');\n    } else {\n      throw new Error(NO_TRAIN_FUNCS_MSG);\n    }\n\n    return moveOutputToTensorMetadataArr(outputValuesOffset, outputCount, outputTensorHandles, outputTensors);\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\nexport const runOptimizerStep =\n    async(trainingSessionId: number, options: InferenceSession.RunOptions): Promise<void> => {\n  const wasm = getInstance();\n\n  let runOptionsHandle = 0;\n  let runOptionsAllocs: number[] = [];\n\n  try {\n    [runOptionsHandle, runOptionsAllocs] = setRunOptions(options);\n\n    if (wasm._OrtTrainingOptimizerStep) {\n      const errCode = wasm._OrtTrainingOptimizerStep(trainingSessionId, runOptionsHandle);\n      ifErrCodeCheckLastError(errCode, 'Failed to call OrtTrainingOptimizerStep in the WebAssembly layer');\n    } else {\n      throw new Error(NO_TRAIN_FUNCS_MSG);\n    }\n  } finally {\n    if (runOptionsHandle !== 0) {\n      wasm._OrtReleaseRunOptions(runOptionsHandle);\n    }\n    runOptionsAllocs.forEach(p => wasm._free(p));\n  }\n};\n\nexport const runEvalStep = async(\n    trainingSessionId: number, inputIndices: number[], inputTensors: TensorMetadata[], outputIndices: number[],\n    outputTensors: Array<TensorMetadata|null>, options: InferenceSession.RunOptions): Promise<TensorMetadata[]> => {\n  const wasm = getInstance();\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\n  try {\n    // prepare parameters by moving them to heap\n    [runOptionsHandle, runOptionsAllocs] = setRunOptions(options);\n\n    // handle inputs -- you don't want anything added to the index\n    const inputValuesOffset = createAndAllocateTensors(\n        trainingSessionId, inputIndices, inputTensors, inputTensorHandles, inputOutputAllocs, 0);\n    // handle outputs\n    // you want inputCount to be added to the index of every output tensor passed to prepareInputOutputTensor\n    const outputValuesOffset = createAndAllocateTensors(\n        trainingSessionId, outputIndices, outputTensors, outputTensorHandles, inputOutputAllocs, inputCount);\n\n    if (wasm._OrtTrainingEvalStep) {\n      const errorCode = wasm._OrtTrainingEvalStep(\n          trainingSessionId, inputValuesOffset, inputCount, outputValuesOffset, outputCount, runOptionsHandle);\n\n      ifErrCodeCheckLastError(errorCode, 'failed to call OrtTrainingEvalStep in the WebAssembly layer');\n    } else {\n      throw new Error(NO_TRAIN_FUNCS_MSG);\n    }\n\n    return moveOutputToTensorMetadataArr(outputValuesOffset, outputCount, outputTensorHandles, outputTensors);\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\nexport const getParametersSize = (trainingSessionId: number, trainableOnly: boolean): number => {\n  const wasm = getInstance();\n  const stack = wasm.stackSave();\n\n  try {\n    const sizeOffset = wasm.stackAlloc(4);\n    if (wasm._OrtTrainingGetParametersSize) {\n      const errorCode = wasm._OrtTrainingGetParametersSize(trainingSessionId, sizeOffset, trainableOnly);\n      ifErrCodeCheckLastError(errorCode, 'Can\\'t get parameters size');\n\n      return wasm.HEAP32[sizeOffset / 4];\n    } else {\n      throw new Error(NO_TRAIN_FUNCS_MSG);\n    }\n  } finally {\n    wasm.stackRestore(stack);\n  }\n};\n\nexport const getContiguousParameters =\n    async(trainingSessionId: number, trainableOnly: boolean): Promise<TensorMetadata> => {\n  const wasm = getInstance();\n  const stack = wasm.stackSave();\n\n  const tensorTypeAsString = 'float32';\n  const locationAsString = 'cpu';\n\n  const parametersSize = getParametersSize(trainingSessionId, trainableOnly);\n  let tensor = 0;\n\n  // allocates a buffer of the correct size on the WASM heap\n  const paramsByteLength = 4 * parametersSize;\n  const paramsOffset = wasm._malloc(paramsByteLength);\n\n  // handles the dimensions-related createTensor parameters\n  const dims = [parametersSize];\n\n  const dimsOffset = wasm.stackAlloc(4);\n  const dimsIndex = dimsOffset / 4;\n  wasm.HEAP32[dimsIndex] = parametersSize;\n\n  try {\n    // wraps allocated array in a tensor\n    tensor = wasm._OrtCreateTensor(\n        tensorDataTypeStringToEnum(tensorTypeAsString), paramsOffset, paramsByteLength, dimsOffset, dims.length,\n        dataLocationStringToEnum(locationAsString));\n    ifErrCodeCheckLastError(\n        tensor, `Can't create tensor for getContiguousParameters. session=${trainingSessionId}.`, false);\n\n    if (wasm._OrtTrainingCopyParametersToBuffer) {\n      const errCode = wasm._OrtTrainingCopyParametersToBuffer(trainingSessionId, tensor, parametersSize, trainableOnly);\n      ifErrCodeCheckLastError(errCode, 'Can\\'t get contiguous parameters.');\n\n    } else {\n      throw new Error(NO_TRAIN_FUNCS_MSG);\n    }\n\n    // copies from WASM memory to a JavaScript typed array, which is then put into a TensorMetadata object\n    const typedArrayConstructor = tensorTypeToTypedArrayConstructor(tensorTypeAsString);\n    const data = new typedArrayConstructor(parametersSize);\n    const output: TensorMetadata[] = [];\n    new Uint8Array(data.buffer, data.byteOffset, data.byteLength)\n        .set(wasm.HEAPU8.subarray(paramsOffset, paramsOffset + paramsByteLength));\n    output.push([tensorTypeAsString, dims, data, locationAsString]);\n    if (output.length !== 1) {\n      throw new Error(`something unexpected happened in the getContiguousParameters function. Expected output length of\n     one, got ${output.length}`);\n    } else {\n      return output[0];\n    }\n  } finally {\n    if (tensor !== 0) {\n      wasm._OrtReleaseTensor(tensor);\n    }\n    wasm._free(paramsOffset);\n    wasm._free(dimsOffset);\n    wasm.stackRestore(stack);\n  }\n};\n\nexport const loadParametersBuffer =\n    async(trainingSessionId: number, buffer: Uint8Array, trainableOnly: boolean): Promise<void> => {\n  const wasm = getInstance();\n  const stack = wasm.stackSave();\n\n  const tensorTypeAsString = 'float32';\n  const locationAsString = 'cpu';\n\n  // allocates & copies JavaScript buffer to WASM heap\n  const bufferByteLength = buffer.length;\n  const bufferCount = bufferByteLength / 4;\n  const bufferOffset = wasm._malloc(bufferByteLength);\n  wasm.HEAPU8.set(buffer, bufferOffset);\n\n  // allocates and handles moving dimensions information to WASM memory\n  const dimsOffset = wasm.stackAlloc(4);\n  wasm.HEAP32[dimsOffset / 4] = bufferCount;\n  const dimsLength = 1;\n  let tensor = 0;\n\n  try {\n    tensor = wasm._OrtCreateTensor(\n        tensorDataTypeStringToEnum(tensorTypeAsString), bufferOffset, bufferByteLength, dimsOffset, dimsLength,\n        dataLocationStringToEnum(locationAsString));\n    ifErrCodeCheckLastError(tensor, `Can't create tensor for input/output. session=${trainingSessionId}`, false);\n\n    if (wasm._OrtTrainingCopyParametersFromBuffer) {\n      const errCode = wasm._OrtTrainingCopyParametersFromBuffer(trainingSessionId, tensor, bufferCount, trainableOnly);\n      ifErrCodeCheckLastError(errCode, 'Can\\'t copy buffer to parameters.');\n    } else {\n      throw new Error(NO_TRAIN_FUNCS_MSG);\n    }\n  } finally {\n    if (tensor !== 0) {\n      wasm._OrtReleaseTensor(tensor);\n    }\n    wasm.stackRestore(stack);\n    wasm._free(bufferOffset);\n    wasm._free(dimsOffset);\n  }\n};\n\nexport const releaseTrainingSessionAndCheckpoint = (checkpointId: number, sessionId: number): void => {\n  const wasm = getInstance();\n\n  if (wasm._OrtTrainingReleaseSession) {\n    wasm._OrtTrainingReleaseSession(sessionId);\n  }\n  if (wasm._OrtTrainingReleaseCheckpoint) {\n    wasm._OrtTrainingReleaseCheckpoint(checkpointId);\n  }\n};\n","// Copyright (c) Microsoft Corporation. All rights reserved.\n// Licensed under the MIT License.\n\nimport {InferenceSession, OnnxValue, SessionHandler, Tensor, TrainingSessionHandler} from 'onnxruntime-common';\n\nimport {SerializableInternalBuffer, TensorMetadata} from './proxy-messages';\nimport {decodeTensorMetadata, encodeTensorMetadata} from './session-handler-inference';\nimport {copyFromExternalBuffer} from './wasm-core-impl';\nimport {createCheckpointHandle, createTrainingSessionHandle, getContiguousParameters, getModelInputOutputNames, getParametersSize, lazyResetGrad, loadParametersBuffer, releaseTrainingSessionAndCheckpoint, runEvalStep, runOptimizerStep, runTrainStep} from './wasm-training-core-impl';\n\nexport class OnnxruntimeWebAssemblyTrainingSessionHandler implements TrainingSessionHandler {\n  private sessionId: number;\n  private checkpointId: number;\n\n  inputNames: string[];\n  outputNames: string[];\n\n  evalInputNames: string[] = [];\n  evalOutputNames: string[] = [];\n\n  async uriOrBufferToHeap(uriOrBuffer: string|Uint8Array): Promise<SerializableInternalBuffer> {\n    let buffer: Uint8Array;\n    if (typeof uriOrBuffer === 'string') {\n      const response = await fetch(uriOrBuffer);\n      const arrayBuffer = await response.arrayBuffer();\n      buffer = new Uint8Array(arrayBuffer);\n    } else {\n      buffer = uriOrBuffer;\n    }\n    return copyFromExternalBuffer(buffer);\n  }\n\n  async createTrainingSession(\n      checkpointStateUriOrBuffer: string|Uint8Array, trainModelUriOrBuffer: string|Uint8Array,\n      evalModelUriOrBuffer: string|Uint8Array, optimizerModelUriOrBuffer: string|Uint8Array,\n      options: InferenceSession.SessionOptions) {\n    const checkpointData: SerializableInternalBuffer = await this.uriOrBufferToHeap(checkpointStateUriOrBuffer);\n    const trainModelData: SerializableInternalBuffer = await this.uriOrBufferToHeap(trainModelUriOrBuffer);\n    // 0 is supposed to be the nullptr\n    let evalModelData: SerializableInternalBuffer = [0, 0];\n    let optimizerModelData: SerializableInternalBuffer = [0, 0];\n\n    if (evalModelUriOrBuffer !== '') {\n      evalModelData = await this.uriOrBufferToHeap(evalModelUriOrBuffer);\n    }\n    if (optimizerModelUriOrBuffer !== '') {\n      optimizerModelData = await this.uriOrBufferToHeap(optimizerModelUriOrBuffer);\n    }\n\n    this.checkpointId = createCheckpointHandle(checkpointData);\n    this.sessionId =\n        createTrainingSessionHandle(this.checkpointId, trainModelData, evalModelData, optimizerModelData, options);\n    [this.inputNames, this.outputNames] = getModelInputOutputNames(this.sessionId, false);\n    if (evalModelUriOrBuffer !== '') {\n      [this.evalInputNames, this.evalOutputNames] = getModelInputOutputNames(this.sessionId, true);\n    }\n  }\n\n  /**\n   * Helper method that converts a feeds or fetches datatype to two arrays, one of values and one that stores the\n   * corresponding name as a number referring to the index in the list of names provided.\n   *\n   * @param feeds meant to match either SessionHandler.FeedsType or SessionHandler.FetchesType\n   * @param names either inputNames or outputNames\n   * @returns a tuple of a list of values and a list of indices.\n   */\n  convertMapIntoValuesArrayAndIndicesArray<T, U>(\n      feeds: {[name: string]: T}, names: string[], mapFunc: (val: T, index: number) => U): [T[], number[], U[]] {\n    const values: T[] = [];\n    const indices: number[] = [];\n    Object.entries(feeds).forEach(kvp => {\n      const name = kvp[0];\n      const tensor = kvp[1];\n      const index = names.indexOf(name);\n      if (index === -1) {\n        throw new Error(`invalid input '${name}`);\n      }\n      values.push(tensor);\n      indices.push(index);\n    });\n\n    const uList = values.map(mapFunc);\n    return [values, indices, uList];\n  }\n\n  /**\n   * Helper method that converts the TensorMetadata that the wasm-core functions return to the\n   * SessionHandler.ReturnType. Any outputs in the provided outputArray that are falsy will be populated with the\n   * corresponding result.\n   *\n   * @param results used to populate the resultMap if there is no value for that outputName already\n   * @param outputArray used to populate the resultMap. If null or undefined, use the corresponding result from results\n   * @param outputIndices specifies which outputName the corresponding value for outputArray refers to.\n   * @returns a map of output names and OnnxValues.\n   */\n  convertTensorMetadataToReturnType(\n      results: TensorMetadata[], outputArray: Array<Tensor|null>, outputIndices: number[]): SessionHandler.ReturnType {\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    return resultMap;\n  }\n\n  async lazyResetGrad(): Promise<void> {\n    await lazyResetGrad(this.sessionId);\n  }\n\n  async runTrainStep(\n      feeds: SessionHandler.FeedsType, fetches: SessionHandler.FetchesType,\n      options: InferenceSession.RunOptions): Promise<SessionHandler.ReturnType> {\n    const [, inputIndices, inputs] = this.convertMapIntoValuesArrayAndIndicesArray<Tensor, TensorMetadata>(\n        feeds, this.inputNames,\n        (t, i): TensorMetadata => encodeTensorMetadata(t, () => `input \"${this.inputNames[inputIndices[i]]}\"`));\n\n    const [outputArray, outputIndices, outputs] =\n        this.convertMapIntoValuesArrayAndIndicesArray<Tensor|null, TensorMetadata|null>(\n            fetches, this.outputNames,\n            (t, i): TensorMetadata|null =>\n                t ? encodeTensorMetadata(t, () => `output \"${this.outputNames[outputIndices[i]]}\"`) : null);\n\n    const results = await runTrainStep(this.sessionId, inputIndices, inputs, outputIndices, outputs, options);\n    return this.convertTensorMetadataToReturnType(results, outputArray, outputIndices);\n  }\n\n  async runOptimizerStep(options: InferenceSession.RunOptions): Promise<void> {\n    await runOptimizerStep(this.sessionId, options);\n  }\n\n  async runEvalStep(\n      feeds: SessionHandler.FeedsType, fetches: SessionHandler.FetchesType,\n      options: InferenceSession.RunOptions): Promise<SessionHandler.ReturnType> {\n    const [, inputIndices, inputs] = this.convertMapIntoValuesArrayAndIndicesArray<Tensor, TensorMetadata>(\n        feeds, this.evalInputNames,\n        (t, i): TensorMetadata => encodeTensorMetadata(t, () => `input \"${this.evalInputNames[inputIndices[i]]}\"`));\n\n    const [outputArray, outputIndices, outputs] =\n        this.convertMapIntoValuesArrayAndIndicesArray<Tensor|null, TensorMetadata|null>(\n            fetches, this.evalOutputNames,\n            (t, i): TensorMetadata|null =>\n                t ? encodeTensorMetadata(t, () => `output \"${this.evalOutputNames[outputIndices[i]]}\"`) : null);\n\n    const results = await runEvalStep(this.sessionId, inputIndices, inputs, outputIndices, outputs, options);\n    return this.convertTensorMetadataToReturnType(results, outputArray, outputIndices);\n  }\n\n  async getParametersSize(trainableOnly: boolean): Promise<number> {\n    return getParametersSize(this.sessionId, trainableOnly);\n  }\n\n  async loadParametersBuffer(array: Uint8Array, trainableOnly: boolean): Promise<void> {\n    await loadParametersBuffer(this.sessionId, array, trainableOnly);\n  }\n  async getContiguousParameters(trainableOnly: boolean): Promise<OnnxValue> {\n    const tensorResult = await getContiguousParameters(this.sessionId, trainableOnly);\n    return decodeTensorMetadata(tensorResult);\n  }\n\n  async dispose(): Promise<void> {\n    return releaseTrainingSessionAndCheckpoint(this.checkpointId, this.sessionId);\n  }\n}\n","// Copyright (c) Microsoft Corporation. All rights reserved.\n// Licensed under the MIT License.\n\nimport {InferenceSession, TrainingSessionHandler} from 'onnxruntime-common';\n\nimport {OnnxruntimeWebAssemblyBackend} from './backend-wasm';\nimport {OnnxruntimeWebAssemblyTrainingSessionHandler} from './wasm/session-handler-training';\n\nclass OnnxruntimeTrainingWebAssemblyBackend extends OnnxruntimeWebAssemblyBackend {\n  async createTrainingSessionHandler(\n      checkpointStateUriOrBuffer: string|Uint8Array, trainModelUriOrBuffer: string|Uint8Array,\n      evalModelUriOrBuffer: string|Uint8Array, optimizerModelUriOrBuffer: string|Uint8Array,\n      options: InferenceSession.SessionOptions): Promise<TrainingSessionHandler> {\n    const handler = new OnnxruntimeWebAssemblyTrainingSessionHandler();\n    await handler.createTrainingSession(\n        checkpointStateUriOrBuffer, trainModelUriOrBuffer, evalModelUriOrBuffer, optimizerModelUriOrBuffer, options);\n    return Promise.resolve(handler);\n  }\n}\n\nexport const wasmBackend = new OnnxruntimeTrainingWebAssemblyBackend();\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"]}