@copio/sdk 0.1.5 → 0.1.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (116) hide show
  1. package/THIRD_PARTY_NOTICES.md +34 -0
  2. package/dist/adapters/edge/index.js +2 -0
  3. package/dist/adapters/edge/index.js.map +7 -0
  4. package/dist/adapters/edge/null-edge-detector-adapter.js +2 -0
  5. package/dist/adapters/edge/null-edge-detector-adapter.js.map +7 -0
  6. package/dist/adapters/edge/scanic-wasm-adapter.js +2 -0
  7. package/dist/adapters/edge/scanic-wasm-adapter.js.map +7 -0
  8. package/dist/adapters/image/canvas2d-adapter.js +1 -1
  9. package/dist/adapters/image/index.js +1 -1
  10. package/dist/adapters/image/null-image-processor-adapter.js +1 -1
  11. package/dist/adapters/index.js +1 -1
  12. package/dist/adapters/indexeddb-adapter.js +1 -1
  13. package/dist/adapters/memory-adapter.js +1 -1
  14. package/dist/adapters/ocr/index.js +1 -1
  15. package/dist/adapters/ocr/null-ocr-adapter.js +1 -1
  16. package/dist/adapters/ocr/tesseract-wasm-adapter.js +1 -1
  17. package/dist/adapters/pdf/index.js +1 -1
  18. package/dist/adapters/pdf/null-pdf-adapter.js +1 -1
  19. package/dist/adapters/pdf/pdfkit-adapter.js +1 -1
  20. package/dist/adapters/storage/index.js +1 -1
  21. package/dist/adapters/storage/indexeddb-adapter.js +1 -1
  22. package/dist/adapters/storage/memory-adapter.js +1 -1
  23. package/dist/adapters/sync/index.js +1 -1
  24. package/dist/adapters/sync/null-sync-adapter.js +1 -1
  25. package/dist/adapters/sync/peerjs-adapter.js +1 -1
  26. package/dist/canvas-GKLGWNAJ.js +2 -0
  27. package/dist/cdn.js +189 -1409
  28. package/dist/chunk-25WAHT3G.js +2 -0
  29. package/dist/chunk-2VH2NPXW.js +175 -0
  30. package/dist/{chunk-DIU5BGU5.js → chunk-4D6GC55I.js} +2 -2
  31. package/dist/chunk-6QK7337A.js +2 -0
  32. package/dist/chunk-GLY5CGCY.js +2 -0
  33. package/dist/chunk-GU6OQMYK.js +4 -0
  34. package/dist/chunk-HCCNUPKB.js +2 -0
  35. package/dist/chunk-JIPKWRBK.js +2 -0
  36. package/dist/{chunk-GGERQ3CJ.js → chunk-NM4YYZYB.js} +3 -3
  37. package/dist/chunk-NNSM2I5L.js +2 -0
  38. package/dist/chunk-PBF7V4Z6.js +2 -0
  39. package/dist/chunk-PSGIWIRH.js +2 -0
  40. package/dist/chunk-Q3AWHANC.js +2 -0
  41. package/dist/chunk-R6Q4OXDG.js +2 -0
  42. package/dist/chunk-SZHKZARU.js +2 -0
  43. package/dist/{chunk-J7HWZNIP.js → chunk-T5CPA7B2.js} +2 -2
  44. package/dist/chunk-TK5N67RB.js +2 -0
  45. package/dist/chunk-V2D55DVU.js +1 -0
  46. package/dist/chunk-VPSUKD6F.js +2 -0
  47. package/dist/chunk-ZILTJGT2.js +2 -0
  48. package/dist/core.js +1 -1
  49. package/dist/custom-elements.json +2316 -135
  50. package/dist/export.js +1 -1
  51. package/dist/fs-Y7NMZRBK.js +2 -0
  52. package/dist/handoff-transport-7YFK4RYL.js +2 -0
  53. package/dist/handoff.js +2 -0
  54. package/dist/http-CYZIMVXQ.js +2 -0
  55. package/dist/https-OLG7KUSR.js +2 -0
  56. package/dist/index.js +11 -11
  57. package/dist/ocr.js +1 -1
  58. package/dist/path2d-HD3LU76S.js +2 -0
  59. package/dist/scanic-mlDetector-BCSVQYFV.js +2 -0
  60. package/dist/scanic-ort.wasm.min-MU4NYSP2.js +2 -0
  61. package/dist/scanner.js +3 -1396
  62. package/dist/sync.js +1 -1
  63. package/dist/types/js/adapters/edge/edge-detector-port.d.ts +183 -0
  64. package/dist/types/js/adapters/edge/index.d.ts +3 -0
  65. package/dist/types/js/adapters/edge/null-edge-detector-adapter.d.ts +35 -0
  66. package/dist/types/js/adapters/edge/scanic-wasm-adapter.d.ts +54 -0
  67. package/dist/types/js/adapters/storage/indexeddb-adapter.d.ts +11 -0
  68. package/dist/types/js/adapters/storage/memory-adapter.d.ts +11 -0
  69. package/dist/types/js/adapters/storage/opfs-adapter.d.ts +11 -0
  70. package/dist/types/js/adapters/storage/storage-port.d.ts +27 -0
  71. package/dist/types/js/services/doc-repository.d.ts +6 -1
  72. package/dist/types/js/services/handoff-crypto.d.ts +84 -0
  73. package/dist/types/js/services/handoff-session.d.ts +257 -0
  74. package/dist/types/js/services/handoff-transport.d.ts +51 -0
  75. package/dist/types/js/services/ice-servers.d.ts +33 -1
  76. package/dist/types/js/services/migration-runner.d.ts +100 -0
  77. package/dist/types/js/utils/perspective.d.ts +70 -0
  78. package/dist/types/js/utils/utils.d.ts +19 -1
  79. package/dist/types/sdk/core.d.ts +52 -6
  80. package/dist/types/sdk/elements.d.ts +2 -0
  81. package/dist/types/sdk/events.d.ts +42 -0
  82. package/dist/types/sdk/handoff-session.d.ts +4 -0
  83. package/dist/types/sdk/handoff-styles.d.ts +9 -0
  84. package/dist/types/sdk/handoff.d.ts +108 -0
  85. package/dist/types/sdk/index.d.ts +5 -1
  86. package/dist/types/sdk/models.d.ts +248 -1
  87. package/dist/types/sdk/scanner.d.ts +94 -1
  88. package/dist/types/sdk/styles.d.ts +1 -1
  89. package/dist/types/sdk/version.d.ts +1 -1
  90. package/dist/url-NYR4TEJV.js +2 -0
  91. package/package.json +10 -3
  92. package/sdk/core.js +219 -12
  93. package/sdk/events.js +14 -0
  94. package/sdk/handoff-session.js +26 -0
  95. package/sdk/handoff-styles.js +531 -0
  96. package/sdk/handoff.js +1079 -0
  97. package/sdk/index.js +38 -1
  98. package/sdk/models.js +116 -4
  99. package/sdk/scanner.js +1517 -151
  100. package/sdk/styles.js +297 -17
  101. package/sdk/version.js +1 -1
  102. package/dist/canvas-FAXPLPXN.js +0 -2
  103. package/dist/chunk-4C666HHU.js +0 -2
  104. package/dist/chunk-FQRADJY6.js +0 -2
  105. package/dist/chunk-G5EUMLYT.js +0 -4
  106. package/dist/chunk-K4NR6OAC.js +0 -2
  107. package/dist/chunk-L4OVZN23.js +0 -2
  108. package/dist/chunk-MEE2NNYB.js +0 -2
  109. package/dist/chunk-O7IV7A6O.js +0 -2
  110. package/dist/chunk-Q7XPZMZA.js +0 -1395
  111. package/dist/chunk-WETG2JD7.js +0 -2
  112. package/dist/fs-HJ6WWW73.js +0 -2
  113. package/dist/http-FKJJMT2N.js +0 -2
  114. package/dist/https-MUBFLDZM.js +0 -2
  115. package/dist/path2d-QWN6DFCC.js +0 -2
  116. package/dist/url-ABJ6S2Y6.js +0 -2
package/dist/export.js CHANGED
@@ -1,2 +1,2 @@
1
- import{a,b}from"./chunk-MEE2NNYB.js";import"./chunk-YNY65JUJ.js";import"./chunk-ZT72PD2C.js";import"./chunk-4C666HHU.js";export{b as exportDocumentAsImages,a as exportDocumentAsPdf};
1
+ import{a,b}from"./chunk-PBF7V4Z6.js";import"./chunk-YNY65JUJ.js";import"./chunk-ZT72PD2C.js";import"./chunk-25WAHT3G.js";export{b as exportDocumentAsImages,a as exportDocumentAsPdf};
2
2
  //# sourceMappingURL=export.js.map
@@ -0,0 +1,2 @@
1
+ import"./chunk-25WAHT3G.js";var t={},a=()=>null,e=globalThis.Path2D||class{};export{e as Path2D,a as createCanvas,t as default};
2
+ //# sourceMappingURL=fs-Y7NMZRBK.js.map
@@ -0,0 +1,2 @@
1
+ import{n as o}from"./chunk-VPSUKD6F.js";import{a as l,b as c}from"./chunk-SZHKZARU.js";import{h as a}from"./chunk-ZT72PD2C.js";import"./chunk-25WAHT3G.js";var d=class{#r;#n=null;#h=null;#e=null;#t=null;#I=null;#l=null;#g=null;#a="all";#y=null;#T=new Set;#P=new Set;#m=new Set;#s=!1;#o=!1;#c=0;#M=5;#d=null;#w=[];#i=null;#f=null;constructor(t={}){if(!t.role||t.role!=="host"&&t.role!=="sender")throw new Error("HandoffPeerTransport requires role to be 'host' or 'sender'");if(this.#r=t.role,this.#n=t.peerId||null,this.#h=t.targetPeerId||null,this.#I=t.iceServers||null,this.#l=t.relayUrl||null,this.#g=t.signalingUrl||null,this.#a=t.iceTransportPolicy||"all",this.#r==="sender"&&!this.#h)throw new Error("Sender transport requires targetPeerId");this.#r==="host"&&this.#n&&this.#H(),t.peerInstance?(this.#e=t.peerInstance,this.#b(this.#e)):this.#C().catch(e=>{console.warn("[HandoffPeerTransport] init error:",e)})}get peerId(){return this.#n}get targetPeerId(){return this.#h}get relayUrl(){return this.#l}get signalingUrl(){return this.#g}get iceTransportPolicy(){return this.#a}get connectionInfo(){return this.#y||{transport:this.#a==="relay"?"turn":"direct",rttMs:0}}async#C(){if(!this.#o)try{let t=this.#I;(!t||t.length===0)&&(t=await c({relayUrl:this.#l}));let e=await a();if(this.#o)return;if(!e)throw new Error("PeerJS is not available");let i={iceServers:t};this.#a&&(i.iceTransportPolicy=this.#a);let s={config:i,debug:0},n=this.#g||this.#l;if(n){let r=l(n);r&&(s.host=r.host,s.port=r.port,s.path=r.path,s.secure=r.secure)}this.#r==="host"&&this.#n?this.#e=new e(this.#n,s):this.#e=new e(s),this.#b(this.#e)}catch(t){console.warn("[HandoffPeerTransport] init failed:",t),this.#r==="sender"&&!this.#s&&this.#u()}}#H(){this.#i||!this.#n||(this.#i=new o,this.#f=o.register(this.#n,this.#i),this.#i.onMessage(t=>{this.#v(t)}))}#b(t){t.on("open",e=>{this.#n=e,this.#r==="host"&&this.#H(),this.#r==="sender"&&this.#h&&this.#S()}),t.on("connection",e=>{this.#r==="host"&&this.#U(e)}),t.on("error",e=>{console.warn("[HandoffPeerTransport] peer error:",e),this.#r==="sender"&&!this.#s&&this.#u()}),t.on("close",()=>{this.#p()})}#S(){if(!this.#e||this.#e.destroyed||!this.#h)return;let t=this.#e.connect(this.#h,{reliable:!0});this.#U(t)}#U(t){this.#t=t,t.on("open",()=>{this.#s=!1,this.#c=0,clearTimeout(this.#d);for(let e of this.#m)try{e()}catch(i){console.error("[HandoffPeerTransport] open handler error:",i)}for(;this.#w.length>0;){let e=this.#w.shift();try{t.send(e)}catch(i){console.error("[HandoffPeerTransport] send queued message error:",i)}}}),t.on("data",e=>{this.#v(e)}),t.on("close",()=>{this.#s||(this.#p(),this.#r==="sender"&&this.#u())}),t.on("error",e=>{console.warn("[HandoffPeerTransport] conn error:",e),this.#s||(this.#p(),this.#r==="sender"&&this.#u())})}#u(){if(this.#o||this.#s)return;if(this.#c>=this.#M){console.warn("[HandoffPeerTransport] max reconnect attempts reached");return}clearTimeout(this.#d);let t=Math.min(1e3*Math.pow(2,this.#c),8e3);this.#c++,this.#d=setTimeout(()=>{!this.#o&&!this.#s&&this.reconnect()},t)}reconnect(){if(!this.#o){if(this.#t){try{this.#t.close()}catch{}this.#t=null}this.#e&&!this.#e.destroyed&&this.#e.open?this.#S():this.#C().catch(()=>{})}}send(t){if(this.#o)throw new Error("Cannot send on destroyed HandoffPeerTransport");if(this.#i)try{this.#i.send(t)}catch{}this.#t&&this.#t.open?this.#t.send(t):(this.#r==="sender"||this.#t&&!this.#t.open)&&this.#w.push(t)}#v(t){for(let e of this.#T)try{e(t)}catch(i){console.error("[HandoffPeerTransport] message handler error:",i)}}#p(){for(let t of this.#P)try{t()}catch(e){console.error("[HandoffPeerTransport] close handler error:",e)}}onMessage(t){return this.#T.add(t),()=>this.#T.delete(t)}onClose(t){return this.#P.add(t),()=>this.#P.delete(t)}onOpen(t){if(this.#m.add(t),this.#t&&this.#t.open)try{t()}catch(e){console.error("[HandoffPeerTransport] open handler error:",e)}return()=>this.#m.delete(t)}async getConnectionInfo(){let t=this.#a==="relay",e=this.#t?.peerConnection||this.#t?._peerConnection;if(e&&typeof e.getStats=="function")try{let s=await e.getStats(),n=null;for(let r of s.values())if(r.type==="transport"&&r.selectedCandidatePairId){n=s.get(r.selectedCandidatePairId);break}if(!n){for(let r of s.values())if(r.type==="candidate-pair"&&(r.selected||r.nominated||r.state==="succeeded")){n=r;break}}if(n){let r=s.get(n.localCandidateId),f=s.get(n.remoteCandidateId),u=t||r?.candidateType==="relay"||f?.candidateType==="relay",p=n.currentRoundTripTime??n.roundTripTime??0,h={transport:u?"turn":"direct",rttMs:Math.round(p*1e3)};return this.#y=h,h}}catch(s){console.warn("[HandoffPeerTransport] getStats error:",s)}let i={transport:t?"turn":"direct",rttMs:0};return this.#y=i,i}close(){if(this.#s=!0,this.#o=!0,clearTimeout(this.#d),this.#f&&(this.#f(),this.#f=null),this.#i){try{this.#i.close()}catch{}this.#i=null}if(this.#t){try{this.#t.close()}catch{}this.#t=null}if(this.#e&&!this.#e.destroyed){try{this.#e.destroy()}catch{}this.#e=null}this.#p()}get isClosed(){return this.#s||this.#o}};export{d as HandoffPeerTransport};
2
+ //# sourceMappingURL=handoff-transport-7YFK4RYL.js.map
@@ -0,0 +1,2 @@
1
+ import{a as r,b as s,c as t,d as u}from"./chunk-2VH2NPXW.js";import{a as c,b as d,c as e,d as f,e as g,f as h,g as i,h as j,i as k,j as l,k as m,l as n,m as o,n as p,o as q}from"./chunk-VPSUKD6F.js";import{a,b}from"./chunk-HCCNUPKB.js";import"./chunk-ZT72PD2C.js";import"./chunk-25WAHT3G.js";export{a as COPIO_EVENTS,u as CopioHandoff,i as HANDOFF_DEFAULT_CHUNK_SIZE,j as HANDOFF_DEFAULT_TTL_MS,q as HandoffSession,p as LoopbackTransport,t as adoptHandoffStyles,n as buildHandoffUrl,m as decodeSessionToken,h as decryptPayload,f as deriveSharedKey,b as dispatchCopioEvent,l as encodeSessionToken,g as encryptPayload,d as exportPublicKey,c as generateEcdhKeyPair,s as getHandoffStyleSheet,r as handoffCss,e as importPublicKey,o as parseHandoffUrl,k as randomHandoffId};
2
+ //# sourceMappingURL=handoff.js.map
@@ -0,0 +1,2 @@
1
+ import"./chunk-25WAHT3G.js";var t={},a=()=>null,e=globalThis.Path2D||class{};export{e as Path2D,a as createCanvas,t as default};
2
+ //# sourceMappingURL=http-CYZIMVXQ.js.map
@@ -0,0 +1,2 @@
1
+ import"./chunk-25WAHT3G.js";var t={},a=()=>null,e=globalThis.Path2D||class{};export{e as Path2D,a as createCanvas,t as default};
2
+ //# sourceMappingURL=https-OLG7KUSR.js.map
package/dist/index.js CHANGED
@@ -1,4 +1,4 @@
1
- import{a as ge,b as he,c as me,d as fe}from"./chunk-Q7XPZMZA.js";import{a as N,b as c,c as V,d as F,e as ee,f as te,j as se,k as re,l as oe,m as ie,n as ae,r as a,s as ne,t as le}from"./chunk-O7IV7A6O.js";import{a as o,b,c as ye}from"./chunk-NQW6FFN7.js";import"./chunk-V6E2SSSW.js";import{a as Te}from"./chunk-2AB5L3Y2.js";import{a as Ce}from"./chunk-J7HWZNIP.js";import{a as Ae}from"./chunk-NEEWG3OP.js";import"./chunk-PUJYN435.js";import{a as u}from"./chunk-4ICUYKSR.js";import"./chunk-CWCS22CQ.js";import{a as ve,b as x}from"./chunk-GGERQ3CJ.js";import"./chunk-4GEMGDRU.js";import{a as I,b as R,c as k,e as D,f as E,g as _,k as d}from"./chunk-G5EUMLYT.js";import{a as Y}from"./chunk-KH5JE65X.js";import{a as X}from"./chunk-ULTSZWZO.js";import{a as O,b as P,c as w}from"./chunk-K4NR6OAC.js";import{d as $}from"./chunk-L4OVZN23.js";import{a as Z}from"./chunk-U3V3VZGO.js";import{a as Q}from"./chunk-6DSLE3AY.js";import{a as H}from"./chunk-5OTO5WFV.js";import{a as q}from"./chunk-O6FQFVKY.js";import{b as f}from"./chunk-WETG2JD7.js";import{a as g,b as ue,c as xe,d as h,e as m}from"./chunk-FAVTIE3M.js";import{a as be,b as Se,c as S}from"./chunk-MEE2NNYB.js";import{a as ce,b as pe,c as de,d as n}from"./chunk-YNY65JUJ.js";import{a as M,b as L,c as z,d as U,e as W,f as B,g as K,h as G,i as j,j as J}from"./chunk-ZT72PD2C.js";import{a as T}from"./chunk-FQRADJY6.js";import{a as C}from"./chunk-DIU5BGU5.js";import"./chunk-4C666HHU.js";var p=class extends b{#e=null;static properties={isOpen:{type:Boolean,state:!0},docId:{type:String,state:!0},docName:{type:String,state:!0},pages:{type:Array,state:!0},lang:{type:String,state:!0},step:{type:String,state:!0},progress:{type:Number,state:!0},statusMessage:{type:String,state:!0},resultText:{type:String,state:!0},confidence:{type:Number,state:!0},copied:{type:Boolean,state:!0}};createRenderRoot(){return this}disconnectedCallback(){super.disconnectedCallback(),this.#e&&(this.#e.abort(),this.#e=null),m(),this.isOpen=!1}constructor(){super(),this.isOpen=!1,this.docId="",this.docName="",this.pages=[],this.lang="eng",this.step="processing",this.progress=0,this.statusMessage="Starting OCR engine...",this.resultText="",this.confidence=0,this.copied=!1,this._pageIndex=null,this.#e=null}open(e,r,s,t="eng"){this._pageIndex=null,this._openInternal(e,r,s,t)}openPage(e,r,s,t,i="eng"){this._pageIndex=t,this._openInternal(e,r,[s],i)}_openInternal(e,r,s,t){if(this.#e&&(this.#e.abort(),this.#e=null),this.docId=e,this.docName=r||"Document",this.pages=s||[],this.lang=t,this.progress=0,this.resultText="",this.confidence=0,this.copied=!1,(this.pages||[]).filter(l=>l.src).length===0){this.step="empty",this.statusMessage="This document does not contain any image pages for text recognition.",this.isOpen=!0;return}this.step="processing",this.statusMessage=typeof window<"u"&&!window.Tesseract?"Downloading OCR engine...":"Starting OCR engine...",this.isOpen=!0,this.startOcr(t)}cancel=()=>{this.#e&&(this.#e.abort(),this.#e=null),this.close()};close=()=>{this.#e&&(this.#e.abort(),this.#e=null),this.isOpen=!1};async startOcr(e="eng"){this.#e&&(this.#e.abort(),this.#e=null),this.#e=new AbortController;let{signal:r}=this.#e;try{let s=await h(this.pages,{lang:e,abortSignal:r,onPageProgress:({overallProgress:t,message:i})=>{this.isOpen&&!r.aborted&&(this.progress=Math.round((t||0)*100),this.statusMessage=i)}});if(this.isOpen&&!r.aborted&&(this.step="done",this.resultText=s.combinedText||"",this.confidence=s.averageConfidence||0,n.success("Text recognition complete"),this.docId&&Array.isArray(s.pagesResults)))try{let t=await c.getDoc(this.docId);if(t&&Array.isArray(t.pages)){for(let i of s.pagesResults){let l=t.pages.find(A=>A.id===i.pageId)||t.pages[i.pageIndex];l&&(l.ocrText=i.text,l.ocrConfidence=i.confidence,l.ocrWords=i.words)}await c.saveDoc(this.docId,t)}}catch(t){console.warn("Could not persist OCR results to document:",t)}}catch(s){if(s.name==="AbortError"||r.aborted)return;console.error("Document OCR Error:",s),this.isOpen&&(this.step="error",this.statusMessage=s.message||"Text recognition failed",n.error(s.message||"Text recognition failed"))}finally{this.#e?.signal===r&&(this.#e=null)}}handleLangChange=e=>{let r=e.target.value;this.lang=r,this.step="processing",this.progress=0,this.statusMessage="Starting OCR engine with new language...",this.startOcr(r)};handleTextInput=e=>{this.resultText=e.target.value};copyText=async()=>{if(this.resultText)try{await navigator.clipboard.writeText(this.resultText),this.copied=!0,n.success("Copied text to clipboard"),setTimeout(()=>{this.copied=!1},2e3)}catch(e){console.error("Failed to copy text:",e),n.error("Failed to copy text to clipboard")}};downloadText=()=>{if(!this.resultText)return;let e=(this.docName||"document").replace(/[/\\?%*:|"<>]/g,"_"),r=new Blob([this.resultText],{type:"text/plain;charset=utf-8"}),s=URL.createObjectURL(r),t=document.createElement("a");t.href=s,t.download=`${e}-ocr.txt`,t.click(),URL.revokeObjectURL(s),n.success(`Exported OCR text (${e}-ocr.txt)`)};get _isSinglePage(){return this._pageIndex!==null}get _dialogLabel(){return this._isSinglePage?`Extract Text \u2014 ${this.docName} (Page ${this._pageIndex+1})`:`Extract All Text \u2014 ${this.docName}`}render(){return this.isOpen?o`
1
+ import{a as Ue,b as He,c as Me,d as ze}from"./chunk-Q3AWHANC.js";import{a as re,b as se,c as ie,d as ae,e as c,f as xe,g as ye,k as a,l as De,m as _e}from"./chunk-TK5N67RB.js";import{a as s,b as R,c as We}from"./chunk-NQW6FFN7.js";import{a as $,b as w,c as E,d as I}from"./chunk-2VH2NPXW.js";import{i as S,j as T,k as A,l as C,m as v,n as O,o as P}from"./chunk-VPSUKD6F.js";import{a as be,b as Se}from"./chunk-HCCNUPKB.js";import"./chunk-V2D55DVU.js";import{a as y}from"./chunk-GLY5CGCY.js";import"./chunk-CWCS22CQ.js";import{a as Ge,b as x}from"./chunk-NM4YYZYB.js";import"./chunk-V6E2SSSW.js";import{a as je}from"./chunk-T5CPA7B2.js";import{a as qe}from"./chunk-2AB5L3Y2.js";import{a as Ve}from"./chunk-NEEWG3OP.js";import"./chunk-PUJYN435.js";import{a as u}from"./chunk-4ICUYKSR.js";import{a as Ee}from"./chunk-PSGIWIRH.js";import{a as Oe,b as Pe,c as $e,d as we}from"./chunk-ZILTJGT2.js";import{a as ve}from"./chunk-5OTO5WFV.js";import{a as Ce}from"./chunk-O6FQFVKY.js";import"./chunk-4GEMGDRU.js";import{a as F,b as K,c as W,d as B,h as Q,i as G,j as V,k as j,l as q,m as J,n as Z,o as X,p as Y,r as ee,s as te,t as oe,x as p}from"./chunk-GU6OQMYK.js";import{a as Re}from"./chunk-KH5JE65X.js";import{a as Ie}from"./chunk-ULTSZWZO.js";import{a as H,b as M,c as z}from"./chunk-6QK7337A.js";import{a as L}from"./chunk-NNSM2I5L.js";import{d as U}from"./chunk-JIPKWRBK.js";import{a as N}from"./chunk-4D6GC55I.js";import{a as Ae}from"./chunk-U3V3VZGO.js";import{a as Te}from"./chunk-6DSLE3AY.js";import{a as m}from"./chunk-R6Q4OXDG.js";import"./chunk-SZHKZARU.js";import{a as g,b as Fe,c as Ke,d as f,e as h}from"./chunk-FAVTIE3M.js";import{a as Be,b as Qe,c as D}from"./chunk-PBF7V4Z6.js";import{a as ke,b as Ne,c as Le,d as n}from"./chunk-YNY65JUJ.js";import{a as ne,b as le,c as ce,d as de,e as pe,f as ge,g as fe,h as he,i as me,j as ue}from"./chunk-ZT72PD2C.js";import"./chunk-25WAHT3G.js";var d=class extends R{#e=null;static properties={isOpen:{type:Boolean,state:!0},docId:{type:String,state:!0},docName:{type:String,state:!0},pages:{type:Array,state:!0},lang:{type:String,state:!0},step:{type:String,state:!0},progress:{type:Number,state:!0},statusMessage:{type:String,state:!0},resultText:{type:String,state:!0},confidence:{type:Number,state:!0},copied:{type:Boolean,state:!0}};createRenderRoot(){return this}disconnectedCallback(){super.disconnectedCallback(),this.#e&&(this.#e.abort(),this.#e=null),h(),this.isOpen=!1}constructor(){super(),this.isOpen=!1,this.docId="",this.docName="",this.pages=[],this.lang="eng",this.step="processing",this.progress=0,this.statusMessage="Starting OCR engine...",this.resultText="",this.confidence=0,this.copied=!1,this._pageIndex=null,this.#e=null}open(e,r,o,t="eng"){this._pageIndex=null,this._openInternal(e,r,o,t)}openPage(e,r,o,t,i="eng"){this._pageIndex=t,this._openInternal(e,r,[o],i)}_openInternal(e,r,o,t){if(this.#e&&(this.#e.abort(),this.#e=null),this.docId=e,this.docName=r||"Document",this.pages=o||[],this.lang=t,this.progress=0,this.resultText="",this.confidence=0,this.copied=!1,(this.pages||[]).filter(l=>l.src).length===0){this.step="empty",this.statusMessage="This document does not contain any image pages for text recognition.",this.isOpen=!0;return}this.step="processing",this.statusMessage=typeof window<"u"&&!window.Tesseract?"Downloading OCR engine...":"Starting OCR engine...",this.isOpen=!0,this.startOcr(t)}cancel=()=>{this.#e&&(this.#e.abort(),this.#e=null),this.close()};close=()=>{this.#e&&(this.#e.abort(),this.#e=null),this.isOpen=!1};async startOcr(e="eng"){this.#e&&(this.#e.abort(),this.#e=null),this.#e=new AbortController;let{signal:r}=this.#e;try{let o=await f(this.pages,{lang:e,abortSignal:r,onPageProgress:({overallProgress:t,message:i})=>{this.isOpen&&!r.aborted&&(this.progress=Math.round((t||0)*100),this.statusMessage=i)}});if(this.isOpen&&!r.aborted&&(this.step="done",this.resultText=o.combinedText||"",this.confidence=o.averageConfidence||0,n.success("Text recognition complete"),this.docId&&Array.isArray(o.pagesResults)))try{let t=await c.getDoc(this.docId);if(t&&Array.isArray(t.pages)){for(let i of o.pagesResults){let l=t.pages.find(k=>k.id===i.pageId)||t.pages[i.pageIndex];l&&(l.ocrText=i.text,l.ocrConfidence=i.confidence,l.ocrWords=i.words)}await c.saveDoc(this.docId,t)}}catch(t){console.warn("Could not persist OCR results to document:",t)}}catch(o){if(o.name==="AbortError"||r.aborted)return;console.error("Document OCR Error:",o),this.isOpen&&(this.step="error",this.statusMessage=o.message||"Text recognition failed",n.error(o.message||"Text recognition failed"))}finally{this.#e?.signal===r&&(this.#e=null)}}handleLangChange=e=>{let r=e.target.value;this.lang=r,this.step="processing",this.progress=0,this.statusMessage="Starting OCR engine with new language...",this.startOcr(r)};handleTextInput=e=>{this.resultText=e.target.value};copyText=async()=>{if(this.resultText)try{await navigator.clipboard.writeText(this.resultText),this.copied=!0,n.success("Copied text to clipboard"),setTimeout(()=>{this.copied=!1},2e3)}catch(e){console.error("Failed to copy text:",e),n.error("Failed to copy text to clipboard")}};downloadText=()=>{if(!this.resultText)return;let e=(this.docName||"document").replace(/[/\\?%*:|"<>]/g,"_"),r=new Blob([this.resultText],{type:"text/plain;charset=utf-8"}),o=URL.createObjectURL(r),t=document.createElement("a");t.href=o,t.download=`${e}-ocr.txt`,t.click(),URL.revokeObjectURL(o),n.success(`Exported OCR text (${e}-ocr.txt)`)};get _isSinglePage(){return this._pageIndex!==null}get _dialogLabel(){return this._isSinglePage?`Extract Text \u2014 ${this.docName} (Page ${this._pageIndex+1})`:`Extract All Text \u2014 ${this.docName}`}render(){return this.isOpen?s`
2
2
  <sl-dialog
3
3
  label="${this._dialogLabel}"
4
4
  open
@@ -12,10 +12,10 @@ import{a as ge,b as he,c as me,d as fe}from"./chunk-Q7XPZMZA.js";import{a as N,b
12
12
  @sl-change=${this.handleLangChange}
13
13
  style="min-width: 180px;"
14
14
  >
15
- ${g.map(e=>o`<sl-option value=${e.code}>${e.flag} ${e.label}</sl-option>`)}
15
+ ${g.map(e=>s`<sl-option value=${e.code}>${e.flag} ${e.label}</sl-option>`)}
16
16
  </sl-select>
17
17
 
18
- ${this.step==="done"?o`
18
+ ${this.step==="done"?s`
19
19
  <sl-badge
20
20
  variant=${this.confidence>=75?"success":this.confidence>=50?"warning":"danger"}
21
21
  >
@@ -24,7 +24,7 @@ import{a as ge,b as he,c as me,d as fe}from"./chunk-Q7XPZMZA.js";import{a as N,b
24
24
  `:""}
25
25
  </div>
26
26
 
27
- ${this.step==="empty"?o`
27
+ ${this.step==="empty"?s`
28
28
  <div style="padding: 2.5rem 1rem; text-align: center; color: #64748b;">
29
29
  <sl-icon name="file-earmark-x" style="font-size: 2.5rem; margin-bottom: 0.5rem; color: #94a3b8;"></sl-icon>
30
30
  <p style="margin: 0; font-size: 1rem; color: #334155; font-weight: 500;">${this.statusMessage}</p>
@@ -32,7 +32,7 @@ import{a as ge,b as he,c as me,d as fe}from"./chunk-Q7XPZMZA.js";import{a as N,b
32
32
  </div>
33
33
  `:""}
34
34
 
35
- ${this.step==="processing"?o`
35
+ ${this.step==="processing"?s`
36
36
  <div style="padding: 2.5rem 1rem; text-align: center;">
37
37
  <div style="font-size: 1.1rem; color: #0284c7; font-weight: 600; margin-bottom: 1rem;">
38
38
  ${this.statusMessage}
@@ -44,14 +44,14 @@ import{a as ge,b as he,c as me,d as fe}from"./chunk-Q7XPZMZA.js";import{a as N,b
44
44
  </div>
45
45
  `:""}
46
46
 
47
- ${this.step==="error"?o`
47
+ ${this.step==="error"?s`
48
48
  <div style="padding: 2rem; text-align: center; color: #ef4444;">
49
49
  <sl-icon name="x-circle-fill" style="font-size: 2rem;"></sl-icon>
50
50
  <p style="margin-top: 0.5rem;">${this.statusMessage}</p>
51
51
  </div>
52
52
  `:""}
53
53
 
54
- ${this.step==="done"?o`
54
+ ${this.step==="done"?s`
55
55
  <div>
56
56
  <sl-textarea
57
57
  rows="14"
@@ -62,18 +62,18 @@ import{a as ge,b as he,c as me,d as fe}from"./chunk-Q7XPZMZA.js";import{a as N,b
62
62
  </div>
63
63
  `:""}
64
64
 
65
- ${this.step==="processing"?o`
65
+ ${this.step==="processing"?s`
66
66
  <sl-button slot="footer" variant="default" @click=${this.cancel}>
67
67
  <sl-icon slot="prefix" name="x-lg"></sl-icon>
68
68
  Cancel
69
69
  </sl-button>
70
70
  `:""}
71
- ${this.step==="empty"||this.step==="error"?o`
71
+ ${this.step==="empty"||this.step==="error"?s`
72
72
  <sl-button slot="footer" variant="default" @click=${this.close}>
73
73
  Close
74
74
  </sl-button>
75
75
  `:""}
76
- ${this.step==="done"?o`
76
+ ${this.step==="done"?s`
77
77
  <sl-button slot="footer" variant="default" @click=${this.close}>
78
78
  Close
79
79
  </sl-button>
@@ -87,5 +87,5 @@ import{a as ge,b as he,c as me,d as fe}from"./chunk-Q7XPZMZA.js";import{a as N,b
87
87
  </sl-button>
88
88
  `:""}
89
89
  </sl-dialog>
90
- `:""}};customElements.define("copio-doc-ocr-dialog",p);var y=class{constructor(e=null){this.key=e}setKey(e){this.key=e}getKey(){return this.key}isValid(){return!!this.key}getTier(){return this.key?this.key.startsWith("pro_")?"pro":this.key.startsWith("ent_")?"enterprise":"commercial":"community"}};a("export",S);a("ocr",new u);a("sync",f);a("pdf",new x);a("imageProcessor",new d);export{V as BUILD_DATE,ie as COPIO_EVENTS,d as Canvas2DAdapter,p as CopioDocOcrDialog,le as CopioEngine,fe as CopioScanner,ye as CopioSyncDialog,N as DocRepository,re as Document,X as ImageProcessorPort,$ as IndexedDbStorageAdapter,y as LicenseManager,T as MemoryStorageAdapter,Y as NullImageProcessorAdapter,Z as NullOcrAdapter,H as NullPdfAdapter,Te as NullSyncAdapter,Q as OcrPort,P as OpfsStorageAdapter,se as Page,x as PdfKitAdapter,q as PdfPort,Ce as PeerJsAdapter,g as SUPPORTED_LANGUAGES,oe as ScanSession,C as StoragePort,f as SyncManager,Ae as SyncPort,u as TesseractWasmAdapter,F as VERSION,me as adoptScannerStyles,de as clearNotifications,w as createDefaultAdapter,ae as dispatchCopioEvent,c as docRepository,Se as exportDocumentAsImages,be as exportDocumentAsPdf,I as extractExif,k as fileToBase64,M as getAssetBase,pe as getContainer,_ as getCroppedSrc,ue as getOcrWorker,ne as getRegisteredService,he as getScannerStyleSheet,te as hasActiveEdits,W as loadCropper,K as loadJsZip,B as loadPdfKit,G as loadPeerJs,j as loadQrCode,U as loadScript,J as loadTesseract,ee as normalizeEditStack,n as notify,O as probeOpfs,R as randomId,h as recognizeDocumentPages,xe as recognizeImageText,a as registerService,ve as renderPdfPagesToDataUrls,z as resolveAssetUrl,E as rotateSrc,ge as scannerCss,L as setAssetBase,ce as setContainer,m as terminateOcrWorker,D as thresholdSrc};
90
+ `:""}};customElements.define("copio-doc-ocr-dialog",d);var b=class{constructor(e=null){this.key=e}setKey(e){this.key=e}getKey(){return this.key}isValid(){return!!this.key}getTier(){return this.key?this.key.startsWith("pro_")?"pro":this.key.startsWith("ent_")?"enterprise":"commercial":"community"}};a("export",D);a("ocr",new u);a("sync",m);a("pdf",new x);a("imageProcessor",new p);a("edge",new y);export{xe as BUILD_DATE,be as COPIO_EVENTS,re as CURRENT_SCHEMA_VERSION,p as Canvas2DAdapter,d as CopioDocOcrDialog,_e as CopioEngine,I as CopioHandoff,ze as CopioScanner,We as CopioSyncDialog,Oe as DEFAULT_FALLBACK_QUAD,se as DEFAULT_MIGRATIONS,ae as DocRepository,q as Document,we as EdgeDetectorPort,P as HandoffSession,Ie as ImageProcessorPort,U as IndexedDbStorageAdapter,b as LicenseManager,O as LoopbackTransport,L as MemoryStorageAdapter,ie as MigrationRunner,Ee as NullEdgeDetectorAdapter,Re as NullImageProcessorAdapter,Ae as NullOcrAdapter,ve as NullPdfAdapter,qe as NullSyncAdapter,Te as OcrPort,M as OpfsStorageAdapter,j as Page,x as PdfKitAdapter,Ce as PdfPort,je as PeerJsAdapter,g as SUPPORTED_LANGUAGES,J as ScanSession,y as ScanicWasmEdgeAdapter,N as StoragePort,m as SyncManager,Ve as SyncPort,u as TesseractWasmAdapter,ye as VERSION,E as adoptHandoffStyles,Me as adoptScannerStyles,C as buildHandoffUrl,Le as clearNotifications,Pe as cloneQuad,z as createDefaultAdapter,K as cropRectToQuad,A as decodeSessionToken,Se as dispatchCopioEvent,c as docRepository,T as encodeSessionToken,Qe as exportDocumentAsImages,Be as exportDocumentAsPdf,Z as extractExif,Y as fileToBase64,ne as getAssetBase,Ne as getContainer,oe as getCroppedSrc,w as getHandoffStyleSheet,Fe as getOcrWorker,De as getRegisteredService,He as getScannerStyleSheet,$ as handoffCss,B as hasActiveEdits,pe as loadCropper,fe as loadJsZip,ge as loadPdfKit,he as loadPeerJs,me as loadQrCode,de as loadScript,ue as loadTesseract,W as normalizeEditStack,F as normalizeQuad,n as notify,v as parseHandoffUrl,H as probeOpfs,G as quadOriginalToRotated,V as quadRotatedToOriginal,$e as quadToCropRect,S as randomHandoffId,X as randomId,f as recognizeDocumentPages,Ke as recognizeImageText,a as registerService,Ge as renderPdfPagesToDataUrls,ce as resolveAssetUrl,Q as rotateQuad,te as rotateSrc,Ue as scannerCss,le as setAssetBase,ke as setContainer,h as terminateOcrWorker,ee as thresholdSrc};
91
91
  //# sourceMappingURL=index.js.map
package/dist/ocr.js CHANGED
@@ -1,2 +1,2 @@
1
- import{a,b,c,d,e}from"./chunk-FAVTIE3M.js";import"./chunk-YNY65JUJ.js";import"./chunk-ZT72PD2C.js";import"./chunk-4C666HHU.js";export{a as SUPPORTED_LANGUAGES,b as getOcrWorker,d as recognizeDocumentPages,c as recognizeImageText,e as terminateOcrWorker};
1
+ import{a,b,c,d,e}from"./chunk-FAVTIE3M.js";import"./chunk-YNY65JUJ.js";import"./chunk-ZT72PD2C.js";import"./chunk-25WAHT3G.js";export{a as SUPPORTED_LANGUAGES,b as getOcrWorker,d as recognizeDocumentPages,c as recognizeImageText,e as terminateOcrWorker};
2
2
  //# sourceMappingURL=ocr.js.map
@@ -0,0 +1,2 @@
1
+ import"./chunk-25WAHT3G.js";var t={},a=()=>null,e=globalThis.Path2D||class{};export{e as Path2D,a as createCanvas,t as default};
2
+ //# sourceMappingURL=path2d-HD3LU76S.js.map
@@ -0,0 +1,2 @@
1
+ import"./chunk-25WAHT3G.js";var s=224,E=[.485,.456,.406],I=[.229,.224,.225],A=["topLeft","topRight","bottomRight","bottomLeft"],T=null,x=new Map,v=null;async function S(){return T||(T=import("./scanic-ort.wasm.min-MU4NYSP2.js").catch(n=>{throw T=null,new Error(`scanic: failed to load the ML runtime (onnxruntime-web). It is bundled with scanic's ESM build; if you use the UMD/CommonJS build, install it alongside scanic: \`npm install onnxruntime-web@1.27.x\`. (original error: ${n?.message||n})`)})),T}async function U(n){let m=n.assetBaseUrl?(c=n.assetBaseUrl).endsWith("/")?c:`${c}/`:new URL("./scanic-ml/",import.meta.url).href;var c;let b=n.modelUrl||`${m}doccornernet_lean.ort`,M=n.wasmPaths||m,l=(p=n.numThreads!==void 0?n.numThreads:n.threaded?4:(function(){if(typeof SharedArrayBuffer>"u"||(typeof window<"u"||typeof importScripts=="function")&&!globalThis.crossOriginIsolated)return 1;let a=globalThis.navigator?.hardwareConcurrency||globalThis.process?.availableParallelism?.()||4;return Math.max(2,Math.min(a,4))})(),v===null||p===v?p:v);var p;let L=n.modelFetchTimeoutMs!==void 0?n.modelFetchTimeoutMs:3e4,g=`${b}|${M}|${l}`;if(x.has(g))return x.get(g);let D=(async()=>{let a=await S();a.env.wasm.wasmPaths=M,a.env.wasm.numThreads=l,a.env.wasm.proxy=!1;let C=n.modelBytes||await(async function(u,e){let o=typeof AbortController<"u"&&e>0?new AbortController:null,d=o?setTimeout(()=>o.abort(),e):null;try{let t=await fetch(u,o?{signal:o.signal}:void 0);if(!t.ok)throw new Error(`scanic: failed to fetch the ML model from ${u} (HTTP ${t.status} ${t.statusText})`);return new Uint8Array(await t.arrayBuffer())}catch(t){throw o?.signal.aborted?new Error(`scanic: timed out after ${e}ms fetching the ML model from ${u}`,{cause:t}):t instanceof Error&&t.message.startsWith("scanic:")?t:new Error(`scanic: failed to fetch the ML model from ${u} (${t?.message||t})`,{cause:t})}finally{d&&clearTimeout(d)}})(b,L);return{ort:a,session:await a.InferenceSession.create(C,{executionProviders:["wasm"],graphOptimizationLevel:"all"})}})(),$=v;v=l,x.set(g,D);try{return await D}catch(a){throw x.delete(g),x.size===0&&(v=$),a}}async function F(n,m={}){let c=[],{width:b,height:M}=(function(e){if(!e)throw new Error("No image provided");let o=e.naturalWidth||e.videoWidth||e.displayWidth||e.width,d=e.naturalHeight||e.videoHeight||e.displayHeight||e.height;if(!(o>0&&d>0))throw new Error("scanic: the image has no pixels yet. Wait for an <img> to load, or for a <video> to fire loadedmetadata.");return{width:o,height:d}})(n),l=(typeof performance<"u"?performance:Date).now(),{session:p}=await U(m);c.push({step:"ML Session Load",ms:((typeof performance<"u"?performance:Date).now()-l).toFixed(2)});let L=await S();l=(typeof performance<"u"?performance:Date).now();let g=m.inputData||(function(e,o,d){let t=typeof OffscreenCanvas<"u",h=t?new OffscreenCanvas(s,s):document.createElement("canvas");t||(h.width=s,h.height=s);let f=h.getContext("2d",{willReadFrequently:!0});if(f.imageSmoothingEnabled=!0,f.imageSmoothingQuality="medium",e&&typeof e.width=="number"&&typeof e.height=="number"&&e.data){let r=t?new OffscreenCanvas(e.width,e.height):document.createElement("canvas");t||(r.width=e.width,r.height=e.height);let y=typeof ImageData<"u"&&!(e instanceof ImageData)?new ImageData(e.data instanceof Uint8ClampedArray?e.data:new Uint8ClampedArray(e.data),e.width,e.height):e;r.getContext("2d").putImageData(y,0,0),f.drawImage(r,0,0,e.width,e.height,0,0,s,s)}else f.drawImage(e,0,0,o,d,0,0,s,s);let{data:w}=f.getImageData(0,0,s,s),i=new Float32Array(150528);for(let r=0,y=0;r<w.length;r+=4,y+=3)i[y]=(w[r]/255-E[0])/I[0],i[y+1]=(w[r+1]/255-E[1])/I[1],i[y+2]=(w[r+2]/255-E[2])/I[2];return i})(n,b,M),D=new L.Tensor("float32",g,[1,s,s,3]);c.push({step:"ML Preprocess",ms:((typeof performance<"u"?performance:Date).now()-l).toFixed(2)}),l=(typeof performance<"u"?performance:Date).now();let $=await p.run({[p.inputNames[0]]:D});c.push({step:"ML Inference",ms:((typeof performance<"u"?performance:Date).now()-l).toFixed(2)});let a=(function(e,o,d){let t=null,h=null;for(let i in e){let r=e[i].data;r.length===8?t=r:r.length===1&&(h=r[0])}if(!t)return null;let f={};for(let i=0;i<4;i++)f[A[i]]={x:t[2*i]*o,y:t[2*i+1]*d};return{corners:f,score:h===null?null:(w=h,1/(1+Math.exp(-w)))};var w})($,b,M);if(!a)return{success:!1,corners:null,confidence:null,score:null,message:"ML model produced no coordinates",timings:c};let C=m.minScore!==void 0?m.minScore:.5,u=a.score===null||a.score>=C;return{success:u,corners:a.corners,confidence:a.score,score:a.score,message:u?"Document detected (ml)":"No confident document (ml)",timings:c}}async function P(n={}){await U(n)}export{F as detectDocumentMl,P as initializeMl};
2
+ //# sourceMappingURL=scanic-mlDetector-BCSVQYFV.js.map
@@ -0,0 +1,2 @@
1
+ import{a as z}from"./chunk-25WAHT3G.js";var xe,de,W,Re,wt,Pt,_t,Pe,I,R,$t,Bt,be,Nt,Mt,St,kt,Dt,K,ye,_e,Gt,Ft,jt,$,k,He,$e,ae,oe,ie,se,Vt,Wt,ee=(e=>typeof z<"u"?z:typeof Proxy<"u"?new Proxy(e,{get:(t,r)=>(typeof z<"u"?z:t)[r]}):e)(function(e){if(typeof z<"u")return z.apply(this,arguments);throw Error('Calling `require` for "'+e+"\" in an environment that doesn't expose the `require` function. See https://rolldown.rs/in-depth/bundling-cjs#require-external-modules for more details.")}),ze=Object.defineProperty,Or=Object.getOwnPropertyDescriptor,Ur=Object.getOwnPropertyNames,Ir=Object.prototype.hasOwnProperty,Lr=(xe=function(e){if(typeof ee<"u")return ee.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')},typeof ee<"u"?ee:typeof Proxy<"u"?new Proxy(xe,{get:(e,t)=>(typeof ee<"u"?ee:e)[t]}):xe),b=(e,t)=>()=>(e&&(t=e(e=0)),t),Ze=(e,t)=>{for(var r in t)ze(e,r,{get:t[r],enumerable:!0})},Ht=e=>((t,r,n,a)=>{if(r&&typeof r=="object"||typeof r=="function")for(let i of Ur(r))!Ir.call(t,i)&&i!==n&&ze(t,i,{get:()=>r[i],enumerable:!(a=Or(r,i))||a.enumerable});return t})(ze({},"__esModule",{value:!0}),e),zt=b(()=>{de=new Map,W=[],Re=(e,t,r)=>{if(t&&typeof t.init=="function"&&typeof t.createInferenceSessionHandler=="function"){let n=de.get(e);if(n===void 0)de.set(e,{backend:t,priority:r});else{if(n.priority>r)return;if(n.priority===r&&n.backend!==t)throw new Error(`cannot register backend "${e}" using priority ${r}`)}if(r>=0){let a=W.indexOf(e);a!==-1&&W.splice(a,1);for(let i=0;i<W.length;i++)if(de.get(W[i]).priority<=r)return void W.splice(i,0,e);W.push(e)}return}throw new TypeError("not a valid backend")},wt=async e=>{let t=de.get(e);if(!t)return"backend not found.";if(t.initialized)return t.backend;if(t.aborted)return t.error;{let r=!!t.initPromise;try{return r||(t.initPromise=t.backend.init(e)),await t.initPromise,t.initialized=!0,t.backend}catch(n){return r||(t.error=`${n}`,t.aborted=!0),t.error}finally{delete t.initPromise}}},Pt=async e=>{let t,r=e.executionProviders||[],n=r.map(s=>typeof s=="string"?s:s.name),a=n.length===0?W:n,i=[],o=new Set;for(let s of a){let l=await wt(s);typeof l=="string"?i.push({name:s,err:l}):(t||(t=l),t===l&&o.add(s))}if(!t)throw new Error(`no available backend found. ERR: ${i.map(s=>`[${s.name}] ${s.err}`).join(", ")}`);for(let{name:s,err:l}of i)n.includes(s);let u=r.filter(s=>o.has(typeof s=="string"?s:s.name));return[t,new Proxy(e,{get:(s,l)=>l==="executionProviders"?u:Reflect.get(s,l)})]}}),xr=b(()=>{zt()}),Pr=b(()=>{_t="1.27.0"}),qt=b(()=>{Pr(),Pe="warning",I={wasm:{},webgl:{},webgpu:{},versions:{common:_t},set logLevel(e){if(e!==void 0){if(typeof e!="string"||["verbose","info","warning","error","fatal"].indexOf(e)===-1)throw new Error(`Unsupported logging level: ${e}`);Pe=e}},get logLevel(){return Pe}},Object.defineProperty(I,"logLevel",{enumerable:!0})}),_r=b(()=>{qt(),R=I}),$r=b(()=>{$t=(e,t)=>{let r=typeof document<"u"?document.createElement("canvas"):new OffscreenCanvas(1,1);r.width=e.dims[3],r.height=e.dims[2];let n=r.getContext("2d");if(n!=null){let a,i;t?.tensorLayout!==void 0&&t.tensorLayout==="NHWC"?(a=e.dims[2],i=e.dims[3]):(a=e.dims[3],i=e.dims[2]);let o,u,s=t?.format!==void 0?t.format:"RGB",l=t?.norm;l===void 0||l.mean===void 0?o=[255,255,255,255]:typeof l.mean=="number"?o=[l.mean,l.mean,l.mean,l.mean]:(o=[l.mean[0],l.mean[1],l.mean[2],0],l.mean[3]!==void 0&&(o[3]=l.mean[3])),l===void 0||l.bias===void 0?u=[0,0,0,0]:typeof l.bias=="number"?u=[l.bias,l.bias,l.bias,l.bias]:(u=[l.bias[0],l.bias[1],l.bias[2],0],l.bias[3]!==void 0&&(u[3]=l.bias[3]));let p=i*a,f=0,d=p,h=2*p,y=-1;s==="RGBA"?(f=0,d=p,h=2*p,y=3*p):s==="RGB"?(f=0,d=p,h=2*p):s==="RBG"&&(f=0,h=p,d=2*p);for(let E=0;E<i;E++)for(let C=0;C<a;C++){let w=(e.data[f++]-u[0])*o[0],c=(e.data[d++]-u[1])*o[1],g=(e.data[h++]-u[2])*o[2],A=y===-1?255:(e.data[y++]-u[3])*o[3];n.fillStyle="rgba("+w+","+c+","+g+","+A+")",n.fillRect(C,E,1,1)}if("toDataURL"in r)return r.toDataURL();throw new Error("toDataURL is not supported")}throw new Error("Can not access image data")},Bt=(e,t)=>{let r,n=typeof document<"u"?document.createElement("canvas").getContext("2d"):new OffscreenCanvas(1,1).getContext("2d");if(n==null)throw new Error("Can not access image data");{let a,i,o;t?.tensorLayout!==void 0&&t.tensorLayout==="NHWC"?(a=e.dims[2],i=e.dims[1],o=e.dims[3]):(a=e.dims[3],i=e.dims[2],o=e.dims[1]);let u,s,l=t!==void 0&&t.format!==void 0?t.format:"RGB",p=t?.norm;p===void 0||p.mean===void 0?u=[255,255,255,255]:typeof p.mean=="number"?u=[p.mean,p.mean,p.mean,p.mean]:(u=[p.mean[0],p.mean[1],p.mean[2],255],p.mean[3]!==void 0&&(u[3]=p.mean[3])),p===void 0||p.bias===void 0?s=[0,0,0,0]:typeof p.bias=="number"?s=[p.bias,p.bias,p.bias,p.bias]:(s=[p.bias[0],p.bias[1],p.bias[2],0],p.bias[3]!==void 0&&(s[3]=p.bias[3]));let f=i*a;if(t!==void 0&&(t.format!==void 0&&o===4&&t.format!=="RGBA"||o===3&&t.format!=="RGB"&&t.format!=="BGR"))throw new Error("Tensor format doesn't match input tensor dims");let d=4,h=0,y=1,E=2,C=3,w=0,c=f,g=2*f,A=-1;l==="RGBA"?(w=0,c=f,g=2*f,A=3*f):l==="RGB"?(w=0,c=f,g=2*f):l==="RBG"&&(w=0,g=f,c=2*f),r=n.createImageData(a,i);for(let L=0;L<i*a;h+=d,y+=d,E+=d,C+=d,L++)r.data[h]=(e.data[w++]-s[0])*u[0],r.data[y]=(e.data[c++]-s[1])*u[1],r.data[E]=(e.data[g++]-s[2])*u[2],r.data[C]=A===-1?255:(e.data[A++]-s[3])*u[3]}return r}}),Br=b(()=>{Je(),be=(e,t)=>{if(e===void 0)throw new Error("Image buffer must be defined");if(t.height===void 0||t.width===void 0)throw new Error("Image height and width must be defined");if(t.tensorLayout==="NHWC")throw new Error("NHWC Tensor layout is not supported yet");let r,n,{height:a,width:i}=t,o=t.norm??{mean:255,bias:0};r=typeof o.mean=="number"?[o.mean,o.mean,o.mean,o.mean]:[o.mean[0],o.mean[1],o.mean[2],o.mean[3]??255],n=typeof o.bias=="number"?[o.bias,o.bias,o.bias,o.bias]:[o.bias[0],o.bias[1],o.bias[2],o.bias[3]??0];let u=t.format!==void 0?t.format:"RGBA",s=t.tensorFormat!==void 0&&t.tensorFormat!==void 0?t.tensorFormat:"RGB",l=a*i,p=s==="RGBA"?new Float32Array(4*l):new Float32Array(3*l),f=4,d=0,h=1,y=2,E=3,C=0,w=l,c=2*l,g=-1;u==="RGB"&&(f=3,d=0,h=1,y=2,E=-1),s==="RGBA"?g=3*l:s==="RBG"?(C=0,c=l,w=2*l):s==="BGR"&&(c=0,w=l,C=2*l);for(let A=0;A<l;A++,d+=f,y+=f,h+=f,E+=f)p[C++]=(e[d]+n[0])/r[0],p[w++]=(e[h]+n[1])/r[1],p[c++]=(e[y]+n[2])/r[2],g!==-1&&E!==-1&&(p[g++]=(e[E]+n[3])/r[3]);return new $("float32",p,s==="RGBA"?[1,4,a,i]:[1,3,a,i])},Nt=async(e,t)=>{let r,n=typeof HTMLImageElement<"u"&&e instanceof HTMLImageElement,a=typeof ImageData<"u"&&e instanceof ImageData,i=typeof ImageBitmap<"u"&&e instanceof ImageBitmap,o=typeof e=="string",u=t??{},s=()=>{if(typeof document<"u")return document.createElement("canvas");if(typeof OffscreenCanvas<"u")return new OffscreenCanvas(1,1);throw new Error("Canvas is not supported")},l=p=>typeof HTMLCanvasElement<"u"&&p instanceof HTMLCanvasElement||p instanceof OffscreenCanvas?p.getContext("2d"):null;if(n){let p=s();p.width=e.width,p.height=e.height;let f=l(p);if(f==null)throw new Error("Can not access image data");{let d=e.height,h=e.width;if(t!==void 0&&t.resizedHeight!==void 0&&t.resizedWidth!==void 0&&(d=t.resizedHeight,h=t.resizedWidth),t!==void 0){if(u=t,t.tensorFormat!==void 0)throw new Error("Image input config format must be RGBA for HTMLImageElement");u.tensorFormat="RGBA",u.height=d,u.width=h}else u.tensorFormat="RGBA",u.height=d,u.width=h;f.drawImage(e,0,0),r=f.getImageData(0,0,h,d).data}}else{if(!a){if(i){if(t===void 0)throw new Error("Please provide image config with format for Imagebitmap");let p=s();p.width=e.width,p.height=e.height;let f=l(p);if(f!=null){let d=e.height,h=e.width;return f.drawImage(e,0,0,h,d),r=f.getImageData(0,0,h,d).data,u.height=d,u.width=h,be(r,u)}throw new Error("Can not access image data")}if(o)return new Promise((p,f)=>{let d=s(),h=l(d);if(!e||!h)return f();let y=new Image;y.crossOrigin="Anonymous",y.src=e,y.onload=()=>{d.width=y.width,d.height=y.height,h.drawImage(y,0,0,d.width,d.height);let E=h.getImageData(0,0,d.width,d.height);u.height=d.height,u.width=d.width,p(be(E.data,u))}});throw new Error("Input data provided is not supported - aborted tensor creation")}{let p,f;if(t!==void 0&&t.resizedWidth!==void 0&&t.resizedHeight!==void 0?(p=t.resizedHeight,f=t.resizedWidth):(p=e.height,f=e.width),t!==void 0&&(u=t),u.format="RGBA",u.height=p,u.width=f,t!==void 0){let d=s();d.width=f,d.height=p;let h=l(d);if(h==null)throw new Error("Can not access image data");h.putImageData(e,0,0),r=h.getImageData(0,0,f,p).data}else r=e.data}}if(r!==void 0)return be(r,u);throw new Error("Input data provided is not supported - aborted tensor creation")},Mt=(e,t)=>{let{width:r,height:n,download:a,dispose:i}=t;return new $({location:"texture",type:"float32",texture:e,dims:[1,n,r,4],download:a,dispose:i})},St=(e,t)=>{let{dataType:r,dims:n,download:a,dispose:i}=t;return new $({location:"gpu-buffer",type:r??"float32",gpuBuffer:e,dims:n,download:a,dispose:i})},kt=(e,t)=>{let{dataType:r,dims:n,download:a,dispose:i}=t;return new $({location:"ml-tensor",type:r??"float32",mlTensor:e,dims:n,download:a,dispose:i})},Dt=(e,t,r)=>new $({location:"cpu-pinned",type:e,data:t,dims:r??[t.length]})}),Nr=b(()=>{K=new Map([["float32",Float32Array],["uint8",Uint8Array],["int8",Int8Array],["uint16",Uint16Array],["int16",Int16Array],["int32",Int32Array],["bool",Uint8Array],["float64",Float64Array],["uint32",Uint32Array],["int4",Uint8Array],["uint4",Uint8Array]]),ye=new Map([[Float32Array,"float32"],[Uint8Array,"uint8"],[Int8Array,"int8"],[Uint16Array,"uint16"],[Int16Array,"int16"],[Int32Array,"int32"],[Float64Array,"float64"],[Uint32Array,"uint32"]]),_e=!1,Gt=()=>{if(!_e){_e=!0;let e=typeof BigInt64Array<"u"&&BigInt64Array.from,t=typeof BigUint64Array<"u"&&BigUint64Array.from,r=globalThis.Float16Array,n=typeof r<"u"&&r.from;e&&(K.set("int64",BigInt64Array),ye.set(BigInt64Array,"int64")),t&&(K.set("uint64",BigUint64Array),ye.set(BigUint64Array,"uint64")),n?(K.set("float16",r),ye.set(r,"float16")):K.set("float16",Uint16Array)}}}),Mr=b(()=>{Je(),Ft=e=>{let t=1;for(let r=0;r<e.length;r++){let n=e[r];if(typeof n!="number"||!Number.isSafeInteger(n))throw new TypeError(`dims[${r}] must be an integer, got: ${n}`);if(n<0)throw new RangeError(`dims[${r}] must be a non-negative integer, got: ${n}`);t*=n}return t},jt=(e,t)=>{switch(e.location){case"cpu":return new $(e.type,e.data,t);case"cpu-pinned":return new $({location:"cpu-pinned",data:e.data,type:e.type,dims:t});case"texture":return new $({location:"texture",texture:e.texture,type:e.type,dims:t});case"gpu-buffer":return new $({location:"gpu-buffer",gpuBuffer:e.gpuBuffer,type:e.type,dims:t});case"ml-tensor":return new $({location:"ml-tensor",mlTensor:e.mlTensor,type:e.type,dims:t});default:throw new Error(`tensorReshape: tensor location ${e.location} is not supported`)}}}),Je=b(()=>{$r(),Br(),Nr(),Mr(),$=class{constructor(e,t,r){let n,a;if(Gt(),typeof e=="object"&&"location"in e)switch(this.dataLocation=e.location,n=e.type,a=e.dims,e.location){case"cpu-pinned":{let o=K.get(n);if(!o)throw new TypeError(`unsupported type "${n}" to create tensor from pinned buffer`);if(!(e.data instanceof o))throw new TypeError(`buffer should be of type ${o.name}`);this.cpuData=e.data;break}case"texture":if(n!=="float32")throw new TypeError(`unsupported type "${n}" to create tensor from texture`);this.gpuTextureData=e.texture,this.downloader=e.download,this.disposer=e.dispose;break;case"gpu-buffer":if(n!=="float32"&&n!=="float16"&&n!=="int32"&&n!=="int64"&&n!=="uint32"&&n!=="uint8"&&n!=="bool"&&n!=="uint4"&&n!=="int4")throw new TypeError(`unsupported type "${n}" to create tensor from gpu buffer`);this.gpuBufferData=e.gpuBuffer,this.downloader=e.download,this.disposer=e.dispose;break;case"ml-tensor":if(n!=="float32"&&n!=="float16"&&n!=="int32"&&n!=="int64"&&n!=="uint32"&&n!=="uint64"&&n!=="int8"&&n!=="uint8"&&n!=="bool"&&n!=="uint4"&&n!=="int4")throw new TypeError(`unsupported type "${n}" to create tensor from MLTensor`);this.mlTensorData=e.mlTensor,this.downloader=e.download,this.disposer=e.dispose;break;default:throw new Error(`Tensor constructor: unsupported location '${this.dataLocation}'`)}else{let o,u;if(typeof e=="string")if(n=e,u=r,e==="string"){if(!Array.isArray(t))throw new TypeError("A string tensor's data must be a string array.");o=t}else{let s=K.get(e);if(s===void 0)throw new TypeError(`Unsupported tensor type: ${e}.`);if(Array.isArray(t)){if(e==="float16"&&s===Uint16Array||e==="uint4"||e==="int4")throw new TypeError(`Creating a ${e} tensor from number array is not supported. Please use ${s.name} as data.`);o=e==="uint64"||e==="int64"?s.from(t,BigInt):s.from(t)}else if(t instanceof s)o=t;else if(t instanceof Uint8ClampedArray){if(e!=="uint8")throw new TypeError("A Uint8ClampedArray tensor's data must be type of uint8");o=Uint8Array.from(t)}else{if(!(e==="float16"&&t instanceof Uint16Array&&s!==Uint16Array))throw new TypeError(`A ${n} tensor's data must be type of ${s}`);o=new globalThis.Float16Array(t.buffer,t.byteOffset,t.length)}}else if(u=t,Array.isArray(e)){if(e.length===0)throw new TypeError("Tensor type cannot be inferred from an empty array.");let s=typeof e[0];if(s==="string")n="string",o=e;else{if(s!=="boolean")throw new TypeError(`Invalid element type of data array: ${s}.`);n="bool",o=Uint8Array.from(e)}}else if(e instanceof Uint8ClampedArray)n="uint8",o=Uint8Array.from(e);else{let s=ye.get(e.constructor);if(s===void 0)throw new TypeError(`Unsupported type for tensor data: ${e.constructor}.`);n=s,o=e}if(u===void 0)u=[o.length];else if(!Array.isArray(u))throw new TypeError("A tensor's dims must be a number array");a=u,this.cpuData=o,this.dataLocation="cpu"}let i=Ft(a);if(this.cpuData&&i!==this.cpuData.length&&(n!=="uint4"&&n!=="int4"||Math.ceil(i/2)!==this.cpuData.length))throw new Error(`Tensor's size(${i}) does not match data length(${this.cpuData.length}).`);this.type=n,this.dims=a,this.size=i}static async fromImage(e,t){return Nt(e,t)}static fromTexture(e,t){return Mt(e,t)}static fromGpuBuffer(e,t){return St(e,t)}static fromMLTensor(e,t){return kt(e,t)}static fromPinnedBuffer(e,t,r){return Dt(e,t,r)}toDataURL(e){return $t(this,e)}toImageData(e){return Bt(this,e)}get data(){if(this.ensureValid(),!this.cpuData)throw new Error("The data is not on CPU. Use `getData()` to download GPU data to CPU, or use `texture` or `gpuBuffer` property to access the GPU data directly.");return this.cpuData}get location(){return this.dataLocation}get texture(){if(this.ensureValid(),!this.gpuTextureData)throw new Error("The data is not stored as a WebGL texture.");return this.gpuTextureData}get gpuBuffer(){if(this.ensureValid(),!this.gpuBufferData)throw new Error("The data is not stored as a WebGPU buffer.");return this.gpuBufferData}get mlTensor(){if(this.ensureValid(),!this.mlTensorData)throw new Error("The data is not stored as a WebNN MLTensor.");return this.mlTensorData}async getData(e){switch(this.ensureValid(),this.dataLocation){case"cpu":case"cpu-pinned":return this.data;case"texture":case"gpu-buffer":case"ml-tensor":if(!this.downloader)throw new Error("The current tensor is not created with a specified data downloader.");if(this.isDownloading)throw new Error("The current tensor is being downloaded.");try{this.isDownloading=!0;let t=await this.downloader();return this.downloader=void 0,this.dataLocation="cpu",this.cpuData=t,e&&this.disposer&&(this.disposer(),this.disposer=void 0),t}finally{this.isDownloading=!1}default:throw new Error(`cannot get data from location: ${this.dataLocation}`)}}dispose(){if(this.isDownloading)throw new Error("The current tensor is being downloaded.");this.disposer&&(this.disposer(),this.disposer=void 0),this.cpuData=void 0,this.gpuTextureData=void 0,this.gpuBufferData=void 0,this.mlTensorData=void 0,this.downloader=void 0,this.isDownloading=void 0,this.dataLocation="none"}ensureValid(){if(this.dataLocation==="none")throw new Error("The tensor is disposed.")}reshape(e){if(this.ensureValid(),this.downloader||this.disposer)throw new Error("Cannot reshape a tensor that owns GPU resource.");return jt(this,e)}}}),Zt=b(()=>{Je(),k=$}),Jt=b(()=>{qt(),He=(e,t)=>{typeof I.trace>"u"?I.wasm.trace:I.trace},$e=(e,t)=>{let r=new Error().stack?.split(/\r\n|\r|\n/g)||[],n=!1;for(let a=0;a<r.length;a++){if(n&&!r[a].includes("TRACE_FUNC")){let i=`FUNC_${e}::${r[a].trim().split(" ")[1]}`;return t&&(i+=`::${t}`),void He("CPU",i)}r[a].includes("TRACE_FUNC")&&(n=!0)}},ae=e=>{(typeof I.trace>"u"?!I.wasm.trace:!I.trace)||$e("BEGIN",e)},oe=e=>{(typeof I.trace>"u"?!I.wasm.trace:!I.trace)||$e("END",e)},ie=e=>{typeof I.trace>"u"?I.wasm.trace:I.trace},se=e=>{typeof I.trace>"u"?I.wasm.trace:I.trace}}),Sr=b(()=>{zt(),Zt(),Jt(),Vt=class Yt{constructor(t){this.handler=t}async run(t,r,n){ae(),ie("InferenceSession.run");let a={},i={};if(typeof t!="object"||t===null||t instanceof k||Array.isArray(t))throw new TypeError("'feeds' must be an object that use input names as keys and OnnxValue as corresponding values.");let o=!0;if(typeof r=="object"){if(r===null)throw new TypeError("Unexpected argument[1]: cannot be null.");if(r instanceof k)throw new TypeError("'fetches' cannot be a Tensor");if(Array.isArray(r)){if(r.length===0)throw new TypeError("'fetches' cannot be an empty array.");o=!1;for(let l of r){if(typeof l!="string")throw new TypeError("'fetches' must be a string array or an object.");if(this.outputNames.indexOf(l)===-1)throw new RangeError(`'fetches' contains invalid output name: ${l}.`);a[l]=null}if(typeof n=="object"&&n!==null)i=n;else if(typeof n<"u")throw new TypeError("'options' must be an object.")}else{let l=!1,p=Object.getOwnPropertyNames(r);for(let f of this.outputNames)if(p.indexOf(f)!==-1){let d=r[f];(d===null||d instanceof k)&&(l=!0,o=!1,a[f]=d)}if(l){if(typeof n=="object"&&n!==null)i=n;else if(typeof n<"u")throw new TypeError("'options' must be an object.")}else i=r}}else if(typeof r<"u")throw new TypeError("Unexpected argument[1]: must be 'fetches' or 'options'.");for(let l of this.inputNames)if(typeof t[l]>"u")throw new Error(`input '${l}' is missing in 'feeds'.`);if(o)for(let l of this.outputNames)a[l]=null;let u=await this.handler.run(t,a,i),s={};for(let l in u)if(Object.hasOwnProperty.call(u,l)){let p=u[l];s[l]=p instanceof k?p:new k(p.type,p.data,p.dims)}return se("InferenceSession.run"),oe(),s}async release(){return this.handler.dispose()}static async create(t,r,n,a){ae(),ie("InferenceSession.create");let i,o={};if(typeof t=="string"){if(i=t,typeof r=="object"&&r!==null)o=r;else if(typeof r<"u")throw new TypeError("'options' must be an object.")}else if(t instanceof Uint8Array){if(i=t,typeof r=="object"&&r!==null)o=r;else if(typeof r<"u")throw new TypeError("'options' must be an object.")}else{if(!(t instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&t instanceof SharedArrayBuffer))throw new TypeError("Unexpected argument[0]: must be 'path' or 'buffer'.");{let p=t,f=0,d=t.byteLength;if(typeof r=="object"&&r!==null)o=r;else if(typeof r=="number"){if(f=r,!Number.isSafeInteger(f))throw new RangeError("'byteOffset' must be an integer.");if(f<0||f>=p.byteLength)throw new RangeError(`'byteOffset' is out of range [0, ${p.byteLength}).`);if(d=t.byteLength-f,typeof n=="number"){if(d=n,!Number.isSafeInteger(d))throw new RangeError("'byteLength' must be an integer.");if(d<=0||f+d>p.byteLength)throw new RangeError(`'byteLength' is out of range (0, ${p.byteLength-f}].`);if(typeof a=="object"&&a!==null)o=a;else if(typeof a<"u")throw new TypeError("'options' must be an object.")}else if(typeof n<"u")throw new TypeError("'byteLength' must be a number.")}else if(typeof r<"u")throw new TypeError("'options' must be an object.");i=new Uint8Array(p,f,d)}}let[u,s]=await Pt(o),l=await u.createInferenceSessionHandler(i,s);return se("InferenceSession.create"),oe(),new Yt(l)}startProfiling(){this.handler.startProfiling()}endProfiling(){this.handler.endProfiling()}get inputNames(){return this.handler.inputNames}get outputNames(){return this.handler.outputNames}get inputMetadata(){return this.handler.inputMetadata}get outputMetadata(){return this.handler.outputMetadata}}}),kr=b(()=>{Sr(),Wt=Vt}),Dr=b(()=>{}),Gr=b(()=>{}),Fr=b(()=>{}),jr=b(()=>{}),Kt={};Ze(Kt,{InferenceSession:()=>Wt,TRACE:()=>He,TRACE_EVENT_BEGIN:()=>ie,TRACE_EVENT_END:()=>se,TRACE_FUNC_BEGIN:()=>ae,TRACE_FUNC_END:()=>oe,Tensor:()=>k,env:()=>R,registerBackend:()=>Re});var Be,ht,Qt,Q=b(()=>{xr(),_r(),kr(),Zt(),Dr(),Gr(),Jt(),Fr(),jr()}),Ye=b(()=>{}),Xt={};Ze(Xt,{default:()=>Qt});var Ne,yt,_,Ke,Ee,mt,gt,Me,bt,Se,er,ke,tr,De,ve,ce,Ge,Et,vt,Tt,Qe,T,N,Oe,v,rr,At,Ct,Rt,q,Ot,nr,re,Ce,ne,ar,or,Xe,et,ir,tt,Ut,rt,nt,Z,It,Fe,Ue,at,ot,je,it,st,lt,H,B,te,we,he,Te,Ve,Ae,J,Y,Lt,sr,lr,ur,fr,pr,dr,cr,We,xt,wr,qe,hr,yr,Vr=b(()=>{br(),le(),ut(),Be="ort-wasm-proxy-worker",(ht=globalThis.self?.name===Be)&&(self.onmessage=e=>{let{type:t,in:r}=e.data;try{switch(t){case"init-wasm":Qe(r.wasm).then(()=>{rt(r).then(()=>{postMessage({type:t})},n=>{postMessage({type:t,err:n})})},n=>{postMessage({type:t,err:n})});break;case"init-ep":{let{epName:n,env:a}=r;nt(a,n).then(()=>{postMessage({type:t})},i=>{postMessage({type:t,err:i})});break}case"copy-from":{let{buffer:n}=r,a=Ue(n);postMessage({type:t,out:a});break}case"create":{let{model:n,options:a}=r;at(n,a).then(i=>{postMessage({type:t,out:i})},i=>{postMessage({type:t,err:i})});break}case"release":ot(r),postMessage({type:t});break;case"run":{let{sessionId:n,inputIndices:a,inputs:i,outputIndices:o,options:u}=r;it(n,a,i,o,new Array(o.length).fill(null),u).then(s=>{s.some(l=>l[3]!=="cpu")?postMessage({type:t,err:"Proxy does not support non-cpu tensor location."}):postMessage({type:t,out:s},lt([...i,...s]))},s=>{postMessage({type:t,err:s})});break}case"end-profiling":st(r),postMessage({type:t})}}catch(n){postMessage({type:t,err:n})}}),Qt=ht?null:e=>new Worker(e??_,{type:"module",name:Be})}),ut=b(()=>{Ye(),Ne=typeof location>"u"?void 0:location.origin,yt=import.meta.url>"file:"&&import.meta.url<"file;",_=yt?new URL(new URL("ort.wasm.min.mjs",import.meta.url).href,Ne).href:import.meta.url,Ke=()=>{if(_&&!_.startsWith("blob:"))return _.substring(0,_.lastIndexOf("/")+1)},Ee=(e,t)=>{try{let r=t??_;return(r?new URL(e,r):new URL(e)).origin===Ne}catch{return!1}},mt=(e,t)=>{let r=t??_;try{return(r?new URL(e,r):new URL(e)).href}catch{return}},gt=(e,t)=>`${t??"./"}${e}`,Me=async e=>{let t=await(await fetch(e,{credentials:"same-origin"})).blob();return URL.createObjectURL(t)},bt=async e=>(await import(e)).default,Se=(Vr(),Ht(Xt)).default,er=async()=>{if(!_)throw new Error("Failed to load proxy worker: cannot determine the script source URL.");if(Ee(_))return[void 0,Se()];let e=await Me(_);return[e,Se(e)]},ke=void 0,tr=async(e,t,r,n)=>{let a=ke;if(a)if(_)a=Ee(_)||n&&!r;else{if(!n||r)throw new Error("cannot determine the script source URL.");a=!0}if(a)return[void 0,ke];{let i="ort-wasm-simd-threaded.mjs",o=e??mt(i,t),u=r&&o&&!Ee(o,t),s=u?await Me(o):o??gt(i,t);return[u?s:void 0,await bt(s)]}}}),le=b(()=>{ut(),ve=!1,ce=!1,Ge=!1,Et=()=>{if(typeof SharedArrayBuffer>"u")return!1;try{return typeof MessageChannel<"u"&&new MessageChannel().port1.postMessage(new SharedArrayBuffer(1)),WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0,1,4,1,96,0,0,3,2,1,0,5,4,1,3,1,1,10,11,1,9,0,65,0,254,16,2,0,26,11]))}catch{return!1}},vt=()=>{try{return WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0,1,4,1,96,0,0,3,2,1,0,10,30,1,28,0,65,0,253,15,253,12,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,253,186,1,26,11]))}catch{return!1}},Tt=()=>{try{return WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0,1,5,1,96,0,1,123,3,2,1,0,10,19,1,17,0,65,1,253,15,65,2,253,15,65,3,253,15,253,147,2,11]))}catch{return!1}},Qe=async e=>{if(ve)return Promise.resolve();if(ce)throw new Error("multiple calls to 'initializeWebAssembly()' detected.");if(Ge)throw new Error("previous call to 'initializeWebAssembly()' failed.");ce=!0;let t=e.initTimeout,r=e.numThreads;if(e.simd!==!1){if(e.simd==="relaxed"){if(!Tt())throw new Error("Relaxed WebAssembly SIMD is not supported in the current environment.")}else if(!vt())throw new Error("WebAssembly SIMD is not supported in the current environment.")}let n=Et();r>1&&!n&&(typeof self<"u"&&self.crossOriginIsolated,e.numThreads=r=1);let a=e.wasmPaths,i=typeof a=="string"?a:void 0,o=a?.mjs,u=o?.href??o,s=a?.wasm,l=s?.href??s,p=e.wasmBinary,[f,d]=await tr(u,i,r>1,!!p||!!l),h=!1,y=[];if(t>0&&y.push(new Promise(E=>{setTimeout(()=>{h=!0,E()},t)})),y.push(new Promise((E,C)=>{let w={numThreads:r};if(p)w.wasmBinary=p,w.locateFile=c=>c;else if(l||i)w.locateFile=c=>l??i+c;else if(u&&u.indexOf("blob:")!==0)w.locateFile=c=>new URL(c,u).href;else if(f){let c=Ke();c&&(w.locateFile=g=>c+g)}d(w).then(c=>{ce=!1,ve=!0,De=c,E(),f&&URL.revokeObjectURL(f)},c=>{ce=!1,Ge=!0,C(c)})})),await Promise.race(y),h)throw new Error(`WebAssembly backend initializing failed due to timeout: ${t}ms`)},T=()=>{if(ve&&De)return De;throw new Error("WebAssembly is not initialized yet.")}}),ft=b(()=>{le(),N=(e,t)=>{let r=T(),n=r.lengthBytesUTF8(e)+1,a=r._malloc(n);return r.stringToUTF8(e,a,n),t.push(a),a},Oe=(e,t,r,n)=>{if(typeof e=="object"&&e!==null){if(r.has(e))throw new Error("Circular reference in options");r.add(e)}Object.entries(e).forEach(([a,i])=>{let o=t?t+a:a;if(typeof i=="object")Oe(i,o+".",r,n);else if(typeof i=="string"||typeof i=="number")n(o,i.toString());else{if(typeof i!="boolean")throw new Error("Can't handle extra config type: "+typeof i);n(o,i?"1":"0")}})},v=e=>{let t=T(),r=t.stackSave();try{let n=t.PTR_SIZE,a=t.stackAlloc(2*n);t._OrtGetLastError(a,a+n);let i=Number(t.getValue(a,n===4?"i32":"i64")),o=t.getValue(a+n,"*"),u=o?t.UTF8ToString(o):"";throw new Error(`${e} ERROR_CODE: ${i}, ERROR_MESSAGE: ${u}`)}finally{t.stackRestore(r)}}}),Wr=b(()=>{le(),ft(),rr=e=>{let t=T(),r=0,n=[],a=e||{};try{if(e?.logSeverityLevel===void 0)a.logSeverityLevel=2;else if(typeof e.logSeverityLevel!="number"||!Number.isInteger(e.logSeverityLevel)||e.logSeverityLevel<0||e.logSeverityLevel>4)throw new Error(`log severity level is not valid: ${e.logSeverityLevel}`);if(e?.logVerbosityLevel===void 0)a.logVerbosityLevel=0;else if(typeof e.logVerbosityLevel!="number"||!Number.isInteger(e.logVerbosityLevel))throw new Error(`log verbosity level is not valid: ${e.logVerbosityLevel}`);e?.terminate===void 0&&(a.terminate=!1);let i=0;return e?.tag!==void 0&&(i=N(e.tag,n)),r=t._OrtCreateRunOptions(a.logSeverityLevel,a.logVerbosityLevel,!!a.terminate,i),r===0&&v("Can't create run options."),e?.extra!==void 0&&Oe(e.extra,"",new WeakSet,(o,u)=>{let s=N(o,n),l=N(u,n);t._OrtAddRunConfigEntry(r,s,l)!==0&&v(`Can't set a run config entry: ${o} - ${u}.`)}),[r,n]}catch(i){throw r!==0&&t._OrtReleaseRunOptions(r),n.forEach(o=>t._free(o)),i}}}),Hr=b(()=>{le(),ft(),At=e=>{switch(e){case"disabled":return 0;case"basic":return 1;case"extended":return 2;case"layout":return 3;case"all":return 99;default:throw new Error(`unsupported graph optimization level: ${e}`)}},Ct=e=>{switch(e){case"sequential":return 0;case"parallel":return 1;default:throw new Error(`unsupported execution mode: ${e}`)}},Rt=e=>{e.extra||(e.extra={}),e.extra.session||(e.extra.session={});let t=e.extra.session;t.use_ort_model_bytes_directly||(t.use_ort_model_bytes_directly="1"),e.executionProviders&&e.executionProviders.some(r=>(typeof r=="string"?r:r.name)==="webgpu")&&(e.enableMemPattern=!1)},q=(e,t,r,n)=>{let a=N(t,n),i=N(r,n);T()._OrtAddSessionConfigEntry(e,a,i)!==0&&v(`Can't set a session config entry: ${t} - ${r}.`)},Ot=async(e,t,r)=>{let n=t.executionProviders;for(let a of n){let i=typeof a=="string"?a:a.name,o=[];switch(i){case"webnn":if(i="WEBNN",q(e,"session.disable_quant_qdq","1",r),q(e,"session.disable_qdq_constant_folding","1",r),typeof a!="string"){let f=a?.deviceType;f&&q(e,"deviceType",f,r)}break;case"webgpu":if(i="JS",typeof a!="string"){let f=a;if(f?.preferredLayout){if(f.preferredLayout!=="NCHW"&&f.preferredLayout!=="NHWC")throw new Error(`preferredLayout must be either 'NCHW' or 'NHWC': ${f.preferredLayout}`);q(e,"preferredLayout",f.preferredLayout,r)}}break;case"wasm":case"cpu":continue;default:throw new Error(`not supported execution provider: ${i}`)}let u=N(i,r),s=o.length,l=0,p=0;if(s>0){l=T()._malloc(s*T().PTR_SIZE),r.push(l),p=T()._malloc(s*T().PTR_SIZE),r.push(p);for(let f=0;f<s;f++)T().setValue(l+f*T().PTR_SIZE,o[f][0],"*"),T().setValue(p+f*T().PTR_SIZE,o[f][1],"*")}await T()._OrtAppendExecutionProvider(e,u,l,p,s)!==0&&v(`Can't append execution provider: ${i}.`)}},nr=async e=>{let t=T(),r=0,n=[],a=e||{};Rt(a);try{let i=At(a.graphOptimizationLevel??"all"),o=Ct(a.executionMode??"sequential"),u=typeof a.logId=="string"?N(a.logId,n):0,s=a.logSeverityLevel??2;if(!Number.isInteger(s)||s<0||s>4)throw new Error(`log severity level is not valid: ${s}`);let l=a.logVerbosityLevel??0;if(!Number.isInteger(l)||l<0||l>4)throw new Error(`log verbosity level is not valid: ${l}`);let p=typeof a.optimizedModelFilePath=="string"?N(a.optimizedModelFilePath,n):0;if(r=t._OrtCreateSessionOptions(i,!!a.enableCpuMemArena,!!a.enableMemPattern,o,!!a.enableProfiling,0,u,s,l,p),r===0&&v("Can't create session options."),a.executionProviders&&await Ot(r,a,n),a.enableGraphCapture!==void 0){if(typeof a.enableGraphCapture!="boolean")throw new Error(`enableGraphCapture must be a boolean value: ${a.enableGraphCapture}`);q(r,"enableGraphCapture",a.enableGraphCapture.toString(),n)}if(a.freeDimensionOverrides)for(let[f,d]of Object.entries(a.freeDimensionOverrides)){if(typeof f!="string")throw new Error(`free dimension override name must be a string: ${f}`);if(typeof d!="number"||!Number.isInteger(d)||d<0)throw new Error(`free dimension override value must be a non-negative integer: ${d}`);let h=N(f,n);t._OrtAddFreeDimensionOverride(r,h,d)!==0&&v(`Can't set a free dimension override: ${f} - ${d}.`)}return a.extra!==void 0&&Oe(a.extra,"",new WeakSet,(f,d)=>{q(r,f,d,n)}),[r,n]}catch(i){throw r!==0&&t._OrtReleaseSessionOptions(r)!==0&&v("Can't release session options."),n.forEach(o=>t._free(o)),i}}}),mr=b(()=>{re=e=>{switch(e){case"int8":return 3;case"uint8":return 2;case"bool":return 9;case"int16":return 5;case"uint16":return 4;case"int32":return 6;case"uint32":return 12;case"float16":return 10;case"float32":return 1;case"float64":return 11;case"string":return 8;case"int64":return 7;case"uint64":return 13;case"int4":return 22;case"uint4":return 21;default:throw new Error(`unsupported data type: ${e}`)}},Ce=e=>{switch(e){case 3:return"int8";case 2:return"uint8";case 9:return"bool";case 5:return"int16";case 4:return"uint16";case 6:return"int32";case 12:return"uint32";case 10:return"float16";case 1:return"float32";case 11:return"float64";case 8:return"string";case 7:return"int64";case 13:return"uint64";case 22:return"int4";case 21:return"uint4";default:throw new Error(`unsupported data type: ${e}`)}},ne=(e,t)=>{let r=[-1,4,1,1,2,2,4,8,-1,1,2,8,4,8,-1,-1,-1,-1,-1,-1,-1,.5,.5][e],n=typeof t=="number"?t:t.reduce((a,i)=>a*i,1);return r>0?Math.ceil(n*r):void 0},ar=e=>{switch(e){case"float16":return typeof Float16Array<"u"?Float16Array:Uint16Array;case"float32":return Float32Array;case"uint8":case"bool":return Uint8Array;case"int8":return Int8Array;case"uint16":return Uint16Array;case"int16":return Int16Array;case"int32":return Int32Array;case"float64":return Float64Array;case"uint32":return Uint32Array;case"int64":return BigInt64Array;case"uint64":return BigUint64Array;default:throw new Error(`unsupported type: ${e}`)}},or=e=>{switch(e){case"verbose":return 0;case"info":return 1;case"warning":return 2;case"error":return 3;case"fatal":return 4;default:throw new Error(`unsupported logging level: ${e}`)}},Xe=e=>e==="float32"||e==="float16"||e==="int32"||e==="int64"||e==="uint32"||e==="uint8"||e==="bool"||e==="uint4"||e==="int4",et=e=>e==="float32"||e==="float16"||e==="int32"||e==="int64"||e==="uint32"||e==="uint64"||e==="int8"||e==="uint8"||e==="bool"||e==="uint4"||e==="int4",ir=e=>{switch(e){case"none":return 0;case"cpu":return 1;case"cpu-pinned":return 2;case"texture":return 3;case"gpu-buffer":return 4;case"ml-tensor":return 5;default:throw new Error(`unsupported data location: ${e}`)}}}),gr=b(()=>{Ye(),tt=async e=>{if(typeof e=="string"){let t=await fetch(e);if(!t.ok)throw new Error(`failed to load external data file: ${e}`);let r=t.headers.get("Content-Length"),n=r?parseInt(r,10):0;if(n<1073741824)return new Uint8Array(await t.arrayBuffer());{if(!t.body)throw new Error(`failed to load external data file: ${e}, no response body.`);let a,i=t.body.getReader();try{a=new ArrayBuffer(n)}catch(u){if(!(u instanceof RangeError))throw u;{let s=Math.ceil(n/65536);a=new WebAssembly.Memory({initial:s,maximum:s}).buffer}}let o=0;for(;;){let{done:u,value:s}=await i.read();if(u)break;let l=s.byteLength;new Uint8Array(a,o,l).set(s),o+=l}return new Uint8Array(a,0,n)}}return e instanceof Blob?new Uint8Array(await e.arrayBuffer()):e instanceof Uint8Array?e:new Uint8Array(e)}}),br=b(()=>{Q(),Wr(),Hr(),mr(),le(),ft(),gr(),Ut=(e,t)=>{T()._OrtInit(e,t)!==0&&v("Can't initialize onnxruntime.")},rt=async e=>{Ut(e.wasm.numThreads,or(e.logLevel))},nt=async(e,t)=>{T().asyncInit?.();let r=e.webgpu.adapter;if(t==="webgpu"){if(typeof navigator>"u"||!navigator.gpu)throw new Error("WebGPU is not supported in current environment");if(r){if(typeof r.limits!="object"||typeof r.features!="object"||typeof r.requestDevice!="function")throw new Error("Invalid GPU adapter set in `env.webgpu.adapter`. It must be a GPUAdapter object.")}else{let n=e.webgpu.powerPreference;if(n!==void 0&&n!=="low-power"&&n!=="high-performance")throw new Error(`Invalid powerPreference setting: "${n}"`);let a=e.webgpu.forceFallbackAdapter;if(a!==void 0&&typeof a!="boolean")throw new Error(`Invalid forceFallbackAdapter setting: "${a}"`);if(r=await navigator.gpu.requestAdapter({powerPreference:n,forceFallbackAdapter:a}),!r)throw new Error('Failed to get GPU adapter. You may need to enable flag "--enable-unsafe-webgpu" if you are using Chrome.')}}if(t==="webnn"&&(typeof navigator>"u"||!navigator.ml))throw new Error("WebNN is not supported in current environment")},Z=new Map,It=e=>{let t=T(),r=t.stackSave();try{let n=t.PTR_SIZE,a=t.stackAlloc(2*n);t._OrtGetInputOutputCount(e,a,a+n)!==0&&v("Can't get session input/output count.");let i=n===4?"i32":"i64";return[Number(t.getValue(a,i)),Number(t.getValue(a+n,i))]}finally{t.stackRestore(r)}},Fe=(e,t)=>{let r=T(),n=r.stackSave(),a=0;try{let i=r.PTR_SIZE,o=r.stackAlloc(2*i);r._OrtGetInputOutputMetadata(e,t,o,o+i)!==0&&v("Can't get session input/output metadata.");let u=Number(r.getValue(o,"*"));a=Number(r.getValue(o+i,"*"));let s=r.HEAP32[a/4];if(s===0)return[u,0];let l=r.HEAPU32[a/4+1],p=[];for(let f=0;f<l;f++){let d=Number(r.getValue(a+8+f*i,"*"));p.push(d!==0?r.UTF8ToString(d):Number(r.getValue(a+8+(f+l)*i,"*")))}return[u,s,p]}finally{r.stackRestore(n),a!==0&&r._OrtFree(a)}},Ue=e=>{let t=T(),r=t._malloc(e.byteLength);if(r===0)throw new Error(`Can't create a session. failed to allocate a buffer of size ${e.byteLength}.`);return t.HEAPU8.set(e,r),[r,e.byteLength]},at=async(e,t)=>{let r,n,a=T();Array.isArray(e)?[r,n]=e:e.buffer===a.HEAPU8.buffer?[r,n]=[e.byteOffset,e.byteLength]:[r,n]=Ue(e);let i=0,o=0,u=[],s=[],l=[];try{if([o,u]=await nr(t),t?.externalData&&a.mountExternalData){let w=[];for(let c of t.externalData){let g=typeof c=="string"?c:c.path;w.push(tt(typeof c=="string"?c:c.data).then(A=>{a.mountExternalData(g,A)}))}await Promise.all(w)}for(let w of t?.executionProviders??[])if((typeof w=="string"?w:w.name)==="webnn"){if(a.shouldTransferToMLTensor=!1,typeof w!="string"){let c=w,g=c?.context,A=c?.gpuDevice,L=c?.deviceType,X=c?.powerPreference;a.currentContext=g||(A?await a.webnnCreateMLContext(A):await a.webnnCreateMLContext({deviceType:L,powerPreference:X}))}else a.currentContext=await a.webnnCreateMLContext();break}i=await a._OrtCreateSession(r,n,o),a.webgpuOnCreateSession?.(i),i===0&&v("Can't create a session."),a.jsepOnCreateSession?.(),a.currentContext&&(a.webnnRegisterMLContext(i,a.currentContext),a.currentContext=void 0,a.shouldTransferToMLTensor=!0);let[p,f]=It(i),d=!!t?.enableGraphCapture,h=[],y=[],E=[],C=[];for(let w=0;w<p;w++){let[c,g,A]=Fe(i,w);c===0&&v("Can't get an input name."),s.push(c);let L=a.UTF8ToString(c);h.push(L),E.push(g===0?{name:L,isTensor:!1}:{name:L,isTensor:!0,type:Ce(g),shape:A})}for(let w=0;w<f;w++){let[c,g,A]=Fe(i,w+p);c===0&&v("Can't get an output name."),l.push(c);let L=a.UTF8ToString(c);y.push(L),C.push(g===0?{name:L,isTensor:!1}:{name:L,isTensor:!0,type:Ce(g),shape:A})}return Z.set(i,[i,s,l,null,d,!1]),[i,h,y,E,C]}catch(p){throw s.forEach(f=>a._OrtFree(f)),l.forEach(f=>a._OrtFree(f)),i!==0&&a._OrtReleaseSession(i)!==0&&v("Can't release session."),p}finally{a._free(r),o!==0&&a._OrtReleaseSessionOptions(o)!==0&&v("Can't release session options."),u.forEach(p=>a._free(p)),a.unmountExternalData?.()}},ot=e=>{let t=T(),r=Z.get(e);if(!r)throw new Error(`cannot release session. invalid session id: ${e}`);let[n,a,i,o,u]=r;o&&(u&&t._OrtClearBoundOutputs(o.handle)!==0&&v("Can't clear bound outputs."),t._OrtReleaseBinding(o.handle)!==0&&v("Can't release IO binding.")),t.jsepOnReleaseSession?.(e),t.webnnOnReleaseSession?.(e),t.webgpuOnReleaseSession?.(e),a.forEach(s=>t._OrtFree(s)),i.forEach(s=>t._OrtFree(s)),t._OrtReleaseSession(n)!==0&&v("Can't release session."),Z.delete(e)},je=async(e,t,r,n,a,i,o=!1)=>{if(!e)return void t.push(0);let u,s,l=T(),p=l.PTR_SIZE,f=e[0],d=e[1],h=e[3],y=h;if(f==="string"&&(h==="gpu-buffer"||h==="ml-tensor"))throw new Error("String tensor is not supported on GPU.");if(o&&h!=="gpu-buffer")throw new Error(`External buffer must be provided for input/output index ${i} when enableGraphCapture is true.`);if(h==="gpu-buffer"){let w=e[2].gpuBuffer;s=ne(re(f),d);{let c=l.jsepRegisterBuffer;if(!c)throw new Error('Tensor location "gpu-buffer" is not supported without using WebGPU.');u=c(n,i,w,s)}}else if(h==="ml-tensor"){let w=e[2].mlTensor;s=ne(re(f),d);let c=l.webnnRegisterMLTensor;if(!c)throw new Error('Tensor location "ml-tensor" is not supported without using WebNN.');u=c(n,w,re(f),d)}else{let w=e[2];if(Array.isArray(w)){s=p*w.length,u=l._malloc(s),r.push(u);for(let c=0;c<w.length;c++){if(typeof w[c]!="string")throw new TypeError(`tensor data at index ${c} is not a string`);l.setValue(u+c*p,N(w[c],r),"*")}}else{let c=l.webnnIsGraphInput,g=l.webnnIsGraphOutput;if(f!=="string"&&c&&g){let A=l.UTF8ToString(a);if(c(n,A)||g(n,A)){let L=re(f);s=ne(L,d),y="ml-tensor";let X=l.webnnCreateTemporaryTensor,ue=l.webnnUploadTensor;if(!X||!ue)throw new Error('Tensor location "ml-tensor" is not supported without using WebNN.');let fe=await X(n,L,d);ue(fe,new Uint8Array(w.buffer,w.byteOffset,w.byteLength)),u=fe}else s=w.byteLength,u=l._malloc(s),r.push(u),l.HEAPU8.set(new Uint8Array(w.buffer,w.byteOffset,s),u)}else s=w.byteLength,u=l._malloc(s),r.push(u),l.HEAPU8.set(new Uint8Array(w.buffer,w.byteOffset,s),u)}}let E=l.stackSave(),C=l.stackAlloc(4*d.length);try{d.forEach((c,g)=>l.setValue(C+g*p,c,p===4?"i32":"i64"));let w=l._OrtCreateTensor(re(f),u,s,C,d.length,ir(y));w===0&&v(`Can't create tensor for input/output. session=${n}, index=${i}.`),t.push(w)}finally{l.stackRestore(E)}},it=async(e,t,r,n,a,i)=>{let o=T(),u=o.PTR_SIZE,s=Z.get(e);if(!s)throw new Error(`cannot run inference. invalid session id: ${e}`);let l=s[0],p=s[1],f=s[2],d=s[3],h=s[4];s[5];let y=t.length,E=n.length,C=0,w=[],c=[],g=[],A=[],L=[],X=o.stackSave(),ue=o.stackAlloc(y*u),fe=o.stackAlloc(y*u),Ie=o.stackAlloc(E*u),pt=o.stackAlloc(E*u);try{[C,w]=rr(i),ie("wasm prepareInputOutputTensor");for(let m=0;m<y;m++)await je(r[m],c,A,e,p[t[m]],t[m],h);for(let m=0;m<E;m++)await je(a[m],g,A,e,f[n[m]],y+n[m],h);se("wasm prepareInputOutputTensor");for(let m=0;m<y;m++)o.setValue(ue+m*u,c[m],"*"),o.setValue(fe+m*u,p[t[m]],"*");for(let m=0;m<E;m++)o.setValue(Ie+m*u,g[m],"*"),o.setValue(pt+m*u,f[n[m]],"*");let M;o.jsepOnRunStart?.(l),o.webnnOnRunStart?.(l),M=await o._OrtRun(l,fe,ue,y,pt,E,Ie,C),M!==0&&v("failed to call OrtRun().");let D=[],dt=[];ie("wasm ProcessOutputTensor");for(let m=0;m<E;m++){let S=Number(o.getValue(Ie+m*u,"*"));if(S===g[m]||L.includes(g[m])){D.push(a[m]),S!==g[m]&&o._OrtReleaseTensor(S)!==0&&v("Can't release tensor.");continue}let U,Tr=o.stackSave(),F=o.stackAlloc(4*u),me=!1,P=0;try{o._OrtGetTensorData(S,F,F+u,F+2*u,F+3*u)!==0&&v(`Can't access output tensor data on index ${m}.`);let Le=u===4?"i32":"i64",ge=Number(o.getValue(F,Le));P=o.getValue(F+u,"*");let ct=o.getValue(F+2*u,"*"),Ar=Number(o.getValue(F+3*u,Le)),j=[];for(let O=0;O<Ar;O++)j.push(Number(o.getValue(ct+O*u,Le)));o._OrtFree(ct)!==0&&v("Can't free memory for tensor dims.");let V=j.reduce((O,x)=>O*x,1);U=Ce(ge);let pe=d?.outputPreferredLocations[n[m]];if(U==="string"){if(pe==="gpu-buffer"||pe==="ml-tensor")throw new Error("String tensor is not supported on GPU.");let O=[];for(let x=0;x<V;x++){let G=o.getValue(P+x*u,"*"),Cr=o.getValue(P+(x+1)*u,"*"),Rr=x===V-1?void 0:Cr-G;O.push(o.UTF8ToString(G,Rr))}D.push([U,j,O,"cpu"])}else if(pe==="gpu-buffer"&&V>0){let O=o.jsepGetBuffer;if(!O)throw new Error('preferredLocation "gpu-buffer" is not supported without using WebGPU.');let x=O(P),G=ne(ge,V);if(G===void 0||!Xe(U))throw new Error(`Unsupported data type: ${U}`);me=!0,D.push([U,j,{gpuBuffer:x,download:o.jsepCreateDownloader(x,G,U),dispose:()=>{o._OrtReleaseTensor(S)!==0&&v("Can't release tensor.")}},"gpu-buffer"])}else if(pe==="ml-tensor"&&V>0){let O=o.webnnEnsureTensor,x=o.webnnIsGraphInputOutputTypeSupported;if(!O||!x)throw new Error('preferredLocation "ml-tensor" is not supported without using WebNN.');if(ne(ge,V)===void 0||!et(U))throw new Error(`Unsupported data type: ${U}`);if(!x(e,U,!1))throw new Error(`preferredLocation "ml-tensor" for ${U} output is not supported by current WebNN Context.`);let G=await O(e,P,ge,j,!1);me=!0,D.push([U,j,{mlTensor:G,download:o.webnnCreateMLTensorDownloader(P,U),dispose:()=>{o.webnnReleaseTensorId(P),o._OrtReleaseTensor(S)}},"ml-tensor"])}else if(pe==="ml-tensor-cpu-output"&&V>0){let O=o.webnnCreateMLTensorDownloader(P,U)(),x=D.length;me=!0,dt.push((async()=>{let G=[x,await O];return o.webnnReleaseTensorId(P),o._OrtReleaseTensor(S),G})()),D.push([U,j,[],"cpu"])}else{let O=new(ar(U))(V);new Uint8Array(O.buffer,O.byteOffset,O.byteLength).set(o.HEAPU8.subarray(P,P+O.byteLength)),D.push([U,j,O,"cpu"])}}finally{o.stackRestore(Tr),U==="string"&&P&&o._free(P),me||o._OrtReleaseTensor(S)}}d&&!h&&(o._OrtClearBoundOutputs(d.handle)!==0&&v("Can't clear bound outputs."),Z.set(e,[l,p,f,d,h,!1]));for(let[m,S]of await Promise.all(dt))D[m][2]=S;return se("wasm ProcessOutputTensor"),D}finally{o.webnnOnRunEnd?.(l),o.stackRestore(X),c.forEach(M=>o._OrtReleaseTensor(M)),g.forEach(M=>o._OrtReleaseTensor(M)),A.forEach(M=>o._free(M)),C!==0&&o._OrtReleaseRunOptions(C),w.forEach(M=>o._free(M))}},st=e=>{let t=T(),r=Z.get(e);if(!r)throw new Error("invalid session id");let n=r[0],a=t._OrtEndProfiling(n);a===0&&v("Can't get an profile file name."),t._OrtFree(a)},lt=e=>{let t=[];for(let r of e){let n=r[2];!Array.isArray(n)&&"buffer"in n&&t.push(n.buffer)}return t}}),Er=b(()=>{Q(),br(),le(),ut(),H=()=>!!R.wasm.proxy&&typeof document<"u",te=!1,we=!1,he=!1,Ae=new Map,J=(e,t)=>{let r=Ae.get(e);r?r.push(t):Ae.set(e,[t])},Y=()=>{if(te||!we||he||!B)throw new Error("worker not ready")},Lt=e=>{switch(e.data.type){case"init-wasm":te=!1,e.data.err?(he=!0,Ve[1](e.data.err)):(we=!0,Ve[0]()),Te&&(URL.revokeObjectURL(Te),Te=void 0);break;case"init-ep":case"copy-from":case"create":case"release":case"run":case"end-profiling":{let t=Ae.get(e.data.type);e.data.err?t.shift()[1](e.data.err):t.shift()[0](e.data.out);break}}},sr=async()=>{if(!we){if(te)throw new Error("multiple calls to 'initWasm()' detected.");if(he)throw new Error("previous call to 'initWasm()' failed.");if(te=!0,H())return new Promise((e,t)=>{B?.terminate(),er().then(([r,n])=>{try{(B=n).onerror=i=>t(i),B.onmessage=Lt,Ve=[e,t];let a={type:"init-wasm",in:R};if(!a.in.wasm.wasmPaths&&r){let i=Ke();i&&(a.in.wasm.wasmPaths=i)}B.postMessage(a),Te=r}catch(a){t(a)}},t)});try{await Qe(R.wasm),await rt(R),we=!0}catch(e){throw he=!0,e}finally{te=!1}}},lr=async e=>{if(H())return Y(),new Promise((t,r)=>{J("init-ep",[t,r]);let n={type:"init-ep",in:{epName:e,env:R}};B.postMessage(n)});await nt(R,e)},ur=async e=>H()?(Y(),new Promise((t,r)=>{J("copy-from",[t,r]);let n={type:"copy-from",in:{buffer:e}};B.postMessage(n,[e.buffer])})):Ue(e),fr=async(e,t)=>{if(H()){if(t?.preferredOutputLocation)throw new Error('session option "preferredOutputLocation" is not supported for proxy.');return Y(),new Promise((r,n)=>{J("create",[r,n]);let a={type:"create",in:{model:e,options:{...t}}},i=[];e instanceof Uint8Array&&i.push(e.buffer),B.postMessage(a,i)})}return at(e,t)},pr=async e=>{if(H())return Y(),new Promise((t,r)=>{J("release",[t,r]);let n={type:"release",in:e};B.postMessage(n)});ot(e)},dr=async(e,t,r,n,a,i)=>{if(H()){if(r.some(o=>o[3]!=="cpu"))throw new Error("input tensor on GPU is not supported for proxy.");if(a.some(o=>o))throw new Error("pre-allocated output tensor is not supported for proxy.");return Y(),new Promise((o,u)=>{J("run",[o,u]);let s=r,l={type:"run",in:{sessionId:e,inputIndices:t,inputs:s,outputIndices:n,options:i}};B.postMessage(l,lt(s))})}return it(e,t,r,n,a,i)},cr=async e=>{if(H())return Y(),new Promise((t,r)=>{J("end-profiling",[t,r]);let n={type:"end-profiling",in:e};B.postMessage(n)});st(e)}}),zr=b(()=>{Q(),Er(),mr(),Ye(),gr(),We=(e,t)=>{switch(e.location){case"cpu":return[e.type,e.dims,e.data,"cpu"];case"gpu-buffer":return[e.type,e.dims,{gpuBuffer:e.gpuBuffer},"gpu-buffer"];case"ml-tensor":return[e.type,e.dims,{mlTensor:e.mlTensor},"ml-tensor"];default:throw new Error(`invalid data location: ${e.location} for ${t()}`)}},xt=e=>{switch(e[3]){case"cpu":return new k(e[0],e[2],e[1]);case"gpu-buffer":{let t=e[0];if(!Xe(t))throw new Error(`not supported data type: ${t} for deserializing GPU tensor`);let{gpuBuffer:r,download:n,dispose:a}=e[2];return k.fromGpuBuffer(r,{dataType:t,dims:e[1],download:n,dispose:a})}case"ml-tensor":{let t=e[0];if(!et(t))throw new Error(`not supported data type: ${t} for deserializing MLTensor tensor`);let{mlTensor:r,download:n,dispose:a}=e[2];return k.fromMLTensor(r,{dataType:t,dims:e[1],download:n,dispose:a})}default:throw new Error(`invalid data location: ${e[3]}`)}},wr=class{async fetchModelAndCopyToWasmMemory(e){return ur(await tt(e))}async loadModel(e,t){let r;ae(),r=typeof e=="string"?await this.fetchModelAndCopyToWasmMemory(e):e,[this.sessionId,this.inputNames,this.outputNames,this.inputMetadata,this.outputMetadata]=await fr(r,t),oe()}async dispose(){return pr(this.sessionId)}async run(e,t,r){ae();let n=[],a=[];Object.entries(e).forEach(f=>{let d=f[0],h=f[1],y=this.inputNames.indexOf(d);if(y===-1)throw new Error(`invalid input '${d}'`);n.push(h),a.push(y)});let i=[],o=[];Object.entries(t).forEach(f=>{let d=f[0],h=f[1],y=this.outputNames.indexOf(d);if(y===-1)throw new Error(`invalid output '${d}'`);i.push(h),o.push(y)});let u=n.map((f,d)=>We(f,()=>`input "${this.inputNames[a[d]]}"`)),s=i.map((f,d)=>f?We(f,()=>`output "${this.outputNames[o[d]]}"`):null),l=await dr(this.sessionId,a,u,o,s,r),p={};for(let f=0;f<l.length;f++)p[this.outputNames[o[f]]]=i[f]??xt(l[f]);return oe(),p}startProfiling(){}endProfiling(){cr(this.sessionId)}}}),vr={};Ze(vr,{OnnxruntimeWebAssemblyBackend:()=>hr,initializeFlags:()=>qe,wasmBackend:()=>yr});var qr=b(()=>{Q(),Er(),zr(),qe=()=>{(typeof R.wasm.initTimeout!="number"||R.wasm.initTimeout<0)&&(R.wasm.initTimeout=0);let e=R.wasm.simd;if(typeof e!="boolean"&&e!==void 0&&e!=="fixed"&&e!=="relaxed"&&(R.wasm.simd=!1),typeof R.wasm.proxy!="boolean"&&(R.wasm.proxy=!1),typeof R.wasm.trace!="boolean"&&(R.wasm.trace=!1),typeof R.wasm.numThreads!="number"||!Number.isInteger(R.wasm.numThreads)||R.wasm.numThreads<=0)if(typeof self<"u"&&!self.crossOriginIsolated)R.wasm.numThreads=1;else{let t=typeof navigator>"u"?Lr("node:os").cpus().length:navigator.hardwareConcurrency;R.wasm.numThreads=Math.min(4,Math.ceil((t||1)/2))}},yr=new(hr=class{async init(e){qe(),await sr(),await lr(e)}async createInferenceSessionHandler(e,t){let r=new wr;return await r.loadModel(e,t),r}})});Q(),Q(),Q();var Zr=Kt;{let e=(qr(),Ht(vr)).wasmBackend;Re("cpu",e,10),Re("wasm",e,10)}Object.defineProperty(R.versions,"web",{value:"1.27.0",enumerable:!0});export{Wt as InferenceSession,He as TRACE,ie as TRACE_EVENT_BEGIN,se as TRACE_EVENT_END,ae as TRACE_FUNC_BEGIN,oe as TRACE_FUNC_END,k as Tensor,Zr as default,R as env,Re as registerBackend};
2
+ //# sourceMappingURL=scanic-ort.wasm.min-MU4NYSP2.js.map