tempest-react-sdk 0.57.0 → 0.58.0

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 (316) hide show
  1. package/bin/lib/icons/generate.test.mjs +4 -4
  2. package/dist/br/geocode.cjs +1 -1
  3. package/dist/br/geocode.cjs.map +1 -1
  4. package/dist/br/geocode.js +1 -1
  5. package/dist/br/geocode.js.map +1 -1
  6. package/dist/capture/use-barcode-scanner.cjs +1 -1
  7. package/dist/capture/use-barcode-scanner.cjs.map +1 -1
  8. package/dist/capture/use-barcode-scanner.js +1 -1
  9. package/dist/capture/use-barcode-scanner.js.map +1 -1
  10. package/dist/components/AIChat/AIChat.cjs +1 -1
  11. package/dist/components/AIChat/AIChat.cjs.map +1 -1
  12. package/dist/components/AIChat/AIChat.js +1 -1
  13. package/dist/components/AIChat/AIChat.js.map +1 -1
  14. package/dist/components/AIChat/AIChatTurn.cjs +1 -1
  15. package/dist/components/AIChat/AIChatTurn.cjs.map +1 -1
  16. package/dist/components/AIChat/AIChatTurn.js +1 -1
  17. package/dist/components/AIChat/AIChatTurn.js.map +1 -1
  18. package/dist/components/AppBar/use-sticky-body-warning.cjs +1 -1
  19. package/dist/components/AppBar/use-sticky-body-warning.cjs.map +1 -1
  20. package/dist/components/AppBar/use-sticky-body-warning.js +1 -1
  21. package/dist/components/AppBar/use-sticky-body-warning.js.map +1 -1
  22. package/dist/components/AudioPlayer/AudioPlayer.cjs +1 -1
  23. package/dist/components/AudioPlayer/AudioPlayer.cjs.map +1 -1
  24. package/dist/components/AudioPlayer/AudioPlayer.js +2 -2
  25. package/dist/components/AudioPlayer/AudioPlayer.js.map +1 -1
  26. package/dist/components/AudioRecorder/AudioRecorder.cjs +1 -1
  27. package/dist/components/AudioRecorder/AudioRecorder.cjs.map +1 -1
  28. package/dist/components/AudioRecorder/AudioRecorder.js +1 -1
  29. package/dist/components/AudioRecorder/AudioRecorder.js.map +1 -1
  30. package/dist/components/Chat/Chat.cjs +1 -1
  31. package/dist/components/Chat/Chat.cjs.map +1 -1
  32. package/dist/components/Chat/Chat.js +1 -1
  33. package/dist/components/Chat/Chat.js.map +1 -1
  34. package/dist/components/FilterBar/FilterBar.cjs +1 -1
  35. package/dist/components/FilterBar/FilterBar.cjs.map +1 -1
  36. package/dist/components/FilterBar/FilterBar.js +1 -1
  37. package/dist/components/FilterBar/FilterBar.js.map +1 -1
  38. package/dist/components/FilterBar/filter-apply.cjs +1 -1
  39. package/dist/components/FilterBar/filter-apply.cjs.map +1 -1
  40. package/dist/components/FilterBar/filter-apply.js +1 -1
  41. package/dist/components/FilterBar/filter-apply.js.map +1 -1
  42. package/dist/components/ImageCropper/ImageCropper.cjs +1 -1
  43. package/dist/components/ImageCropper/ImageCropper.cjs.map +1 -1
  44. package/dist/components/ImageCropper/ImageCropper.js +1 -1
  45. package/dist/components/ImageCropper/ImageCropper.js.map +1 -1
  46. package/dist/components/VideoPlayer/VideoPlayer.cjs +1 -1
  47. package/dist/components/VideoPlayer/VideoPlayer.cjs.map +1 -1
  48. package/dist/components/VideoPlayer/VideoPlayer.js +2 -2
  49. package/dist/components/VideoPlayer/VideoPlayer.js.map +1 -1
  50. package/dist/components/VirtualTable/VirtualTable.cjs +1 -1
  51. package/dist/components/VirtualTable/VirtualTable.cjs.map +1 -1
  52. package/dist/components/VirtualTable/VirtualTable.js +1 -1
  53. package/dist/components/VirtualTable/VirtualTable.js.map +1 -1
  54. package/dist/feature-flags/growthbook-adapter.cjs +1 -1
  55. package/dist/feature-flags/growthbook-adapter.cjs.map +1 -1
  56. package/dist/feature-flags/growthbook-adapter.js +1 -1
  57. package/dist/feature-flags/growthbook-adapter.js.map +1 -1
  58. package/dist/hooks/use-focus-trap.cjs +1 -1
  59. package/dist/hooks/use-focus-trap.cjs.map +1 -1
  60. package/dist/hooks/use-focus-trap.js +1 -1
  61. package/dist/hooks/use-focus-trap.js.map +1 -1
  62. package/dist/hooks/use-push-to-talk.cjs +1 -1
  63. package/dist/hooks/use-push-to-talk.cjs.map +1 -1
  64. package/dist/hooks/use-push-to-talk.js +1 -1
  65. package/dist/hooks/use-push-to-talk.js.map +1 -1
  66. package/dist/http/resumable-upload.cjs +1 -1
  67. package/dist/http/resumable-upload.cjs.map +1 -1
  68. package/dist/http/resumable-upload.js +1 -1
  69. package/dist/http/resumable-upload.js.map +1 -1
  70. package/dist/icons/generated/aliases.cjs +1 -1
  71. package/dist/icons/generated/aliases.cjs.map +1 -1
  72. package/dist/icons/generated/aliases.js +1 -0
  73. package/dist/icons/generated/aliases.js.map +1 -1
  74. package/dist/icons/generated/icon-names.cjs +1 -1
  75. package/dist/icons/generated/icon-names.cjs.map +1 -1
  76. package/dist/icons/generated/icon-names.js +1 -1
  77. package/dist/icons/generated/icon-names.js.map +1 -1
  78. package/dist/icons/generated/loaders.cjs +1 -1
  79. package/dist/icons/generated/loaders.cjs.map +1 -1
  80. package/dist/icons/generated/loaders.js +48 -42
  81. package/dist/icons/generated/loaders.js.map +1 -1
  82. package/dist/icons/generated/shard-02.cjs +1 -1
  83. package/dist/icons/generated/shard-02.cjs.map +1 -1
  84. package/dist/icons/generated/shard-02.js +20 -20
  85. package/dist/icons/generated/shard-02.js.map +1 -1
  86. package/dist/icons/generated/shard-03.cjs +1 -1
  87. package/dist/icons/generated/shard-03.cjs.map +1 -1
  88. package/dist/icons/generated/shard-03.js +41 -41
  89. package/dist/icons/generated/shard-03.js.map +1 -1
  90. package/dist/icons/generated/shard-04.cjs +1 -1
  91. package/dist/icons/generated/shard-04.cjs.map +1 -1
  92. package/dist/icons/generated/shard-04.js +41 -41
  93. package/dist/icons/generated/shard-04.js.map +1 -1
  94. package/dist/icons/generated/shard-05.cjs +1 -1
  95. package/dist/icons/generated/shard-05.cjs.map +1 -1
  96. package/dist/icons/generated/shard-05.js +41 -41
  97. package/dist/icons/generated/shard-05.js.map +1 -1
  98. package/dist/icons/generated/shard-06.cjs +1 -1
  99. package/dist/icons/generated/shard-06.cjs.map +1 -1
  100. package/dist/icons/generated/shard-06.js +41 -41
  101. package/dist/icons/generated/shard-06.js.map +1 -1
  102. package/dist/icons/generated/shard-07.cjs +1 -1
  103. package/dist/icons/generated/shard-07.cjs.map +1 -1
  104. package/dist/icons/generated/shard-07.js +41 -41
  105. package/dist/icons/generated/shard-07.js.map +1 -1
  106. package/dist/icons/generated/shard-08.cjs +1 -1
  107. package/dist/icons/generated/shard-08.cjs.map +1 -1
  108. package/dist/icons/generated/shard-08.js +41 -41
  109. package/dist/icons/generated/shard-08.js.map +1 -1
  110. package/dist/icons/generated/shard-09.cjs +1 -1
  111. package/dist/icons/generated/shard-09.cjs.map +1 -1
  112. package/dist/icons/generated/shard-09.js +41 -41
  113. package/dist/icons/generated/shard-09.js.map +1 -1
  114. package/dist/icons/generated/shard-10.cjs +1 -1
  115. package/dist/icons/generated/shard-10.cjs.map +1 -1
  116. package/dist/icons/generated/shard-10.js +41 -41
  117. package/dist/icons/generated/shard-10.js.map +1 -1
  118. package/dist/icons/generated/shard-11.cjs +1 -1
  119. package/dist/icons/generated/shard-11.cjs.map +1 -1
  120. package/dist/icons/generated/shard-11.js +41 -41
  121. package/dist/icons/generated/shard-11.js.map +1 -1
  122. package/dist/icons/generated/shard-12.cjs +1 -1
  123. package/dist/icons/generated/shard-12.cjs.map +1 -1
  124. package/dist/icons/generated/shard-12.js +41 -41
  125. package/dist/icons/generated/shard-12.js.map +1 -1
  126. package/dist/icons/generated/shard-13.cjs +1 -1
  127. package/dist/icons/generated/shard-13.cjs.map +1 -1
  128. package/dist/icons/generated/shard-13.js +41 -41
  129. package/dist/icons/generated/shard-13.js.map +1 -1
  130. package/dist/icons/generated/shard-14.cjs +1 -1
  131. package/dist/icons/generated/shard-14.cjs.map +1 -1
  132. package/dist/icons/generated/shard-14.js +41 -41
  133. package/dist/icons/generated/shard-14.js.map +1 -1
  134. package/dist/icons/generated/shard-15.cjs +1 -1
  135. package/dist/icons/generated/shard-15.cjs.map +1 -1
  136. package/dist/icons/generated/shard-15.js +41 -41
  137. package/dist/icons/generated/shard-15.js.map +1 -1
  138. package/dist/icons/generated/shard-16.cjs +1 -1
  139. package/dist/icons/generated/shard-16.cjs.map +1 -1
  140. package/dist/icons/generated/shard-16.js +41 -41
  141. package/dist/icons/generated/shard-16.js.map +1 -1
  142. package/dist/icons/generated/shard-17.cjs +1 -1
  143. package/dist/icons/generated/shard-17.cjs.map +1 -1
  144. package/dist/icons/generated/shard-17.js +41 -41
  145. package/dist/icons/generated/shard-17.js.map +1 -1
  146. package/dist/icons/generated/shard-18.cjs +1 -1
  147. package/dist/icons/generated/shard-18.cjs.map +1 -1
  148. package/dist/icons/generated/shard-18.js +41 -41
  149. package/dist/icons/generated/shard-18.js.map +1 -1
  150. package/dist/icons/generated/shard-19.cjs +1 -1
  151. package/dist/icons/generated/shard-19.cjs.map +1 -1
  152. package/dist/icons/generated/shard-19.js +41 -41
  153. package/dist/icons/generated/shard-19.js.map +1 -1
  154. package/dist/icons/generated/shard-20.cjs +1 -1
  155. package/dist/icons/generated/shard-20.cjs.map +1 -1
  156. package/dist/icons/generated/shard-20.js +41 -41
  157. package/dist/icons/generated/shard-20.js.map +1 -1
  158. package/dist/icons/generated/shard-21.cjs +1 -1
  159. package/dist/icons/generated/shard-21.cjs.map +1 -1
  160. package/dist/icons/generated/shard-21.js +41 -41
  161. package/dist/icons/generated/shard-21.js.map +1 -1
  162. package/dist/icons/generated/shard-22.cjs +1 -1
  163. package/dist/icons/generated/shard-22.cjs.map +1 -1
  164. package/dist/icons/generated/shard-22.js +41 -41
  165. package/dist/icons/generated/shard-22.js.map +1 -1
  166. package/dist/icons/generated/shard-23.cjs +1 -1
  167. package/dist/icons/generated/shard-23.cjs.map +1 -1
  168. package/dist/icons/generated/shard-23.js +41 -41
  169. package/dist/icons/generated/shard-23.js.map +1 -1
  170. package/dist/icons/generated/shard-24.cjs +1 -1
  171. package/dist/icons/generated/shard-24.cjs.map +1 -1
  172. package/dist/icons/generated/shard-24.js +41 -41
  173. package/dist/icons/generated/shard-24.js.map +1 -1
  174. package/dist/icons/generated/shard-25.cjs +1 -1
  175. package/dist/icons/generated/shard-25.cjs.map +1 -1
  176. package/dist/icons/generated/shard-25.js +41 -41
  177. package/dist/icons/generated/shard-25.js.map +1 -1
  178. package/dist/icons/generated/shard-26.cjs +1 -1
  179. package/dist/icons/generated/shard-26.cjs.map +1 -1
  180. package/dist/icons/generated/shard-26.js +41 -41
  181. package/dist/icons/generated/shard-26.js.map +1 -1
  182. package/dist/icons/generated/shard-27.cjs +1 -1
  183. package/dist/icons/generated/shard-27.cjs.map +1 -1
  184. package/dist/icons/generated/shard-27.js +41 -41
  185. package/dist/icons/generated/shard-27.js.map +1 -1
  186. package/dist/icons/generated/shard-28.cjs +1 -1
  187. package/dist/icons/generated/shard-28.cjs.map +1 -1
  188. package/dist/icons/generated/shard-28.js +41 -41
  189. package/dist/icons/generated/shard-28.js.map +1 -1
  190. package/dist/icons/generated/shard-29.cjs +1 -1
  191. package/dist/icons/generated/shard-29.cjs.map +1 -1
  192. package/dist/icons/generated/shard-29.js +41 -41
  193. package/dist/icons/generated/shard-29.js.map +1 -1
  194. package/dist/icons/generated/shard-30.cjs +1 -1
  195. package/dist/icons/generated/shard-30.cjs.map +1 -1
  196. package/dist/icons/generated/shard-30.js +41 -41
  197. package/dist/icons/generated/shard-30.js.map +1 -1
  198. package/dist/icons/generated/shard-31.cjs +1 -1
  199. package/dist/icons/generated/shard-31.cjs.map +1 -1
  200. package/dist/icons/generated/shard-31.js +41 -41
  201. package/dist/icons/generated/shard-31.js.map +1 -1
  202. package/dist/icons/generated/shard-32.cjs +1 -1
  203. package/dist/icons/generated/shard-32.cjs.map +1 -1
  204. package/dist/icons/generated/shard-32.js +41 -41
  205. package/dist/icons/generated/shard-32.js.map +1 -1
  206. package/dist/icons/generated/shard-33.cjs +1 -1
  207. package/dist/icons/generated/shard-33.cjs.map +1 -1
  208. package/dist/icons/generated/shard-33.js +41 -41
  209. package/dist/icons/generated/shard-33.js.map +1 -1
  210. package/dist/icons/generated/shard-34.cjs +1 -1
  211. package/dist/icons/generated/shard-34.cjs.map +1 -1
  212. package/dist/icons/generated/shard-34.js +41 -41
  213. package/dist/icons/generated/shard-34.js.map +1 -1
  214. package/dist/icons/generated/shard-35.cjs +1 -1
  215. package/dist/icons/generated/shard-35.cjs.map +1 -1
  216. package/dist/icons/generated/shard-35.js +41 -41
  217. package/dist/icons/generated/shard-35.js.map +1 -1
  218. package/dist/icons/generated/shard-36.cjs +1 -1
  219. package/dist/icons/generated/shard-36.cjs.map +1 -1
  220. package/dist/icons/generated/shard-36.js +41 -41
  221. package/dist/icons/generated/shard-36.js.map +1 -1
  222. package/dist/icons/generated/shard-37.cjs +1 -1
  223. package/dist/icons/generated/shard-37.cjs.map +1 -1
  224. package/dist/icons/generated/shard-37.js +41 -41
  225. package/dist/icons/generated/shard-37.js.map +1 -1
  226. package/dist/icons/generated/shard-38.cjs +1 -1
  227. package/dist/icons/generated/shard-38.cjs.map +1 -1
  228. package/dist/icons/generated/shard-38.js +41 -41
  229. package/dist/icons/generated/shard-38.js.map +1 -1
  230. package/dist/icons/generated/shard-39.cjs +1 -1
  231. package/dist/icons/generated/shard-39.cjs.map +1 -1
  232. package/dist/icons/generated/shard-39.js +41 -41
  233. package/dist/icons/generated/shard-39.js.map +1 -1
  234. package/dist/icons/generated/shard-40.cjs +1 -1
  235. package/dist/icons/generated/shard-40.cjs.map +1 -1
  236. package/dist/icons/generated/shard-40.js +41 -41
  237. package/dist/icons/generated/shard-40.js.map +1 -1
  238. package/dist/icons/generated/shard-41.cjs +1 -1
  239. package/dist/icons/generated/shard-41.cjs.map +1 -1
  240. package/dist/icons/generated/shard-41.js +41 -41
  241. package/dist/icons/generated/shard-41.js.map +1 -1
  242. package/dist/icons/generated/shard-42.cjs +1 -1
  243. package/dist/icons/generated/shard-42.cjs.map +1 -1
  244. package/dist/icons/generated/shard-42.js +41 -41
  245. package/dist/icons/generated/shard-42.js.map +1 -1
  246. package/dist/icons/generated/shard-43.cjs +1 -1
  247. package/dist/icons/generated/shard-43.cjs.map +1 -1
  248. package/dist/icons/generated/shard-43.js +41 -41
  249. package/dist/icons/generated/shard-43.js.map +1 -1
  250. package/dist/icons/generated/shard-44.cjs +1 -1
  251. package/dist/icons/generated/shard-44.cjs.map +1 -1
  252. package/dist/icons/generated/shard-44.js +43 -10
  253. package/dist/icons/generated/shard-44.js.map +1 -1
  254. package/dist/icons/generated/shard-45.cjs +2 -0
  255. package/dist/icons/generated/shard-45.cjs.map +1 -0
  256. package/dist/icons/generated/shard-45.js +15 -0
  257. package/dist/icons/generated/shard-45.js.map +1 -0
  258. package/dist/icons/material-symbols.cjs +1 -1
  259. package/dist/icons/material-symbols.cjs.map +1 -1
  260. package/dist/icons/material-symbols.js +3 -3
  261. package/dist/icons/material-symbols.js.map +1 -1
  262. package/dist/icons.d.ts +4 -4
  263. package/dist/query/foreign-client-warning.cjs +1 -1
  264. package/dist/query/foreign-client-warning.cjs.map +1 -1
  265. package/dist/query/foreign-client-warning.js +1 -1
  266. package/dist/query/foreign-client-warning.js.map +1 -1
  267. package/dist/utils/json-frame.cjs +1 -1
  268. package/dist/utils/json-frame.cjs.map +1 -1
  269. package/dist/utils/json-frame.js +1 -1
  270. package/dist/utils/json-frame.js.map +1 -1
  271. package/dist/vision/core/providers.cjs +1 -1
  272. package/dist/vision/core/providers.cjs.map +1 -1
  273. package/dist/vision/core/providers.js +22 -3
  274. package/dist/vision/core/providers.js.map +1 -1
  275. package/dist/vision/core/session.cjs +1 -1
  276. package/dist/vision/core/session.cjs.map +1 -1
  277. package/dist/vision/core/session.js +22 -15
  278. package/dist/vision/core/session.js.map +1 -1
  279. package/dist/vision/fusion.cjs.map +1 -1
  280. package/dist/vision/fusion.js.map +1 -1
  281. package/dist/vision/index.cjs +1 -1
  282. package/dist/vision/index.cjs.map +1 -1
  283. package/dist/vision/index.js +17 -16
  284. package/dist/vision/index.js.map +1 -1
  285. package/dist/vision/normalization.cjs +2 -0
  286. package/dist/vision/normalization.cjs.map +1 -0
  287. package/dist/vision/normalization.js +49 -0
  288. package/dist/vision/normalization.js.map +1 -0
  289. package/dist/vision/results.cjs +1 -1
  290. package/dist/vision/results.cjs.map +1 -1
  291. package/dist/vision/results.js +8 -2
  292. package/dist/vision/results.js.map +1 -1
  293. package/dist/vision/tasks/classifier.cjs +1 -1
  294. package/dist/vision/tasks/classifier.cjs.map +1 -1
  295. package/dist/vision/tasks/classifier.js +36 -32
  296. package/dist/vision/tasks/classifier.js.map +1 -1
  297. package/dist/vision.cjs +1 -1
  298. package/dist/vision.d.ts +218 -13
  299. package/dist/vision.js +19 -18
  300. package/dist/vite/tempest-pwa-manifest.cjs +1 -1
  301. package/dist/vite/tempest-pwa-manifest.cjs.map +1 -1
  302. package/dist/vite/tempest-pwa-manifest.js +1 -1
  303. package/dist/vite/tempest-pwa-manifest.js.map +1 -1
  304. package/dist/webrtc/peer-link.cjs +1 -1
  305. package/dist/webrtc/peer-link.cjs.map +1 -1
  306. package/dist/webrtc/peer-link.js +1 -1
  307. package/dist/webrtc/peer-link.js.map +1 -1
  308. package/dist/webrtc/peer-mesh.cjs +1 -1
  309. package/dist/webrtc/peer-mesh.cjs.map +1 -1
  310. package/dist/webrtc/peer-mesh.js +1 -1
  311. package/dist/webrtc/peer-mesh.js.map +1 -1
  312. package/dist/ws/create-web-socket.cjs +1 -1
  313. package/dist/ws/create-web-socket.cjs.map +1 -1
  314. package/dist/ws/create-web-socket.js +1 -1
  315. package/dist/ws/create-web-socket.js.map +1 -1
  316. package/package.json +1 -1
@@ -1 +1 @@
1
- {"version":3,"file":"json-frame.js","names":[],"sources":["../../src/utils/json-frame.ts"],"sourcesContent":["import { isDevBuild } from \"./dev-mode\";\n\n/**\n * The one decoder behind `createWebSocket`, `useWebSocket` and\n * `createEventStream`.\n *\n * Internal, and imported by path rather than through the `utils` barrel: it\n * exists so the three transports share one answer to \"the frame is not JSON\",\n * not so consumers can call it.\n *\n * That question used to have three identical copies of the same wrong answer —\n * `return raw as unknown as T`, which hands the consumer a `string` announced as\n * `T`. The failure never surfaced at the parse; it surfaced later, on the first\n * `message.id`, with nothing left to say the frame had not been JSON.\n */\n\n/** Outcome of decoding one frame. */\nexport interface DecodedFrame<T> {\n /** Whether the message should reach `onMessage`. */\n delivered: boolean;\n /** The decoded payload. Only meaningful when `delivered` is `true`. */\n data: T;\n}\n\nconst warned = new Set<string>();\n\n/**\n * Warn once per transport that a frame arrived which was not JSON.\n *\n * Once, because a stream sending text frames sends many, and a console line per\n * frame buries the one that mattered. Development builds only.\n *\n * @param transport - Label used in the message, e.g. `\"createWebSocket\"`.\n * @returns Nothing.\n */\nfunction warnOnce(transport: string): void {\n if (!isDevBuild() || warned.has(transport)) return;\n warned.add(transport);\n console.warn(\n `[tempest-react-sdk] ${transport}: a frame was not valid JSON, so the raw string is ` +\n `being delivered as if it were your message type. Pass \\`parser\\` to decode it, or ` +\n `\\`onParseError\\` to drop it and handle the failure. This warning appears once.`,\n );\n}\n\n/**\n * Decode one frame, reporting whether it should be delivered.\n *\n * A caller-supplied `parser` owns the frame completely and its result is always\n * delivered — decoding text, binary-as-base64 or a protocol of its own is the\n * point of that option.\n *\n * Without one, the frame is parsed as JSON. When that throws:\n *\n * - with `onParseError`, the callback fires and the frame is **not** delivered,\n * because a consumer that asked to hear about failures did not ask to also\n * receive the broken frame;\n * - without it, the raw string is delivered as `T` — the behaviour every version\n * before this one had, kept so nothing breaks — and development builds warn\n * once that it happened.\n *\n * @param raw - The frame body as text.\n * @param parser - Caller-supplied decoder, if any.\n * @param onParseError - Caller-supplied failure handler, if any.\n * @param transport - Label used in the development warning.\n * @returns Whether to deliver, and the payload.\n */\nexport function decodeFrame<T>(\n raw: string,\n parser: ((raw: string) => T) | undefined,\n onParseError: ((error: unknown, raw: string) => void) | undefined,\n transport: string,\n): DecodedFrame<T> {\n if (parser) return { delivered: true, data: parser(raw) };\n try {\n return { delivered: true, data: JSON.parse(raw) as T };\n } catch (error) {\n if (onParseError) {\n onParseError(error, raw);\n return { delivered: false, data: undefined as T };\n }\n warnOnce(transport);\n return { delivered: true, data: raw as unknown as T };\n }\n}\n\n/**\n * Forget which transports have already warned.\n *\n * Exists for tests, which would otherwise see the first case swallow the\n * warning for every case after it.\n *\n * @returns Nothing.\n */\nexport function resetFrameWarnings(): void {\n warned.clear();\n}\n"],"mappings":";;AAwBA,IAAM,oBAAS,IAAI,IAAY;AAW/B,SAAS,EAAS,GAAyB;CACnC,CAAC,EAAW,KAAK,EAAO,IAAI,CAAS,MACzC,EAAO,IAAI,CAAS,GACpB,QAAQ,KACJ,uBAAuB,EAAU,oNAGrC;AACJ;AAwBA,SAAgB,EACZ,GACA,GACA,GACA,GACe;CACf,IAAI,GAAQ,OAAO;EAAE,WAAW;EAAM,MAAM,EAAO,CAAG;CAAE;CACxD,IAAI;EACA,OAAO;GAAE,WAAW;GAAM,MAAM,KAAK,MAAM,CAAG;EAAO;CACzD,SAAS,GAAO;EAMZ,OALI,KACA,EAAa,GAAO,CAAG,GAChB;GAAE,WAAW;GAAO,MAAM,KAAA;EAAe,MAEpD,EAAS,CAAS,GACX;GAAE,WAAW;GAAM,MAAM;EAAoB;CACxD;AACJ"}
1
+ {"version":3,"file":"json-frame.js","names":[],"sources":["../../src/utils/json-frame.ts"],"sourcesContent":["import { isDevBuild } from \"./dev-mode\";\n\n/**\n * The one decoder behind `createWebSocket`, `useWebSocket` and\n * `createEventStream`.\n *\n * Internal, and imported by path rather than through the `utils` barrel: it\n * exists so the three transports share one answer to \"the frame is not JSON\",\n * not so consumers can call it.\n *\n * That question used to have three identical copies of the same wrong answer —\n * `return raw as unknown as T`, which hands the consumer a `string` announced as\n * `T`. The failure never surfaced at the parse; it surfaced later, on the first\n * `message.id`, with nothing left to say the frame had not been JSON.\n */\n\n/** Outcome of decoding one frame. */\nexport interface DecodedFrame<T> {\n /** Whether the message should reach `onMessage`. */\n delivered: boolean;\n /** The decoded payload. Only meaningful when `delivered` is `true`. */\n data: T;\n}\n\nconst warned = new Set<string>();\n\n/**\n * Warn once per transport that a frame arrived which was not JSON.\n *\n * Once, because a stream sending text frames sends many, and a console line per\n * frame buries the one that mattered. Development builds only.\n *\n * @param transport - Label used in the message, e.g. `\"createWebSocket\"`.\n * @returns Nothing.\n */\nfunction warnOnce(transport: string): void {\n if (!isDevBuild() || warned.has(transport)) return;\n warned.add(transport);\n console.warn(\n `[tempest-react-sdk] ${transport}: a frame was not valid JSON, so the raw string is ` +\n `being delivered as if it were your message type. Pass \\`parser\\` to decode it, or ` +\n `\\`onParseError\\` to drop it and handle the failure. This warning appears once.`,\n );\n}\n\n/**\n * Decode one frame, reporting whether it should be delivered.\n *\n * A caller-supplied `parser` owns the frame completely and its result is always\n * delivered — decoding text, binary-as-base64 or a protocol of its own is the\n * point of that option.\n *\n * Without one, the frame is parsed as JSON. When that throws:\n *\n * - with `onParseError`, the callback fires and the frame is **not** delivered,\n * because a consumer that asked to hear about failures did not ask to also\n * receive the broken frame;\n * - without it, the raw string is delivered as `T` — the behaviour every version\n * before this one had, kept so nothing breaks — and development builds warn\n * once that it happened.\n *\n * @param raw - The frame body as text.\n * @param parser - Caller-supplied decoder, if any.\n * @param onParseError - Caller-supplied failure handler, if any.\n * @param transport - Label used in the development warning.\n * @returns Whether to deliver, and the payload.\n */\nexport function decodeFrame<T>(\n raw: string,\n parser: ((raw: string) => T) | undefined,\n onParseError: ((error: unknown, raw: string) => void) | undefined,\n transport: string,\n): DecodedFrame<T> {\n if (parser) return { delivered: true, data: parser(raw) };\n try {\n return { delivered: true, data: JSON.parse(raw) as T };\n } catch (error) {\n if (onParseError) {\n onParseError(error, raw);\n return { delivered: false, data: undefined as T };\n }\n warnOnce(transport);\n return { delivered: true, data: raw as unknown as T };\n }\n}\n\n/**\n * Forget which transports have already warned.\n *\n * Exists for tests, which would otherwise see the first case swallow the\n * warning for every case after it.\n *\n * @returns Nothing.\n */\nexport function resetFrameWarnings(): void {\n warned.clear();\n}\n"],"mappings":";;AAwBA,IAAM,oBAAS,IAAI,IAAY;AAW/B,SAAS,EAAS,GAAyB;CACnC,AAAC,EAAW,KAAK,GAAO,IAAI,CAAS,MACzC,EAAO,IAAI,CAAS,GACpB,QAAQ,KACJ,uBAAuB,EAAU,oNAGrC;AACJ;AAwBA,SAAgB,EACZ,GACA,GACA,GACA,GACe;CACf,IAAI,GAAQ,OAAO;EAAE,WAAW;EAAM,MAAM,EAAO,CAAG;CAAE;CACxD,IAAI;EACA,OAAO;GAAE,WAAW;GAAM,MAAM,KAAK,MAAM,CAAG;EAAO;CACzD,SAAS,GAAO;EAMZ,OALI,KACA,EAAa,GAAO,CAAG,GAChB;GAAE,WAAW;GAAO,MAAM,KAAA;EAAe,MAEpD,EAAS,CAAS,GACX;GAAE,WAAW;GAAM,MAAM;EAAoB;CACxD;AACJ"}
@@ -1,2 +1,2 @@
1
- var e=[`webgpu`,`wasm`];function t(t){return t===void 0||t.length===0?[...e]:[...t]}exports.DEFAULT_PROVIDERS=e,exports.resolveProviders=t;
1
+ var e=[`webgpu`,`wasm`],t=`wasm`;function n(t){return t===void 0||t.length===0?[...e]:[...t]}async function r(e){let t=await i();return e.filter(e=>{switch(e){case`webgpu`:return t;case`webnn`:return typeof navigator<`u`&&`ml`in navigator;default:return!0}})}async function i(){let e=globalThis.navigator?.gpu;if(e===void 0)return!1;try{return await e.requestAdapter()!==null}catch{return!1}}exports.DEFAULT_PROVIDERS=e,exports.FALLBACK_PROVIDER=t,exports.detectProviders=r,exports.resolveProviders=n;
2
2
  //# sourceMappingURL=providers.cjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"providers.cjs","names":[],"sources":["../../../src/vision/core/providers.ts"],"sourcesContent":["/** @generated Vendored from @mauriciobenjamin700/ort-vision-sdk-web. Do not hand-edit — regenerate with `npm run vendor:vision`. */\n/**\n * Execution-provider defaults for ONNX Runtime Web sessions.\n *\n * Unlike Node ORT, the browser ORT cannot enumerate \"available providers\" at\n * runtime — `webgpu` either works or ORT silently falls back to the next\n * provider in the list. We just expose a sensible default order.\n */\n\n/**\n * Default execution provider preference order for browser ORT.\n *\n * `webgpu` is tried first when available; ORT-Web falls back to `wasm`\n * automatically when WebGPU is not supported by the browser or device.\n */\nexport const DEFAULT_PROVIDERS: readonly string[] = [\"webgpu\", \"wasm\"];\n\n/**\n * Resolve the execution providers to pass to `InferenceSession.create`.\n *\n * @param requested Explicit provider list in preference order; `undefined` returns the default.\n */\nexport function resolveProviders(requested?: readonly string[]): string[] {\n if (requested === undefined) {\n return [...DEFAULT_PROVIDERS];\n }\n if (requested.length === 0) {\n return [...DEFAULT_PROVIDERS];\n }\n return [...requested];\n}\n"],"mappings":"AAeA,IAAa,EAAuC,CAAC,SAAU,MAAM,EAOrE,SAAgB,EAAiB,EAAyC,CAOtE,OANI,IAAc,IAAA,IAGd,EAAU,SAAW,EACd,CAAC,GAAG,CAAiB,EAEzB,CAAC,GAAG,CAAS,CACxB"}
1
+ {"version":3,"file":"providers.cjs","names":[],"sources":["../../../src/vision/core/providers.ts"],"sourcesContent":["/** @generated Vendored from @mauriciobenjamin700/ort-vision-sdk-web. Do not hand-edit — regenerate with `npm run vendor:vision`. */\n/**\n * Execution-provider defaults for ONNX Runtime Web sessions.\n *\n * Unlike Node ORT, the browser ORT cannot enumerate \"available providers\" at\n * runtime — `webgpu` either works or ORT silently falls back to the next\n * provider in the list. We just expose a sensible default order.\n */\n\n/**\n * Default execution provider preference order for browser ORT.\n *\n * `webgpu` is tried first when available; ORT-Web falls back to `wasm`\n * automatically when WebGPU is not supported by the browser or device.\n */\nexport const DEFAULT_PROVIDERS: readonly string[] = [\"webgpu\", \"wasm\"];\n\n/**\n * The provider ORT-Web can always run, whatever the device.\n *\n * Used as the floor when capability detection rules everything else out. Passing\n * ORT a list it cannot satisfy is not a graceful failure — `InferenceSession.create`\n * rejects with \"no available backend found\" and the page gets no inference at\n * all, which is worse than the slow-but-working fallback the warning describes.\n */\nexport const FALLBACK_PROVIDER = \"wasm\";\n\n/**\n * Resolve the execution providers to pass to `InferenceSession.create`.\n *\n * @param requested Explicit provider list in preference order; `undefined` returns the default.\n */\nexport function resolveProviders(requested?: readonly string[]): string[] {\n if (requested === undefined) {\n return [...DEFAULT_PROVIDERS];\n }\n if (requested.length === 0) {\n return [...DEFAULT_PROVIDERS];\n }\n return [...requested];\n}\n\n/**\n * Narrow a provider list to the ones this browser can actually offer.\n *\n * ORT-Web exposes no equivalent of Node's `session.getProviders()`, so there is\n * no way to ask which provider a session ended up on. What the browser *does*\n * answer is whether the underlying API exists at all — no `navigator.gpu`, or no\n * adapter behind it, means `webgpu` was never going to run — and that covers the\n * case that actually bites: a page asking for WebGPU on a device without it,\n * silently getting WASM, and being several times slower than intended with no\n * error to point at.\n *\n * This is best-effort by construction. A provider that survives here can still\n * fail inside ORT for a reason the browser does not surface (a missing shader\n * feature, an exhausted device), so a surviving entry means \"not ruled out\",\n * not \"confirmed running\". Anything this function does not know how to test is\n * kept rather than dropped: guessing a provider away would be worse than\n * admitting ignorance about it.\n *\n * @param requested Providers in preference order, already resolved.\n * @returns The subset that is not ruled out, in the same order.\n */\nexport async function detectProviders(requested: readonly string[]): Promise<string[]> {\n const webgpu = await hasWebGpuAdapter();\n return requested.filter((provider) => {\n switch (provider) {\n case \"webgpu\":\n return webgpu;\n case \"webnn\":\n return typeof navigator !== \"undefined\" && \"ml\" in navigator;\n default:\n return true;\n }\n });\n}\n\n/**\n * Whether this environment exposes a WebGPU adapter.\n *\n * `navigator.gpu` existing is not enough — a browser can ship the API and still\n * hand back no adapter (a blocklisted driver, a headless context, a machine with\n * no suitable GPU), which is exactly the configuration where a page asks for\n * WebGPU and quietly runs on WASM.\n */\nasync function hasWebGpuAdapter(): Promise<boolean> {\n const gpu = (\n globalThis.navigator as { gpu?: { requestAdapter(): Promise<unknown> } } | undefined\n )?.gpu;\n if (gpu === undefined) {\n return false;\n }\n try {\n return (await gpu.requestAdapter()) !== null;\n } catch {\n return false;\n }\n}\n"],"mappings":"AAeA,IAAa,EAAuC,CAAC,SAAU,MAAM,EAUxD,EAAoB,OAOjC,SAAgB,EAAiB,EAAyC,CAOtE,OANI,IAAc,IAAA,IAGd,EAAU,SAAW,EACd,CAAC,GAAG,CAAiB,EAEzB,CAAC,GAAG,CAAS,CACxB,CAuBA,eAAsB,EAAgB,EAAiD,CACnF,IAAM,EAAS,MAAM,EAAiB,EACtC,OAAO,EAAU,OAAQ,GAAa,CAClC,OAAQ,EAAR,CACI,IAAK,SACD,OAAO,EACX,IAAK,QACD,OAAO,OAAO,UAAc,KAAe,OAAQ,UACvD,QACI,MAAO,EACf,CACJ,CAAC,CACL,CAUA,eAAe,GAAqC,CAChD,IAAM,EACF,WAAW,WACZ,IACH,GAAI,IAAQ,IAAA,GACR,MAAO,GAEX,GAAI,CACA,OAAQ,MAAM,EAAI,eAAe,IAAO,IAC5C,MAAQ,CACJ,MAAO,EACX,CACJ"}
@@ -1,9 +1,28 @@
1
1
  //#region src/vision/core/providers.ts
2
- var e = ["webgpu", "wasm"];
3
- function t(t) {
2
+ var e = ["webgpu", "wasm"], t = "wasm";
3
+ function n(t) {
4
4
  return t === void 0 || t.length === 0 ? [...e] : [...t];
5
5
  }
6
+ async function r(e) {
7
+ let t = await i();
8
+ return e.filter((e) => {
9
+ switch (e) {
10
+ case "webgpu": return t;
11
+ case "webnn": return typeof navigator < "u" && "ml" in navigator;
12
+ default: return !0;
13
+ }
14
+ });
15
+ }
16
+ async function i() {
17
+ let e = globalThis.navigator?.gpu;
18
+ if (e === void 0) return !1;
19
+ try {
20
+ return await e.requestAdapter() !== null;
21
+ } catch {
22
+ return !1;
23
+ }
24
+ }
6
25
  //#endregion
7
- export { e as DEFAULT_PROVIDERS, t as resolveProviders };
26
+ export { e as DEFAULT_PROVIDERS, t as FALLBACK_PROVIDER, r as detectProviders, n as resolveProviders };
8
27
 
9
28
  //# sourceMappingURL=providers.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"providers.js","names":[],"sources":["../../../src/vision/core/providers.ts"],"sourcesContent":["/** @generated Vendored from @mauriciobenjamin700/ort-vision-sdk-web. Do not hand-edit — regenerate with `npm run vendor:vision`. */\n/**\n * Execution-provider defaults for ONNX Runtime Web sessions.\n *\n * Unlike Node ORT, the browser ORT cannot enumerate \"available providers\" at\n * runtime — `webgpu` either works or ORT silently falls back to the next\n * provider in the list. We just expose a sensible default order.\n */\n\n/**\n * Default execution provider preference order for browser ORT.\n *\n * `webgpu` is tried first when available; ORT-Web falls back to `wasm`\n * automatically when WebGPU is not supported by the browser or device.\n */\nexport const DEFAULT_PROVIDERS: readonly string[] = [\"webgpu\", \"wasm\"];\n\n/**\n * Resolve the execution providers to pass to `InferenceSession.create`.\n *\n * @param requested Explicit provider list in preference order; `undefined` returns the default.\n */\nexport function resolveProviders(requested?: readonly string[]): string[] {\n if (requested === undefined) {\n return [...DEFAULT_PROVIDERS];\n }\n if (requested.length === 0) {\n return [...DEFAULT_PROVIDERS];\n }\n return [...requested];\n}\n"],"mappings":";AAeA,IAAa,IAAuC,CAAC,UAAU,MAAM;AAOrE,SAAgB,EAAiB,GAAyC;CAOtE,OANI,MAAc,KAAA,KAGd,EAAU,WAAW,IACd,CAAC,GAAG,CAAiB,IAEzB,CAAC,GAAG,CAAS;AACxB"}
1
+ {"version":3,"file":"providers.js","names":[],"sources":["../../../src/vision/core/providers.ts"],"sourcesContent":["/** @generated Vendored from @mauriciobenjamin700/ort-vision-sdk-web. Do not hand-edit — regenerate with `npm run vendor:vision`. */\n/**\n * Execution-provider defaults for ONNX Runtime Web sessions.\n *\n * Unlike Node ORT, the browser ORT cannot enumerate \"available providers\" at\n * runtime — `webgpu` either works or ORT silently falls back to the next\n * provider in the list. We just expose a sensible default order.\n */\n\n/**\n * Default execution provider preference order for browser ORT.\n *\n * `webgpu` is tried first when available; ORT-Web falls back to `wasm`\n * automatically when WebGPU is not supported by the browser or device.\n */\nexport const DEFAULT_PROVIDERS: readonly string[] = [\"webgpu\", \"wasm\"];\n\n/**\n * The provider ORT-Web can always run, whatever the device.\n *\n * Used as the floor when capability detection rules everything else out. Passing\n * ORT a list it cannot satisfy is not a graceful failure — `InferenceSession.create`\n * rejects with \"no available backend found\" and the page gets no inference at\n * all, which is worse than the slow-but-working fallback the warning describes.\n */\nexport const FALLBACK_PROVIDER = \"wasm\";\n\n/**\n * Resolve the execution providers to pass to `InferenceSession.create`.\n *\n * @param requested Explicit provider list in preference order; `undefined` returns the default.\n */\nexport function resolveProviders(requested?: readonly string[]): string[] {\n if (requested === undefined) {\n return [...DEFAULT_PROVIDERS];\n }\n if (requested.length === 0) {\n return [...DEFAULT_PROVIDERS];\n }\n return [...requested];\n}\n\n/**\n * Narrow a provider list to the ones this browser can actually offer.\n *\n * ORT-Web exposes no equivalent of Node's `session.getProviders()`, so there is\n * no way to ask which provider a session ended up on. What the browser *does*\n * answer is whether the underlying API exists at all — no `navigator.gpu`, or no\n * adapter behind it, means `webgpu` was never going to run — and that covers the\n * case that actually bites: a page asking for WebGPU on a device without it,\n * silently getting WASM, and being several times slower than intended with no\n * error to point at.\n *\n * This is best-effort by construction. A provider that survives here can still\n * fail inside ORT for a reason the browser does not surface (a missing shader\n * feature, an exhausted device), so a surviving entry means \"not ruled out\",\n * not \"confirmed running\". Anything this function does not know how to test is\n * kept rather than dropped: guessing a provider away would be worse than\n * admitting ignorance about it.\n *\n * @param requested Providers in preference order, already resolved.\n * @returns The subset that is not ruled out, in the same order.\n */\nexport async function detectProviders(requested: readonly string[]): Promise<string[]> {\n const webgpu = await hasWebGpuAdapter();\n return requested.filter((provider) => {\n switch (provider) {\n case \"webgpu\":\n return webgpu;\n case \"webnn\":\n return typeof navigator !== \"undefined\" && \"ml\" in navigator;\n default:\n return true;\n }\n });\n}\n\n/**\n * Whether this environment exposes a WebGPU adapter.\n *\n * `navigator.gpu` existing is not enough — a browser can ship the API and still\n * hand back no adapter (a blocklisted driver, a headless context, a machine with\n * no suitable GPU), which is exactly the configuration where a page asks for\n * WebGPU and quietly runs on WASM.\n */\nasync function hasWebGpuAdapter(): Promise<boolean> {\n const gpu = (\n globalThis.navigator as { gpu?: { requestAdapter(): Promise<unknown> } } | undefined\n )?.gpu;\n if (gpu === undefined) {\n return false;\n }\n try {\n return (await gpu.requestAdapter()) !== null;\n } catch {\n return false;\n }\n}\n"],"mappings":";AAeA,IAAa,IAAuC,CAAC,UAAU,MAAM,GAUxD,IAAoB;AAOjC,SAAgB,EAAiB,GAAyC;CAOtE,OANI,MAAc,KAAA,KAGd,EAAU,WAAW,IACd,CAAC,GAAG,CAAiB,IAEzB,CAAC,GAAG,CAAS;AACxB;AAuBA,eAAsB,EAAgB,GAAiD;CACnF,IAAM,IAAS,MAAM,EAAiB;CACtC,OAAO,EAAU,QAAQ,MAAa;EAClC,QAAQ,GAAR;GACI,KAAK,UACD,OAAO;GACX,KAAK,SACD,OAAO,OAAO,YAAc,OAAe,QAAQ;GACvD,SACI,OAAO;EACf;CACJ,CAAC;AACL;AAUA,eAAe,IAAqC;CAChD,IAAM,IACF,WAAW,WACZ;CACH,IAAI,MAAQ,KAAA,GACR,OAAO;CAEX,IAAI;EACA,OAAQ,MAAM,EAAI,eAAe,MAAO;CAC5C,QAAQ;EACJ,OAAO;CACX;AACJ"}
@@ -1,2 +1,2 @@
1
- const e=require("../../_virtual/_rolldown/runtime.cjs"),t=require("./exceptions.cjs"),n=require("./graph.cjs"),r=require("./metadata.cjs"),i=require("./providers.cjs");let a=require("onnxruntime-web");a=e.__toESM(a,1);async function o(e){try{let t=await fetch(e);return t.ok?new Uint8Array(await t.arrayBuffer()):(s(e,`HTTP ${t.status} ${t.statusText}`),e)}catch(t){return s(e,t.message),e}}function s(e,t){console.warn(`[@ort-vision-sdk/web] Could not fetch ${e} to read its metadata (${t}). Letting ONNX Runtime load it instead: the model will work, but its baked-in class names are unavailable, so labels fall back to class_0, class_1, ... Pass \`labels\` explicitly to name them.`)}var c=class e{_session;providers;_metadata;constructor(e,t,n){this._session=e,this.providers=t,this._metadata=n}static async create(n,s={}){let c=i.resolveProviders(s.providers),l={...s.sessionOptions??{},executionProviders:c},u=s.readMetadata!==!1,d=typeof n==`string`&&u?await o(n):n,f=u&&typeof d!=`string`?r.readModelMetadata(d):{},p;try{p=(typeof d==`string`||d instanceof Uint8Array,await a.InferenceSession.create(d,l))}catch(e){throw new t.ModelLoadError(`Failed to load ONNX model: ${e.message}`,{cause:e})}return new e(p,c,f)}get inputNames(){return this._session.inputNames}get inputName(){let e=this._session.inputNames[0];if(e===void 0)throw new t.InferenceError(`Model has no inputs.`);return e}get outputNames(){return this._session.outputNames}get inputShapes(){return n.declaredShapesFrom(this._session.inputMetadata)}get inputShape(){return this.inputShapes[0]??[]}get outputShapes(){return n.declaredShapesFrom(this._session.outputMetadata)}get outputShape(){return this.outputShapes[0]??[]}get metadata(){return this._metadata}async release(){await this._session.release().catch(()=>void 0)}get raw(){return this._session}async run(e){try{return await this._session.run(e)}catch(e){throw new t.InferenceError(`Inference failed: ${e.message}`,{cause:e})}}};exports.OrtSession=c;
1
+ const e=require("../../_virtual/_rolldown/runtime.cjs"),t=require("./exceptions.cjs"),n=require("./graph.cjs"),r=require("./metadata.cjs"),i=require("./providers.cjs");let a=require("onnxruntime-web");a=e.__toESM(a,1);async function o(e){try{let t=await fetch(e);return t.ok?new Uint8Array(await t.arrayBuffer()):(s(e,`HTTP ${t.status} ${t.statusText}`),e)}catch(t){return s(e,t.message),e}}function s(e,t){console.warn(`[@ort-vision-sdk/web] Could not fetch ${e} to read its metadata (${t}). Letting ONNX Runtime load it instead: the model will work, but its baked-in class names are unavailable, so labels fall back to class_0, class_1, ... Pass \`labels\` explicitly to name them.`)}function c(e,t){let n=e.filter(e=>!t.includes(e));n.length!==0&&console.warn(`This browser cannot offer the requested execution provider(s) ${JSON.stringify(n)}; the session will run on ${JSON.stringify(t)}. Inference still produces correct results, on the fallback provider.`)}var l=class e{_session;providers;_metadata;requestedProviders;constructor(e,t,n,r){this._session=e,this.providers=t,this._metadata=n,this.requestedProviders=r}static async create(n,s={}){let l=i.resolveProviders(s.providers),u=await i.detectProviders(l),d=u.length>0?u:[i.FALLBACK_PROVIDER];s.providers!==void 0&&s.providers.length>0&&c(l,d);let f={...s.sessionOptions??{},executionProviders:d},p=s.readMetadata!==!1,m=typeof n==`string`&&p?await o(n):n,h=p&&typeof m!=`string`?r.readModelMetadata(m):{},g;try{g=(typeof m==`string`||m instanceof Uint8Array,await a.InferenceSession.create(m,f))}catch(e){throw new t.ModelLoadError(`Failed to load ONNX model: ${e.message}`,{cause:e})}return new e(g,d,h,l)}get inputNames(){return this._session.inputNames}get inputName(){let e=this._session.inputNames[0];if(e===void 0)throw new t.InferenceError(`Model has no inputs.`);return e}get outputNames(){return this._session.outputNames}get inputShapes(){return n.declaredShapesFrom(this._session.inputMetadata)}get inputShape(){return this.inputShapes[0]??[]}get outputShapes(){return n.declaredShapesFrom(this._session.outputMetadata)}get outputShape(){return this.outputShapes[0]??[]}get metadata(){return this._metadata}async release(){await this._session.release().catch(()=>void 0)}get raw(){return this._session}async run(e){try{return await this._session.run(e)}catch(e){throw new t.InferenceError(`Inference failed: ${e.message}`,{cause:e})}}};exports.OrtSession=l;
2
2
  //# sourceMappingURL=session.cjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"session.cjs","names":[],"sources":["../../../src/vision/core/session.ts"],"sourcesContent":["/** @generated Vendored from @mauriciobenjamin700/ort-vision-sdk-web. Do not hand-edit — regenerate with `npm run vendor:vision`. */\n/**\n * Thin wrapper around `onnxruntime-web` `InferenceSession` with typed metadata.\n */\n\nimport type * as ort from \"onnxruntime-web\";\nimport * as ortRuntime from \"onnxruntime-web\";\n\nimport { InferenceError, ModelLoadError } from \"./exceptions\";\nimport { type DeclaredShape, declaredShapesFrom } from \"./graph\";\nimport { readModelMetadata } from \"./metadata\";\nimport { resolveProviders } from \"./providers\";\n\n/** Anything `InferenceSession.create` accepts. */\nexport type ModelSource = string | ArrayBufferLike | Uint8Array;\n\n/**\n * Fetch a model URL as bytes so its metadata can be read.\n *\n * Falls back to the URL itself when the fetch fails, letting ORT try its own\n * load path: losing the metadata map is a downgrade, but failing to load a model\n * that ORT could have fetched would be a regression.\n *\n * @param url Where the `.onnx` lives.\n * @returns The model bytes, or the original URL when they could not be fetched.\n */\nasync function fetchModel(url: string): Promise<Uint8Array | string> {\n try {\n const response = await fetch(url);\n if (!response.ok) {\n warnMetadataUnavailable(url, `HTTP ${response.status} ${response.statusText}`);\n return url;\n }\n return new Uint8Array(await response.arrayBuffer());\n } catch (err) {\n warnMetadataUnavailable(url, (err as Error).message);\n return url;\n }\n}\n\n/**\n * Warn that a model's metadata could not be read, and say what that costs.\n *\n * The fallback itself is right — losing the metadata beats failing a load that\n * ORT could have completed on its own — but it used to be silent, and the\n * symptom it produces is remote from the cause: class names come back as\n * `class_0`, `class_1`, ... with nothing anywhere explaining why. Whoever hits\n * this needs to be told that passing `labels` is the way out.\n *\n * @param url The model URL that could not be fetched here.\n * @param reason What went wrong, as reported by `fetch`.\n */\nfunction warnMetadataUnavailable(url: string, reason: string): void {\n console.warn(\n `[@ort-vision-sdk/web] Could not fetch ${url} to read its metadata (${reason}). ` +\n \"Letting ONNX Runtime load it instead: the model will work, but its baked-in \" +\n \"class names are unavailable, so labels fall back to class_0, class_1, ... \" +\n \"Pass `labels` explicitly to name them.\",\n );\n}\n\nexport interface OrtSessionOptions {\n /** Execution providers in preference order. `undefined` uses {@link DEFAULT_PROVIDERS}. */\n readonly providers?: readonly string[];\n /** Optional ORT session options forwarded to `InferenceSession.create`. */\n readonly sessionOptions?: ort.InferenceSession.SessionOptions;\n /**\n * Whether to read the model's custom metadata map (`names`, `task`, `imgsz`).\n * Defaults to `true`.\n *\n * The runtime does not expose that map, so it is read from the file itself —\n * which means a URL model is fetched here and handed to ORT as bytes instead\n * of letting ORT fetch it. That is the same single download either way, and\n * it is what lets a task resolve its labels off the model. Set to `false` to\n * keep the URL path untouched and leave {@link OrtSession.metadata} empty.\n *\n * `false` is also the escape hatch when a device cannot afford the bytes: the\n * fetched buffer is dropped before ORT builds the graph (see\n * {@link OrtSession.create}), but ORT's own load path still keeps the model out\n * of reach of anything the SDK holds. A session built this way resolves its\n * input size from the graph as usual — only the class names are lost, so a\n * caller taking this route has to pass `labels` itself.\n */\n readonly readMetadata?: boolean;\n}\n\n/**\n * Wrap an ONNX Runtime Web `InferenceSession` with convenient metadata access.\n *\n * The wrapper exposes input/output names and the shapes the graph declares,\n * manages execution-provider selection, provides a typed {@link OrtSession.run}\n * method, and releases the native session through {@link OrtSession.release}.\n */\nexport class OrtSession {\n private constructor(\n private readonly _session: ort.InferenceSession,\n public readonly providers: readonly string[],\n private readonly _metadata: Readonly<Record<string, string>>,\n ) {}\n\n /**\n * Load an ONNX model into an ORT inference session.\n *\n * The metadata map is read **before** the session is built, and that order is\n * load-bearing on memory-constrained devices. ORT copies the model into its\n * WASM heap and then allocates the graph and the weights on top of that copy;\n * a `readModelMetadata` call placed after `InferenceSession.create` keeps the\n * JavaScript-side buffer reachable across the whole build, so a 5 MB model\n * costs 5 MB of JS heap plus 5 MB of WASM heap plus the weights at the same\n * instant. Reading first makes the buffer collectable as soon as ORT has copied\n * it — on a phone that was the difference between a session and\n * `Can't create a session. failed to allocate a buffer of size N`.\n *\n * @param model Either a URL string, or a `Uint8Array`/`ArrayBuffer` containing the model bytes.\n * @param options Provider list, pass-through `SessionOptions`, and whether to\n * read the model's metadata map (see {@link OrtSessionOptions.readMetadata}).\n * @throws {@link ModelLoadError} if the model cannot be loaded.\n */\n static async create(model: ModelSource, options: OrtSessionOptions = {}): Promise<OrtSession> {\n const providers = resolveProviders(options.providers);\n const sessionOptions: ort.InferenceSession.SessionOptions = {\n ...(options.sessionOptions ?? {}),\n executionProviders:\n providers as ort.InferenceSession.SessionOptions[\"executionProviders\"],\n };\n const wantsMetadata = options.readMetadata !== false;\n const source = typeof model === \"string\" && wantsMetadata ? await fetchModel(model) : model;\n const metadata =\n wantsMetadata && typeof source !== \"string\" ? readModelMetadata(source) : {};\n\n let session: ort.InferenceSession;\n try {\n if (typeof source === \"string\") {\n session = await ortRuntime.InferenceSession.create(source, sessionOptions);\n } else if (source instanceof Uint8Array) {\n session = await ortRuntime.InferenceSession.create(source, sessionOptions);\n } else {\n session = await ortRuntime.InferenceSession.create(\n source as ArrayBuffer,\n sessionOptions,\n );\n }\n } catch (err) {\n throw new ModelLoadError(`Failed to load ONNX model: ${(err as Error).message}`, {\n cause: err,\n });\n }\n\n return new OrtSession(session, providers, metadata);\n }\n\n /** Names of the model's inputs, in declaration order. */\n get inputNames(): readonly string[] {\n return this._session.inputNames;\n }\n\n /** Name of the first (and usually only) input. */\n get inputName(): string {\n const name = this._session.inputNames[0];\n if (name === undefined) {\n throw new InferenceError(\"Model has no inputs.\");\n }\n return name;\n }\n\n /** Names of the model's outputs, in declaration order. */\n get outputNames(): readonly string[] {\n return this._session.outputNames;\n }\n\n /**\n * Shapes the graph declares for its inputs, in declaration order.\n *\n * Dynamic (symbolic) axes appear as `null`. Empty shapes mean the runtime\n * reported no metadata — either a non-tensor input, or an `onnxruntime-web`\n * older than 1.21, which predates input metadata.\n */\n get inputShapes(): readonly DeclaredShape[] {\n return declaredShapesFrom(\n this._session.inputMetadata as\n readonly ort.InferenceSession.ValueMetadata[] | undefined,\n );\n }\n\n /**\n * Shape the graph declares for its first input, dynamic axes as `null`.\n *\n * Empty when the runtime reports no metadata for it.\n */\n get inputShape(): DeclaredShape {\n return this.inputShapes[0] ?? [];\n }\n\n /**\n * Shapes the graph declares for its outputs, in declaration order.\n *\n * Dynamic (symbolic) axes appear as `null`. Reading them is how a task can\n * tell how many classes a head emits without being told.\n */\n get outputShapes(): readonly DeclaredShape[] {\n return declaredShapesFrom(\n this._session.outputMetadata as\n readonly ort.InferenceSession.ValueMetadata[] | undefined,\n );\n }\n\n /**\n * Shape the graph declares for its first output, dynamic axes as `null`.\n *\n * Empty when the runtime reports no metadata for it.\n */\n get outputShape(): DeclaredShape {\n return this.outputShapes[0] ?? [];\n }\n\n /**\n * The model's custom metadata map — `names`, `task`, `imgsz`, ... for an\n * Ultralytics export.\n *\n * Read from the model's bytes at load time, since the runtime does not expose\n * it. Empty when the session was created with `readMetadata: false`, from a\n * URL that could not be fetched here, or from a model carrying no metadata.\n */\n get metadata(): Readonly<Record<string, string>> {\n return this._metadata;\n }\n\n /**\n * Release the native session and free its memory.\n *\n * Call it when a session is discarded while the page lives on — rebuilding a\n * task at a different input size, swapping in a newer model. A failure from\n * the runtime is ignored: a session being torn down has nothing left to fail\n * at, and the caller is already moving on.\n */\n async release(): Promise<void> {\n await this._session.release().catch(() => undefined);\n }\n\n /** The underlying `onnxruntime-web` session, for advanced use cases. */\n get raw(): ort.InferenceSession {\n return this._session;\n }\n\n /**\n * Run inference and return all outputs.\n *\n * @param feeds Map of input name to `ort.Tensor`. Keys must match {@link inputNames}.\n * @throws {@link InferenceError} if ORT raises any error during execution.\n */\n async run(feeds: Record<string, ort.Tensor>): Promise<Record<string, ort.Tensor>> {\n try {\n const result = await this._session.run(feeds);\n return result as Record<string, ort.Tensor>;\n } catch (err) {\n throw new InferenceError(`Inference failed: ${(err as Error).message}`, { cause: err });\n }\n }\n}\n"],"mappings":"0NA0BA,eAAe,EAAW,EAA2C,CACjE,GAAI,CACA,IAAM,EAAW,MAAM,MAAM,CAAG,EAKhC,OAJK,EAAS,GAIP,IAAI,WAAW,MAAM,EAAS,YAAY,CAAC,GAH9C,EAAwB,EAAK,QAAQ,EAAS,OAAO,GAAG,EAAS,YAAY,EACtE,EAGf,OAAS,EAAK,CAEV,OADA,EAAwB,EAAM,EAAc,OAAO,EAC5C,CACX,CACJ,CAcA,SAAS,EAAwB,EAAa,EAAsB,CAChE,QAAQ,KACJ,yCAAyC,EAAI,yBAAyB,EAAO,kMAIjF,CACJ,CAkCA,IAAa,EAAb,MAAa,CAAW,CAEC,SACD,UACC,UAHrB,YACI,EACA,EACA,EACF,CAHmB,KAAA,SAAA,EACD,KAAA,UAAA,EACC,KAAA,UAAA,CAClB,CAoBH,aAAa,OAAO,EAAoB,EAA6B,CAAC,EAAwB,CAC1F,IAAM,EAAY,EAAA,iBAAiB,EAAQ,SAAS,EAC9C,EAAsD,CACxD,GAAI,EAAQ,gBAAkB,CAAC,EAC/B,mBACI,CACR,EACM,EAAgB,EAAQ,eAAiB,GACzC,EAAS,OAAO,GAAU,UAAY,EAAgB,MAAM,EAAW,CAAK,EAAI,EAChF,EACF,GAAiB,OAAO,GAAW,SAAW,EAAA,kBAAkB,CAAM,EAAI,CAAC,EAE3E,EACJ,GAAI,CACA,AAKI,GALA,OAAO,GAAW,UAEX,aAAkB,WADf,MAAM,EAAW,iBAAiB,OAAO,EAAQ,CAAc,EASjF,OAAS,EAAK,CACV,MAAM,IAAI,EAAA,eAAe,8BAA+B,EAAc,UAAW,CAC7E,MAAO,CACX,CAAC,CACL,CAEA,OAAO,IAAI,EAAW,EAAS,EAAW,CAAQ,CACtD,CAGA,IAAI,YAAgC,CAChC,OAAO,KAAK,SAAS,UACzB,CAGA,IAAI,WAAoB,CACpB,IAAM,EAAO,KAAK,SAAS,WAAW,GACtC,GAAI,IAAS,IAAA,GACT,MAAM,IAAI,EAAA,eAAe,sBAAsB,EAEnD,OAAO,CACX,CAGA,IAAI,aAAiC,CACjC,OAAO,KAAK,SAAS,WACzB,CASA,IAAI,aAAwC,CACxC,OAAO,EAAA,mBACH,KAAK,SAAS,aAElB,CACJ,CAOA,IAAI,YAA4B,CAC5B,OAAO,KAAK,YAAY,IAAM,CAAC,CACnC,CAQA,IAAI,cAAyC,CACzC,OAAO,EAAA,mBACH,KAAK,SAAS,cAElB,CACJ,CAOA,IAAI,aAA6B,CAC7B,OAAO,KAAK,aAAa,IAAM,CAAC,CACpC,CAUA,IAAI,UAA6C,CAC7C,OAAO,KAAK,SAChB,CAUA,MAAM,SAAyB,CAC3B,MAAM,KAAK,SAAS,QAAQ,CAAC,CAAC,UAAY,IAAA,EAAS,CACvD,CAGA,IAAI,KAA4B,CAC5B,OAAO,KAAK,QAChB,CAQA,MAAM,IAAI,EAAwE,CAC9E,GAAI,CAEA,OAAO,MADc,KAAK,SAAS,IAAI,CAAK,CAEhD,OAAS,EAAK,CACV,MAAM,IAAI,EAAA,eAAe,qBAAsB,EAAc,UAAW,CAAE,MAAO,CAAI,CAAC,CAC1F,CACJ,CACJ"}
1
+ {"version":3,"file":"session.cjs","names":[],"sources":["../../../src/vision/core/session.ts"],"sourcesContent":["/** @generated Vendored from @mauriciobenjamin700/ort-vision-sdk-web. Do not hand-edit — regenerate with `npm run vendor:vision`. */\n/**\n * Thin wrapper around `onnxruntime-web` `InferenceSession` with typed metadata.\n */\n\nimport type * as ort from \"onnxruntime-web\";\nimport * as ortRuntime from \"onnxruntime-web\";\n\nimport { InferenceError, ModelLoadError } from \"./exceptions\";\nimport { type DeclaredShape, declaredShapesFrom } from \"./graph\";\nimport { readModelMetadata } from \"./metadata\";\nimport { FALLBACK_PROVIDER, detectProviders, resolveProviders } from \"./providers\";\n\n/** Anything `InferenceSession.create` accepts. */\nexport type ModelSource = string | ArrayBufferLike | Uint8Array;\n\n/**\n * Fetch a model URL as bytes so its metadata can be read.\n *\n * Falls back to the URL itself when the fetch fails, letting ORT try its own\n * load path: losing the metadata map is a downgrade, but failing to load a model\n * that ORT could have fetched would be a regression.\n *\n * @param url Where the `.onnx` lives.\n * @returns The model bytes, or the original URL when they could not be fetched.\n */\nasync function fetchModel(url: string): Promise<Uint8Array | string> {\n try {\n const response = await fetch(url);\n if (!response.ok) {\n warnMetadataUnavailable(url, `HTTP ${response.status} ${response.statusText}`);\n return url;\n }\n return new Uint8Array(await response.arrayBuffer());\n } catch (err) {\n warnMetadataUnavailable(url, (err as Error).message);\n return url;\n }\n}\n\n/**\n * Warn that a model's metadata could not be read, and say what that costs.\n *\n * The fallback itself is right — losing the metadata beats failing a load that\n * ORT could have completed on its own — but it used to be silent, and the\n * symptom it produces is remote from the cause: class names come back as\n * `class_0`, `class_1`, ... with nothing anywhere explaining why. Whoever hits\n * this needs to be told that passing `labels` is the way out.\n *\n * @param url The model URL that could not be fetched here.\n * @param reason What went wrong, as reported by `fetch`.\n */\nfunction warnMetadataUnavailable(url: string, reason: string): void {\n console.warn(\n `[@ort-vision-sdk/web] Could not fetch ${url} to read its metadata (${reason}). ` +\n \"Letting ONNX Runtime load it instead: the model will work, but its baked-in \" +\n \"class names are unavailable, so labels fall back to class_0, class_1, ... \" +\n \"Pass `labels` explicitly to name them.\",\n );\n}\n\nexport interface OrtSessionOptions {\n /**\n * Execution providers in preference order. `undefined` uses {@link DEFAULT_PROVIDERS}.\n *\n * Naming one explicitly also opts into a `console.warn` when this browser\n * cannot offer it, instead of falling back in silence.\n */\n readonly providers?: readonly string[];\n /** Optional ORT session options forwarded to `InferenceSession.create`. */\n readonly sessionOptions?: ort.InferenceSession.SessionOptions;\n /**\n * Whether to read the model's custom metadata map (`names`, `task`, `imgsz`).\n * Defaults to `true`.\n *\n * The runtime does not expose that map, so it is read from the file itself —\n * which means a URL model is fetched here and handed to ORT as bytes instead\n * of letting ORT fetch it. That is the same single download either way, and\n * it is what lets a task resolve its labels off the model. Set to `false` to\n * keep the URL path untouched and leave {@link OrtSession.metadata} empty.\n *\n * `false` is also the escape hatch when a device cannot afford the bytes: the\n * fetched buffer is dropped before ORT builds the graph (see\n * {@link OrtSession.create}), but ORT's own load path still keeps the model out\n * of reach of anything the SDK holds. A session built this way resolves its\n * input size from the graph as usual — only the class names are lost, so a\n * caller taking this route has to pass `labels` itself.\n */\n readonly readMetadata?: boolean;\n}\n\n/**\n * Warn when a provider named explicitly by the caller is not going to run.\n *\n * Only explicit requests are worth a warning. The default list exists precisely\n * so that falling from `webgpu` to `wasm` is the expected outcome — but a caller\n * who wrote `providers: [\"webgpu\"]` and lands on WASM has a page several times\n * slower than intended and nothing in the console to explain it.\n *\n * @param requested Providers that were asked for.\n * @param effective Providers that survived capability detection.\n */\nfunction warnOnDroppedProviders(requested: readonly string[], effective: readonly string[]): void {\n const dropped = requested.filter((provider) => !effective.includes(provider));\n if (dropped.length === 0) {\n return;\n }\n console.warn(\n `This browser cannot offer the requested execution provider(s) ${JSON.stringify(dropped)}; ` +\n `the session will run on ${JSON.stringify(effective)}. Inference still produces correct ` +\n \"results, on the fallback provider.\",\n );\n}\n\n/**\n * Wrap an ONNX Runtime Web `InferenceSession` with convenient metadata access.\n *\n * The wrapper exposes input/output names and the shapes the graph declares,\n * manages execution-provider selection, provides a typed {@link OrtSession.run}\n * method, and releases the native session through {@link OrtSession.release}.\n */\nexport class OrtSession {\n private constructor(\n private readonly _session: ort.InferenceSession,\n /**\n * Execution providers this session is expected to run on.\n *\n * The requested list narrowed to what this browser can actually offer — a\n * `webgpu` entry survives only where an adapter exists. Best-effort: ORT-Web\n * exposes no way to ask which provider a session ended up on, so an entry\n * here means \"not ruled out\", not \"confirmed\". See\n * {@link requestedProviders} for what was asked for.\n *\n * When nothing survives — a caller asking for `webgpu` alone on a device\n * without it — this falls back to {@link FALLBACK_PROVIDER}, which ORT-Web\n * can always run. Handing ORT the unsatisfiable list instead makes\n * `InferenceSession.create` reject with \"no available backend found\", so the\n * page gets no inference at all rather than the slow-but-working fallback\n * the `console.warn` describes. Measured in a real Chromium, where\n * `navigator.gpu` exists but yields no adapter.\n */\n public readonly providers: readonly string[],\n private readonly _metadata: Readonly<Record<string, string>>,\n /**\n * Execution providers that were asked for, after defaults were applied.\n *\n * Kept separate because ORT-Web falls back silently: a page that asks for\n * `webgpu` on a device without it runs on WASM and is told nothing.\n */\n public readonly requestedProviders: readonly string[],\n ) {}\n\n /**\n * Load an ONNX model into an ORT inference session.\n *\n * The metadata map is read **before** the session is built, and that order is\n * load-bearing on memory-constrained devices. ORT copies the model into its\n * WASM heap and then allocates the graph and the weights on top of that copy;\n * a `readModelMetadata` call placed after `InferenceSession.create` keeps the\n * JavaScript-side buffer reachable across the whole build, so a 5 MB model\n * costs 5 MB of JS heap plus 5 MB of WASM heap plus the weights at the same\n * instant. Reading first makes the buffer collectable as soon as ORT has copied\n * it — on a phone that was the difference between a session and\n * `Can't create a session. failed to allocate a buffer of size N`.\n *\n * @param model Either a URL string, or a `Uint8Array`/`ArrayBuffer` containing the model bytes.\n * @param options Provider list, pass-through `SessionOptions`, and whether to\n * read the model's metadata map (see {@link OrtSessionOptions.readMetadata}).\n * @throws {@link ModelLoadError} if the model cannot be loaded.\n */\n static async create(model: ModelSource, options: OrtSessionOptions = {}): Promise<OrtSession> {\n const requested = resolveProviders(options.providers);\n const detected = await detectProviders(requested);\n const providers = detected.length > 0 ? detected : [FALLBACK_PROVIDER];\n if (options.providers !== undefined && options.providers.length > 0) {\n warnOnDroppedProviders(requested, providers);\n }\n const sessionOptions: ort.InferenceSession.SessionOptions = {\n ...(options.sessionOptions ?? {}),\n executionProviders:\n providers as ort.InferenceSession.SessionOptions[\"executionProviders\"],\n };\n const wantsMetadata = options.readMetadata !== false;\n const source = typeof model === \"string\" && wantsMetadata ? await fetchModel(model) : model;\n const metadata =\n wantsMetadata && typeof source !== \"string\" ? readModelMetadata(source) : {};\n\n let session: ort.InferenceSession;\n try {\n if (typeof source === \"string\") {\n session = await ortRuntime.InferenceSession.create(source, sessionOptions);\n } else if (source instanceof Uint8Array) {\n session = await ortRuntime.InferenceSession.create(source, sessionOptions);\n } else {\n session = await ortRuntime.InferenceSession.create(\n source as ArrayBuffer,\n sessionOptions,\n );\n }\n } catch (err) {\n throw new ModelLoadError(`Failed to load ONNX model: ${(err as Error).message}`, {\n cause: err,\n });\n }\n\n return new OrtSession(session, providers, metadata, requested);\n }\n\n /** Names of the model's inputs, in declaration order. */\n get inputNames(): readonly string[] {\n return this._session.inputNames;\n }\n\n /** Name of the first (and usually only) input. */\n get inputName(): string {\n const name = this._session.inputNames[0];\n if (name === undefined) {\n throw new InferenceError(\"Model has no inputs.\");\n }\n return name;\n }\n\n /** Names of the model's outputs, in declaration order. */\n get outputNames(): readonly string[] {\n return this._session.outputNames;\n }\n\n /**\n * Shapes the graph declares for its inputs, in declaration order.\n *\n * Dynamic (symbolic) axes appear as `null`. Empty shapes mean the runtime\n * reported no metadata — either a non-tensor input, or an `onnxruntime-web`\n * older than 1.21, which predates input metadata.\n */\n get inputShapes(): readonly DeclaredShape[] {\n return declaredShapesFrom(\n this._session.inputMetadata as\n readonly ort.InferenceSession.ValueMetadata[] | undefined,\n );\n }\n\n /**\n * Shape the graph declares for its first input, dynamic axes as `null`.\n *\n * Empty when the runtime reports no metadata for it.\n */\n get inputShape(): DeclaredShape {\n return this.inputShapes[0] ?? [];\n }\n\n /**\n * Shapes the graph declares for its outputs, in declaration order.\n *\n * Dynamic (symbolic) axes appear as `null`. Reading them is how a task can\n * tell how many classes a head emits without being told.\n */\n get outputShapes(): readonly DeclaredShape[] {\n return declaredShapesFrom(\n this._session.outputMetadata as\n readonly ort.InferenceSession.ValueMetadata[] | undefined,\n );\n }\n\n /**\n * Shape the graph declares for its first output, dynamic axes as `null`.\n *\n * Empty when the runtime reports no metadata for it.\n */\n get outputShape(): DeclaredShape {\n return this.outputShapes[0] ?? [];\n }\n\n /**\n * The model's custom metadata map — `names`, `task`, `imgsz`, ... for an\n * Ultralytics export.\n *\n * Read from the model's bytes at load time, since the runtime does not expose\n * it. Empty when the session was created with `readMetadata: false`, from a\n * URL that could not be fetched here, or from a model carrying no metadata.\n */\n get metadata(): Readonly<Record<string, string>> {\n return this._metadata;\n }\n\n /**\n * Release the native session and free its memory.\n *\n * Call it when a session is discarded while the page lives on — rebuilding a\n * task at a different input size, swapping in a newer model. A failure from\n * the runtime is ignored: a session being torn down has nothing left to fail\n * at, and the caller is already moving on.\n */\n async release(): Promise<void> {\n await this._session.release().catch(() => undefined);\n }\n\n /** The underlying `onnxruntime-web` session, for advanced use cases. */\n get raw(): ort.InferenceSession {\n return this._session;\n }\n\n /**\n * Run inference and return all outputs.\n *\n * @param feeds Map of input name to `ort.Tensor`. Keys must match {@link inputNames}.\n * @throws {@link InferenceError} if ORT raises any error during execution.\n */\n async run(feeds: Record<string, ort.Tensor>): Promise<Record<string, ort.Tensor>> {\n try {\n const result = await this._session.run(feeds);\n return result as Record<string, ort.Tensor>;\n } catch (err) {\n throw new InferenceError(`Inference failed: ${(err as Error).message}`, { cause: err });\n }\n }\n}\n"],"mappings":"0NA0BA,eAAe,EAAW,EAA2C,CACjE,GAAI,CACA,IAAM,EAAW,MAAM,MAAM,CAAG,EAKhC,OAJK,EAAS,GAIP,IAAI,WAAW,MAAM,EAAS,YAAY,CAAC,GAH9C,EAAwB,EAAK,QAAQ,EAAS,OAAO,GAAG,EAAS,YAAY,EACtE,EAGf,OAAS,EAAK,CAEV,OADA,EAAwB,EAAM,EAAc,OAAO,EAC5C,CACX,CACJ,CAcA,SAAS,EAAwB,EAAa,EAAsB,CAChE,QAAQ,KACJ,yCAAyC,EAAI,yBAAyB,EAAO,kMAIjF,CACJ,CA2CA,SAAS,EAAuB,EAA8B,EAAoC,CAC9F,IAAM,EAAU,EAAU,OAAQ,GAAa,CAAC,EAAU,SAAS,CAAQ,CAAC,EACxE,EAAQ,SAAW,GAGvB,QAAQ,KACJ,iEAAiE,KAAK,UAAU,CAAO,EAAE,4BAC1D,KAAK,UAAU,CAAS,EAAE,sEAE7D,CACJ,CASA,IAAa,EAAb,MAAa,CAAW,CAEC,SAkBD,UACC,UAOD,mBA3BpB,YACI,EAkBA,EACA,EAOA,EACF,CA3BmB,KAAA,SAAA,EAkBD,KAAA,UAAA,EACC,KAAA,UAAA,EAOD,KAAA,mBAAA,CACjB,CAoBH,aAAa,OAAO,EAAoB,EAA6B,CAAC,EAAwB,CAC1F,IAAM,EAAY,EAAA,iBAAiB,EAAQ,SAAS,EAC9C,EAAW,MAAM,EAAA,gBAAgB,CAAS,EAC1C,EAAY,EAAS,OAAS,EAAI,EAAW,CAAC,EAAA,iBAAiB,EACjE,EAAQ,YAAc,IAAA,IAAa,EAAQ,UAAU,OAAS,GAC9D,EAAuB,EAAW,CAAS,EAE/C,IAAM,EAAsD,CACxD,GAAI,EAAQ,gBAAkB,CAAC,EAC/B,mBACI,CACR,EACM,EAAgB,EAAQ,eAAiB,GACzC,EAAS,OAAO,GAAU,UAAY,EAAgB,MAAM,EAAW,CAAK,EAAI,EAChF,EACF,GAAiB,OAAO,GAAW,SAAW,EAAA,kBAAkB,CAAM,EAAI,CAAC,EAE3E,EACJ,GAAI,CACA,AAKI,GALA,OAAO,GAAW,UAEX,aAAkB,WADf,MAAM,EAAW,iBAAiB,OAAO,EAAQ,CAAc,EASjF,OAAS,EAAK,CACV,MAAM,IAAI,EAAA,eAAe,8BAA+B,EAAc,UAAW,CAC7E,MAAO,CACX,CAAC,CACL,CAEA,OAAO,IAAI,EAAW,EAAS,EAAW,EAAU,CAAS,CACjE,CAGA,IAAI,YAAgC,CAChC,OAAO,KAAK,SAAS,UACzB,CAGA,IAAI,WAAoB,CACpB,IAAM,EAAO,KAAK,SAAS,WAAW,GACtC,GAAI,IAAS,IAAA,GACT,MAAM,IAAI,EAAA,eAAe,sBAAsB,EAEnD,OAAO,CACX,CAGA,IAAI,aAAiC,CACjC,OAAO,KAAK,SAAS,WACzB,CASA,IAAI,aAAwC,CACxC,OAAO,EAAA,mBACH,KAAK,SAAS,aAElB,CACJ,CAOA,IAAI,YAA4B,CAC5B,OAAO,KAAK,YAAY,IAAM,CAAC,CACnC,CAQA,IAAI,cAAyC,CACzC,OAAO,EAAA,mBACH,KAAK,SAAS,cAElB,CACJ,CAOA,IAAI,aAA6B,CAC7B,OAAO,KAAK,aAAa,IAAM,CAAC,CACpC,CAUA,IAAI,UAA6C,CAC7C,OAAO,KAAK,SAChB,CAUA,MAAM,SAAyB,CAC3B,MAAM,KAAK,SAAS,QAAQ,CAAC,CAAC,UAAY,IAAA,EAAS,CACvD,CAGA,IAAI,KAA4B,CAC5B,OAAO,KAAK,QAChB,CAQA,MAAM,IAAI,EAAwE,CAC9E,GAAI,CAEA,OAAO,MADc,KAAK,SAAS,IAAI,CAAK,CAEhD,OAAS,EAAK,CACV,MAAM,IAAI,EAAA,eAAe,qBAAsB,EAAc,UAAW,CAAE,MAAO,CAAI,CAAC,CAC1F,CACJ,CACJ"}
@@ -1,38 +1,45 @@
1
1
  import { InferenceError as e, ModelLoadError as t } from "./exceptions.js";
2
2
  import { declaredShapesFrom as n } from "./graph.js";
3
3
  import { readModelMetadata as r } from "./metadata.js";
4
- import { resolveProviders as i } from "./providers.js";
5
- import * as a from "onnxruntime-web";
4
+ import { FALLBACK_PROVIDER as i, detectProviders as a, resolveProviders as o } from "./providers.js";
5
+ import * as s from "onnxruntime-web";
6
6
  //#region src/vision/core/session.ts
7
- async function o(e) {
7
+ async function c(e) {
8
8
  try {
9
9
  let t = await fetch(e);
10
- return t.ok ? new Uint8Array(await t.arrayBuffer()) : (s(e, `HTTP ${t.status} ${t.statusText}`), e);
10
+ return t.ok ? new Uint8Array(await t.arrayBuffer()) : (l(e, `HTTP ${t.status} ${t.statusText}`), e);
11
11
  } catch (t) {
12
- return s(e, t.message), e;
12
+ return l(e, t.message), e;
13
13
  }
14
14
  }
15
- function s(e, t) {
15
+ function l(e, t) {
16
16
  console.warn(`[@ort-vision-sdk/web] Could not fetch ${e} to read its metadata (${t}). Letting ONNX Runtime load it instead: the model will work, but its baked-in class names are unavailable, so labels fall back to class_0, class_1, ... Pass \`labels\` explicitly to name them.`);
17
17
  }
18
- var c = class s {
18
+ function u(e, t) {
19
+ let n = e.filter((e) => !t.includes(e));
20
+ n.length !== 0 && console.warn(`This browser cannot offer the requested execution provider(s) ${JSON.stringify(n)}; the session will run on ${JSON.stringify(t)}. Inference still produces correct results, on the fallback provider.`);
21
+ }
22
+ var d = class l {
19
23
  _session;
20
24
  providers;
21
25
  _metadata;
22
- constructor(e, t, n) {
23
- this._session = e, this.providers = t, this._metadata = n;
26
+ requestedProviders;
27
+ constructor(e, t, n, r) {
28
+ this._session = e, this.providers = t, this._metadata = n, this.requestedProviders = r;
24
29
  }
25
30
  static async create(e, n = {}) {
26
- let c = i(n.providers), l = {
31
+ let d = o(n.providers), f = await a(d), p = f.length > 0 ? f : [i];
32
+ n.providers !== void 0 && n.providers.length > 0 && u(d, p);
33
+ let m = {
27
34
  ...n.sessionOptions ?? {},
28
- executionProviders: c
29
- }, u = n.readMetadata !== !1, d = typeof e == "string" && u ? await o(e) : e, f = u && typeof d != "string" ? r(d) : {}, p;
35
+ executionProviders: p
36
+ }, h = n.readMetadata !== !1, g = typeof e == "string" && h ? await c(e) : e, _ = h && typeof g != "string" ? r(g) : {}, v;
30
37
  try {
31
- p = (typeof d == "string" || d instanceof Uint8Array, await a.InferenceSession.create(d, l));
38
+ v = (typeof g == "string" || g instanceof Uint8Array, await s.InferenceSession.create(g, m));
32
39
  } catch (e) {
33
40
  throw new t(`Failed to load ONNX model: ${e.message}`, { cause: e });
34
41
  }
35
- return new s(p, c, f);
42
+ return new l(v, p, _, d);
36
43
  }
37
44
  get inputNames() {
38
45
  return this._session.inputNames;
@@ -75,6 +82,6 @@ var c = class s {
75
82
  }
76
83
  };
77
84
  //#endregion
78
- export { c as OrtSession };
85
+ export { d as OrtSession };
79
86
 
80
87
  //# sourceMappingURL=session.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"session.js","names":[],"sources":["../../../src/vision/core/session.ts"],"sourcesContent":["/** @generated Vendored from @mauriciobenjamin700/ort-vision-sdk-web. Do not hand-edit — regenerate with `npm run vendor:vision`. */\n/**\n * Thin wrapper around `onnxruntime-web` `InferenceSession` with typed metadata.\n */\n\nimport type * as ort from \"onnxruntime-web\";\nimport * as ortRuntime from \"onnxruntime-web\";\n\nimport { InferenceError, ModelLoadError } from \"./exceptions\";\nimport { type DeclaredShape, declaredShapesFrom } from \"./graph\";\nimport { readModelMetadata } from \"./metadata\";\nimport { resolveProviders } from \"./providers\";\n\n/** Anything `InferenceSession.create` accepts. */\nexport type ModelSource = string | ArrayBufferLike | Uint8Array;\n\n/**\n * Fetch a model URL as bytes so its metadata can be read.\n *\n * Falls back to the URL itself when the fetch fails, letting ORT try its own\n * load path: losing the metadata map is a downgrade, but failing to load a model\n * that ORT could have fetched would be a regression.\n *\n * @param url Where the `.onnx` lives.\n * @returns The model bytes, or the original URL when they could not be fetched.\n */\nasync function fetchModel(url: string): Promise<Uint8Array | string> {\n try {\n const response = await fetch(url);\n if (!response.ok) {\n warnMetadataUnavailable(url, `HTTP ${response.status} ${response.statusText}`);\n return url;\n }\n return new Uint8Array(await response.arrayBuffer());\n } catch (err) {\n warnMetadataUnavailable(url, (err as Error).message);\n return url;\n }\n}\n\n/**\n * Warn that a model's metadata could not be read, and say what that costs.\n *\n * The fallback itself is right — losing the metadata beats failing a load that\n * ORT could have completed on its own — but it used to be silent, and the\n * symptom it produces is remote from the cause: class names come back as\n * `class_0`, `class_1`, ... with nothing anywhere explaining why. Whoever hits\n * this needs to be told that passing `labels` is the way out.\n *\n * @param url The model URL that could not be fetched here.\n * @param reason What went wrong, as reported by `fetch`.\n */\nfunction warnMetadataUnavailable(url: string, reason: string): void {\n console.warn(\n `[@ort-vision-sdk/web] Could not fetch ${url} to read its metadata (${reason}). ` +\n \"Letting ONNX Runtime load it instead: the model will work, but its baked-in \" +\n \"class names are unavailable, so labels fall back to class_0, class_1, ... \" +\n \"Pass `labels` explicitly to name them.\",\n );\n}\n\nexport interface OrtSessionOptions {\n /** Execution providers in preference order. `undefined` uses {@link DEFAULT_PROVIDERS}. */\n readonly providers?: readonly string[];\n /** Optional ORT session options forwarded to `InferenceSession.create`. */\n readonly sessionOptions?: ort.InferenceSession.SessionOptions;\n /**\n * Whether to read the model's custom metadata map (`names`, `task`, `imgsz`).\n * Defaults to `true`.\n *\n * The runtime does not expose that map, so it is read from the file itself —\n * which means a URL model is fetched here and handed to ORT as bytes instead\n * of letting ORT fetch it. That is the same single download either way, and\n * it is what lets a task resolve its labels off the model. Set to `false` to\n * keep the URL path untouched and leave {@link OrtSession.metadata} empty.\n *\n * `false` is also the escape hatch when a device cannot afford the bytes: the\n * fetched buffer is dropped before ORT builds the graph (see\n * {@link OrtSession.create}), but ORT's own load path still keeps the model out\n * of reach of anything the SDK holds. A session built this way resolves its\n * input size from the graph as usual — only the class names are lost, so a\n * caller taking this route has to pass `labels` itself.\n */\n readonly readMetadata?: boolean;\n}\n\n/**\n * Wrap an ONNX Runtime Web `InferenceSession` with convenient metadata access.\n *\n * The wrapper exposes input/output names and the shapes the graph declares,\n * manages execution-provider selection, provides a typed {@link OrtSession.run}\n * method, and releases the native session through {@link OrtSession.release}.\n */\nexport class OrtSession {\n private constructor(\n private readonly _session: ort.InferenceSession,\n public readonly providers: readonly string[],\n private readonly _metadata: Readonly<Record<string, string>>,\n ) {}\n\n /**\n * Load an ONNX model into an ORT inference session.\n *\n * The metadata map is read **before** the session is built, and that order is\n * load-bearing on memory-constrained devices. ORT copies the model into its\n * WASM heap and then allocates the graph and the weights on top of that copy;\n * a `readModelMetadata` call placed after `InferenceSession.create` keeps the\n * JavaScript-side buffer reachable across the whole build, so a 5 MB model\n * costs 5 MB of JS heap plus 5 MB of WASM heap plus the weights at the same\n * instant. Reading first makes the buffer collectable as soon as ORT has copied\n * it — on a phone that was the difference between a session and\n * `Can't create a session. failed to allocate a buffer of size N`.\n *\n * @param model Either a URL string, or a `Uint8Array`/`ArrayBuffer` containing the model bytes.\n * @param options Provider list, pass-through `SessionOptions`, and whether to\n * read the model's metadata map (see {@link OrtSessionOptions.readMetadata}).\n * @throws {@link ModelLoadError} if the model cannot be loaded.\n */\n static async create(model: ModelSource, options: OrtSessionOptions = {}): Promise<OrtSession> {\n const providers = resolveProviders(options.providers);\n const sessionOptions: ort.InferenceSession.SessionOptions = {\n ...(options.sessionOptions ?? {}),\n executionProviders:\n providers as ort.InferenceSession.SessionOptions[\"executionProviders\"],\n };\n const wantsMetadata = options.readMetadata !== false;\n const source = typeof model === \"string\" && wantsMetadata ? await fetchModel(model) : model;\n const metadata =\n wantsMetadata && typeof source !== \"string\" ? readModelMetadata(source) : {};\n\n let session: ort.InferenceSession;\n try {\n if (typeof source === \"string\") {\n session = await ortRuntime.InferenceSession.create(source, sessionOptions);\n } else if (source instanceof Uint8Array) {\n session = await ortRuntime.InferenceSession.create(source, sessionOptions);\n } else {\n session = await ortRuntime.InferenceSession.create(\n source as ArrayBuffer,\n sessionOptions,\n );\n }\n } catch (err) {\n throw new ModelLoadError(`Failed to load ONNX model: ${(err as Error).message}`, {\n cause: err,\n });\n }\n\n return new OrtSession(session, providers, metadata);\n }\n\n /** Names of the model's inputs, in declaration order. */\n get inputNames(): readonly string[] {\n return this._session.inputNames;\n }\n\n /** Name of the first (and usually only) input. */\n get inputName(): string {\n const name = this._session.inputNames[0];\n if (name === undefined) {\n throw new InferenceError(\"Model has no inputs.\");\n }\n return name;\n }\n\n /** Names of the model's outputs, in declaration order. */\n get outputNames(): readonly string[] {\n return this._session.outputNames;\n }\n\n /**\n * Shapes the graph declares for its inputs, in declaration order.\n *\n * Dynamic (symbolic) axes appear as `null`. Empty shapes mean the runtime\n * reported no metadata — either a non-tensor input, or an `onnxruntime-web`\n * older than 1.21, which predates input metadata.\n */\n get inputShapes(): readonly DeclaredShape[] {\n return declaredShapesFrom(\n this._session.inputMetadata as\n readonly ort.InferenceSession.ValueMetadata[] | undefined,\n );\n }\n\n /**\n * Shape the graph declares for its first input, dynamic axes as `null`.\n *\n * Empty when the runtime reports no metadata for it.\n */\n get inputShape(): DeclaredShape {\n return this.inputShapes[0] ?? [];\n }\n\n /**\n * Shapes the graph declares for its outputs, in declaration order.\n *\n * Dynamic (symbolic) axes appear as `null`. Reading them is how a task can\n * tell how many classes a head emits without being told.\n */\n get outputShapes(): readonly DeclaredShape[] {\n return declaredShapesFrom(\n this._session.outputMetadata as\n readonly ort.InferenceSession.ValueMetadata[] | undefined,\n );\n }\n\n /**\n * Shape the graph declares for its first output, dynamic axes as `null`.\n *\n * Empty when the runtime reports no metadata for it.\n */\n get outputShape(): DeclaredShape {\n return this.outputShapes[0] ?? [];\n }\n\n /**\n * The model's custom metadata map — `names`, `task`, `imgsz`, ... for an\n * Ultralytics export.\n *\n * Read from the model's bytes at load time, since the runtime does not expose\n * it. Empty when the session was created with `readMetadata: false`, from a\n * URL that could not be fetched here, or from a model carrying no metadata.\n */\n get metadata(): Readonly<Record<string, string>> {\n return this._metadata;\n }\n\n /**\n * Release the native session and free its memory.\n *\n * Call it when a session is discarded while the page lives on — rebuilding a\n * task at a different input size, swapping in a newer model. A failure from\n * the runtime is ignored: a session being torn down has nothing left to fail\n * at, and the caller is already moving on.\n */\n async release(): Promise<void> {\n await this._session.release().catch(() => undefined);\n }\n\n /** The underlying `onnxruntime-web` session, for advanced use cases. */\n get raw(): ort.InferenceSession {\n return this._session;\n }\n\n /**\n * Run inference and return all outputs.\n *\n * @param feeds Map of input name to `ort.Tensor`. Keys must match {@link inputNames}.\n * @throws {@link InferenceError} if ORT raises any error during execution.\n */\n async run(feeds: Record<string, ort.Tensor>): Promise<Record<string, ort.Tensor>> {\n try {\n const result = await this._session.run(feeds);\n return result as Record<string, ort.Tensor>;\n } catch (err) {\n throw new InferenceError(`Inference failed: ${(err as Error).message}`, { cause: err });\n }\n }\n}\n"],"mappings":";;;;;;AA0BA,eAAe,EAAW,GAA2C;CACjE,IAAI;EACA,IAAM,IAAW,MAAM,MAAM,CAAG;EAKhC,OAJK,EAAS,KAIP,IAAI,WAAW,MAAM,EAAS,YAAY,CAAC,KAH9C,EAAwB,GAAK,QAAQ,EAAS,OAAO,GAAG,EAAS,YAAY,GACtE;CAGf,SAAS,GAAK;EAEV,OADA,EAAwB,GAAM,EAAc,OAAO,GAC5C;CACX;AACJ;AAcA,SAAS,EAAwB,GAAa,GAAsB;CAChE,QAAQ,KACJ,yCAAyC,EAAI,yBAAyB,EAAO,kMAIjF;AACJ;AAkCA,IAAa,IAAb,MAAa,EAAW;CAEC;CACD;CACC;CAHrB,YACI,GACA,GACA,GACF;EADmB,AAFA,KAAA,WAAA,GACD,KAAA,YAAA,GACC,KAAA,YAAA;CAClB;CAoBH,aAAa,OAAO,GAAoB,IAA6B,CAAC,GAAwB;EAC1F,IAAM,IAAY,EAAiB,EAAQ,SAAS,GAC9C,IAAsD;GACxD,GAAI,EAAQ,kBAAkB,CAAC;GAC/B,oBACI;EACR,GACM,IAAgB,EAAQ,iBAAiB,IACzC,IAAS,OAAO,KAAU,YAAY,IAAgB,MAAM,EAAW,CAAK,IAAI,GAChF,IACF,KAAiB,OAAO,KAAW,WAAW,EAAkB,CAAM,IAAI,CAAC,GAE3E;EACJ,IAAI;GACA,AAKI,KALA,OAAO,KAAW,YAEX,aAAkB,YADf,MAAM,EAAW,iBAAiB,OAAO,GAAQ,CAAc;EASjF,SAAS,GAAK;GACV,MAAM,IAAI,EAAe,8BAA+B,EAAc,WAAW,EAC7E,OAAO,EACX,CAAC;EACL;EAEA,OAAO,IAAI,EAAW,GAAS,GAAW,CAAQ;CACtD;CAGA,IAAI,aAAgC;EAChC,OAAO,KAAK,SAAS;CACzB;CAGA,IAAI,YAAoB;EACpB,IAAM,IAAO,KAAK,SAAS,WAAW;EACtC,IAAI,MAAS,KAAA,GACT,MAAM,IAAI,EAAe,sBAAsB;EAEnD,OAAO;CACX;CAGA,IAAI,cAAiC;EACjC,OAAO,KAAK,SAAS;CACzB;CASA,IAAI,cAAwC;EACxC,OAAO,EACH,KAAK,SAAS,aAElB;CACJ;CAOA,IAAI,aAA4B;EAC5B,OAAO,KAAK,YAAY,MAAM,CAAC;CACnC;CAQA,IAAI,eAAyC;EACzC,OAAO,EACH,KAAK,SAAS,cAElB;CACJ;CAOA,IAAI,cAA6B;EAC7B,OAAO,KAAK,aAAa,MAAM,CAAC;CACpC;CAUA,IAAI,WAA6C;EAC7C,OAAO,KAAK;CAChB;CAUA,MAAM,UAAyB;EAC3B,MAAM,KAAK,SAAS,QAAQ,CAAC,CAAC,YAAY,KAAA,CAAS;CACvD;CAGA,IAAI,MAA4B;EAC5B,OAAO,KAAK;CAChB;CAQA,MAAM,IAAI,GAAwE;EAC9E,IAAI;GAEA,OAAO,MADc,KAAK,SAAS,IAAI,CAAK;EAEhD,SAAS,GAAK;GACV,MAAM,IAAI,EAAe,qBAAsB,EAAc,WAAW,EAAE,OAAO,EAAI,CAAC;EAC1F;CACJ;AACJ"}
1
+ {"version":3,"file":"session.js","names":[],"sources":["../../../src/vision/core/session.ts"],"sourcesContent":["/** @generated Vendored from @mauriciobenjamin700/ort-vision-sdk-web. Do not hand-edit — regenerate with `npm run vendor:vision`. */\n/**\n * Thin wrapper around `onnxruntime-web` `InferenceSession` with typed metadata.\n */\n\nimport type * as ort from \"onnxruntime-web\";\nimport * as ortRuntime from \"onnxruntime-web\";\n\nimport { InferenceError, ModelLoadError } from \"./exceptions\";\nimport { type DeclaredShape, declaredShapesFrom } from \"./graph\";\nimport { readModelMetadata } from \"./metadata\";\nimport { FALLBACK_PROVIDER, detectProviders, resolveProviders } from \"./providers\";\n\n/** Anything `InferenceSession.create` accepts. */\nexport type ModelSource = string | ArrayBufferLike | Uint8Array;\n\n/**\n * Fetch a model URL as bytes so its metadata can be read.\n *\n * Falls back to the URL itself when the fetch fails, letting ORT try its own\n * load path: losing the metadata map is a downgrade, but failing to load a model\n * that ORT could have fetched would be a regression.\n *\n * @param url Where the `.onnx` lives.\n * @returns The model bytes, or the original URL when they could not be fetched.\n */\nasync function fetchModel(url: string): Promise<Uint8Array | string> {\n try {\n const response = await fetch(url);\n if (!response.ok) {\n warnMetadataUnavailable(url, `HTTP ${response.status} ${response.statusText}`);\n return url;\n }\n return new Uint8Array(await response.arrayBuffer());\n } catch (err) {\n warnMetadataUnavailable(url, (err as Error).message);\n return url;\n }\n}\n\n/**\n * Warn that a model's metadata could not be read, and say what that costs.\n *\n * The fallback itself is right — losing the metadata beats failing a load that\n * ORT could have completed on its own — but it used to be silent, and the\n * symptom it produces is remote from the cause: class names come back as\n * `class_0`, `class_1`, ... with nothing anywhere explaining why. Whoever hits\n * this needs to be told that passing `labels` is the way out.\n *\n * @param url The model URL that could not be fetched here.\n * @param reason What went wrong, as reported by `fetch`.\n */\nfunction warnMetadataUnavailable(url: string, reason: string): void {\n console.warn(\n `[@ort-vision-sdk/web] Could not fetch ${url} to read its metadata (${reason}). ` +\n \"Letting ONNX Runtime load it instead: the model will work, but its baked-in \" +\n \"class names are unavailable, so labels fall back to class_0, class_1, ... \" +\n \"Pass `labels` explicitly to name them.\",\n );\n}\n\nexport interface OrtSessionOptions {\n /**\n * Execution providers in preference order. `undefined` uses {@link DEFAULT_PROVIDERS}.\n *\n * Naming one explicitly also opts into a `console.warn` when this browser\n * cannot offer it, instead of falling back in silence.\n */\n readonly providers?: readonly string[];\n /** Optional ORT session options forwarded to `InferenceSession.create`. */\n readonly sessionOptions?: ort.InferenceSession.SessionOptions;\n /**\n * Whether to read the model's custom metadata map (`names`, `task`, `imgsz`).\n * Defaults to `true`.\n *\n * The runtime does not expose that map, so it is read from the file itself —\n * which means a URL model is fetched here and handed to ORT as bytes instead\n * of letting ORT fetch it. That is the same single download either way, and\n * it is what lets a task resolve its labels off the model. Set to `false` to\n * keep the URL path untouched and leave {@link OrtSession.metadata} empty.\n *\n * `false` is also the escape hatch when a device cannot afford the bytes: the\n * fetched buffer is dropped before ORT builds the graph (see\n * {@link OrtSession.create}), but ORT's own load path still keeps the model out\n * of reach of anything the SDK holds. A session built this way resolves its\n * input size from the graph as usual — only the class names are lost, so a\n * caller taking this route has to pass `labels` itself.\n */\n readonly readMetadata?: boolean;\n}\n\n/**\n * Warn when a provider named explicitly by the caller is not going to run.\n *\n * Only explicit requests are worth a warning. The default list exists precisely\n * so that falling from `webgpu` to `wasm` is the expected outcome — but a caller\n * who wrote `providers: [\"webgpu\"]` and lands on WASM has a page several times\n * slower than intended and nothing in the console to explain it.\n *\n * @param requested Providers that were asked for.\n * @param effective Providers that survived capability detection.\n */\nfunction warnOnDroppedProviders(requested: readonly string[], effective: readonly string[]): void {\n const dropped = requested.filter((provider) => !effective.includes(provider));\n if (dropped.length === 0) {\n return;\n }\n console.warn(\n `This browser cannot offer the requested execution provider(s) ${JSON.stringify(dropped)}; ` +\n `the session will run on ${JSON.stringify(effective)}. Inference still produces correct ` +\n \"results, on the fallback provider.\",\n );\n}\n\n/**\n * Wrap an ONNX Runtime Web `InferenceSession` with convenient metadata access.\n *\n * The wrapper exposes input/output names and the shapes the graph declares,\n * manages execution-provider selection, provides a typed {@link OrtSession.run}\n * method, and releases the native session through {@link OrtSession.release}.\n */\nexport class OrtSession {\n private constructor(\n private readonly _session: ort.InferenceSession,\n /**\n * Execution providers this session is expected to run on.\n *\n * The requested list narrowed to what this browser can actually offer — a\n * `webgpu` entry survives only where an adapter exists. Best-effort: ORT-Web\n * exposes no way to ask which provider a session ended up on, so an entry\n * here means \"not ruled out\", not \"confirmed\". See\n * {@link requestedProviders} for what was asked for.\n *\n * When nothing survives — a caller asking for `webgpu` alone on a device\n * without it — this falls back to {@link FALLBACK_PROVIDER}, which ORT-Web\n * can always run. Handing ORT the unsatisfiable list instead makes\n * `InferenceSession.create` reject with \"no available backend found\", so the\n * page gets no inference at all rather than the slow-but-working fallback\n * the `console.warn` describes. Measured in a real Chromium, where\n * `navigator.gpu` exists but yields no adapter.\n */\n public readonly providers: readonly string[],\n private readonly _metadata: Readonly<Record<string, string>>,\n /**\n * Execution providers that were asked for, after defaults were applied.\n *\n * Kept separate because ORT-Web falls back silently: a page that asks for\n * `webgpu` on a device without it runs on WASM and is told nothing.\n */\n public readonly requestedProviders: readonly string[],\n ) {}\n\n /**\n * Load an ONNX model into an ORT inference session.\n *\n * The metadata map is read **before** the session is built, and that order is\n * load-bearing on memory-constrained devices. ORT copies the model into its\n * WASM heap and then allocates the graph and the weights on top of that copy;\n * a `readModelMetadata` call placed after `InferenceSession.create` keeps the\n * JavaScript-side buffer reachable across the whole build, so a 5 MB model\n * costs 5 MB of JS heap plus 5 MB of WASM heap plus the weights at the same\n * instant. Reading first makes the buffer collectable as soon as ORT has copied\n * it — on a phone that was the difference between a session and\n * `Can't create a session. failed to allocate a buffer of size N`.\n *\n * @param model Either a URL string, or a `Uint8Array`/`ArrayBuffer` containing the model bytes.\n * @param options Provider list, pass-through `SessionOptions`, and whether to\n * read the model's metadata map (see {@link OrtSessionOptions.readMetadata}).\n * @throws {@link ModelLoadError} if the model cannot be loaded.\n */\n static async create(model: ModelSource, options: OrtSessionOptions = {}): Promise<OrtSession> {\n const requested = resolveProviders(options.providers);\n const detected = await detectProviders(requested);\n const providers = detected.length > 0 ? detected : [FALLBACK_PROVIDER];\n if (options.providers !== undefined && options.providers.length > 0) {\n warnOnDroppedProviders(requested, providers);\n }\n const sessionOptions: ort.InferenceSession.SessionOptions = {\n ...(options.sessionOptions ?? {}),\n executionProviders:\n providers as ort.InferenceSession.SessionOptions[\"executionProviders\"],\n };\n const wantsMetadata = options.readMetadata !== false;\n const source = typeof model === \"string\" && wantsMetadata ? await fetchModel(model) : model;\n const metadata =\n wantsMetadata && typeof source !== \"string\" ? readModelMetadata(source) : {};\n\n let session: ort.InferenceSession;\n try {\n if (typeof source === \"string\") {\n session = await ortRuntime.InferenceSession.create(source, sessionOptions);\n } else if (source instanceof Uint8Array) {\n session = await ortRuntime.InferenceSession.create(source, sessionOptions);\n } else {\n session = await ortRuntime.InferenceSession.create(\n source as ArrayBuffer,\n sessionOptions,\n );\n }\n } catch (err) {\n throw new ModelLoadError(`Failed to load ONNX model: ${(err as Error).message}`, {\n cause: err,\n });\n }\n\n return new OrtSession(session, providers, metadata, requested);\n }\n\n /** Names of the model's inputs, in declaration order. */\n get inputNames(): readonly string[] {\n return this._session.inputNames;\n }\n\n /** Name of the first (and usually only) input. */\n get inputName(): string {\n const name = this._session.inputNames[0];\n if (name === undefined) {\n throw new InferenceError(\"Model has no inputs.\");\n }\n return name;\n }\n\n /** Names of the model's outputs, in declaration order. */\n get outputNames(): readonly string[] {\n return this._session.outputNames;\n }\n\n /**\n * Shapes the graph declares for its inputs, in declaration order.\n *\n * Dynamic (symbolic) axes appear as `null`. Empty shapes mean the runtime\n * reported no metadata — either a non-tensor input, or an `onnxruntime-web`\n * older than 1.21, which predates input metadata.\n */\n get inputShapes(): readonly DeclaredShape[] {\n return declaredShapesFrom(\n this._session.inputMetadata as\n readonly ort.InferenceSession.ValueMetadata[] | undefined,\n );\n }\n\n /**\n * Shape the graph declares for its first input, dynamic axes as `null`.\n *\n * Empty when the runtime reports no metadata for it.\n */\n get inputShape(): DeclaredShape {\n return this.inputShapes[0] ?? [];\n }\n\n /**\n * Shapes the graph declares for its outputs, in declaration order.\n *\n * Dynamic (symbolic) axes appear as `null`. Reading them is how a task can\n * tell how many classes a head emits without being told.\n */\n get outputShapes(): readonly DeclaredShape[] {\n return declaredShapesFrom(\n this._session.outputMetadata as\n readonly ort.InferenceSession.ValueMetadata[] | undefined,\n );\n }\n\n /**\n * Shape the graph declares for its first output, dynamic axes as `null`.\n *\n * Empty when the runtime reports no metadata for it.\n */\n get outputShape(): DeclaredShape {\n return this.outputShapes[0] ?? [];\n }\n\n /**\n * The model's custom metadata map — `names`, `task`, `imgsz`, ... for an\n * Ultralytics export.\n *\n * Read from the model's bytes at load time, since the runtime does not expose\n * it. Empty when the session was created with `readMetadata: false`, from a\n * URL that could not be fetched here, or from a model carrying no metadata.\n */\n get metadata(): Readonly<Record<string, string>> {\n return this._metadata;\n }\n\n /**\n * Release the native session and free its memory.\n *\n * Call it when a session is discarded while the page lives on — rebuilding a\n * task at a different input size, swapping in a newer model. A failure from\n * the runtime is ignored: a session being torn down has nothing left to fail\n * at, and the caller is already moving on.\n */\n async release(): Promise<void> {\n await this._session.release().catch(() => undefined);\n }\n\n /** The underlying `onnxruntime-web` session, for advanced use cases. */\n get raw(): ort.InferenceSession {\n return this._session;\n }\n\n /**\n * Run inference and return all outputs.\n *\n * @param feeds Map of input name to `ort.Tensor`. Keys must match {@link inputNames}.\n * @throws {@link InferenceError} if ORT raises any error during execution.\n */\n async run(feeds: Record<string, ort.Tensor>): Promise<Record<string, ort.Tensor>> {\n try {\n const result = await this._session.run(feeds);\n return result as Record<string, ort.Tensor>;\n } catch (err) {\n throw new InferenceError(`Inference failed: ${(err as Error).message}`, { cause: err });\n }\n }\n}\n"],"mappings":";;;;;;AA0BA,eAAe,EAAW,GAA2C;CACjE,IAAI;EACA,IAAM,IAAW,MAAM,MAAM,CAAG;EAKhC,OAJK,EAAS,KAIP,IAAI,WAAW,MAAM,EAAS,YAAY,CAAC,KAH9C,EAAwB,GAAK,QAAQ,EAAS,OAAO,GAAG,EAAS,YAAY,GACtE;CAGf,SAAS,GAAK;EAEV,OADA,EAAwB,GAAM,EAAc,OAAO,GAC5C;CACX;AACJ;AAcA,SAAS,EAAwB,GAAa,GAAsB;CAChE,QAAQ,KACJ,yCAAyC,EAAI,yBAAyB,EAAO,kMAIjF;AACJ;AA2CA,SAAS,EAAuB,GAA8B,GAAoC;CAC9F,IAAM,IAAU,EAAU,QAAQ,MAAa,CAAC,EAAU,SAAS,CAAQ,CAAC;CACxE,EAAQ,WAAW,KAGvB,QAAQ,KACJ,iEAAiE,KAAK,UAAU,CAAO,EAAE,4BAC1D,KAAK,UAAU,CAAS,EAAE,sEAE7D;AACJ;AASA,IAAa,IAAb,MAAa,EAAW;CAEC;CAkBD;CACC;CAOD;CA3BpB,YACI,GAkBA,GACA,GAOA,GACF;EADkB,AA1BC,KAAA,WAAA,GAkBD,KAAA,YAAA,GACC,KAAA,YAAA,GAOD,KAAA,qBAAA;CACjB;CAoBH,aAAa,OAAO,GAAoB,IAA6B,CAAC,GAAwB;EAC1F,IAAM,IAAY,EAAiB,EAAQ,SAAS,GAC9C,IAAW,MAAM,EAAgB,CAAS,GAC1C,IAAY,EAAS,SAAS,IAAI,IAAW,CAAC,CAAiB;EACrE,AAAI,EAAQ,cAAc,KAAA,KAAa,EAAQ,UAAU,SAAS,KAC9D,EAAuB,GAAW,CAAS;EAE/C,IAAM,IAAsD;GACxD,GAAI,EAAQ,kBAAkB,CAAC;GAC/B,oBACI;EACR,GACM,IAAgB,EAAQ,iBAAiB,IACzC,IAAS,OAAO,KAAU,YAAY,IAAgB,MAAM,EAAW,CAAK,IAAI,GAChF,IACF,KAAiB,OAAO,KAAW,WAAW,EAAkB,CAAM,IAAI,CAAC,GAE3E;EACJ,IAAI;GACA,AAKI,KALA,OAAO,KAAW,YAEX,aAAkB,YADf,MAAM,EAAW,iBAAiB,OAAO,GAAQ,CAAc;EASjF,SAAS,GAAK;GACV,MAAM,IAAI,EAAe,8BAA+B,EAAc,WAAW,EAC7E,OAAO,EACX,CAAC;EACL;EAEA,OAAO,IAAI,EAAW,GAAS,GAAW,GAAU,CAAS;CACjE;CAGA,IAAI,aAAgC;EAChC,OAAO,KAAK,SAAS;CACzB;CAGA,IAAI,YAAoB;EACpB,IAAM,IAAO,KAAK,SAAS,WAAW;EACtC,IAAI,MAAS,KAAA,GACT,MAAM,IAAI,EAAe,sBAAsB;EAEnD,OAAO;CACX;CAGA,IAAI,cAAiC;EACjC,OAAO,KAAK,SAAS;CACzB;CASA,IAAI,cAAwC;EACxC,OAAO,EACH,KAAK,SAAS,aAElB;CACJ;CAOA,IAAI,aAA4B;EAC5B,OAAO,KAAK,YAAY,MAAM,CAAC;CACnC;CAQA,IAAI,eAAyC;EACzC,OAAO,EACH,KAAK,SAAS,cAElB;CACJ;CAOA,IAAI,cAA6B;EAC7B,OAAO,KAAK,aAAa,MAAM,CAAC;CACpC;CAUA,IAAI,WAA6C;EAC7C,OAAO,KAAK;CAChB;CAUA,MAAM,UAAyB;EAC3B,MAAM,KAAK,SAAS,QAAQ,CAAC,CAAC,YAAY,KAAA,CAAS;CACvD;CAGA,IAAI,MAA4B;EAC5B,OAAO,KAAK;CAChB;CAQA,MAAM,IAAI,GAAwE;EAC9E,IAAI;GAEA,OAAO,MADc,KAAK,SAAS,IAAI,CAAK;EAEhD,SAAS,GAAK;GACV,MAAM,IAAI,EAAe,qBAAsB,EAAc,WAAW,EAAE,OAAO,EAAI,CAAC;EAC1F;CACJ;AACJ"}
@@ -1 +1 @@
1
- {"version":3,"file":"fusion.cjs","names":[],"sources":["../../src/vision/fusion.ts"],"sourcesContent":["/** @generated Vendored from @mauriciobenjamin700/ort-vision-sdk-web. Do not hand-edit — regenerate with `npm run vendor:vision`. */\n/**\n * The contract a fused pipeline carries inside its own `.onnx` file.\n *\n * A pipeline built by the Python SDK's `ort_vision_sdk.compose` is a single\n * graph that already contains the detector, the crop-and-resize bridge and the\n * classifier. Everything the runtime needs to drive it — the letterbox\n * resolution, the crop resolution, where the crops come from, how many\n * detections the graph emits, the class names of both stages — was decided at\n * fusion time and written into the model's metadata.\n *\n * This module reads it back. It is the browser half of a contract whose other\n * half lives in `ort_vision_sdk/fusion.py`: the same keys, the same encodings,\n * the same fallbacks. A pipeline fused once therefore runs identically in\n * Python and in a browser tab, off the same file.\n *\n * Building a pipeline stays a Python-side build step — there is no ONNX\n * protobuf writer here, and there is no reason for one: fusing is something you\n * do once next to your export pipeline, not in a page load.\n */\n\nimport { parseNames } from \"./core/metadata\";\n\n/**\n * Which tensor the bridge crops the detected boxes out of.\n *\n * - `\"detector_input\"`: the letterboxed tensor already fed to the detector.\n * The fused graph then has a **single** image input, but a small object is\n * cropped out of its downscaled copy.\n * - `\"original\"`: a second, full-resolution image input. The bridge undoes the\n * letterbox transform in-graph and crops at native resolution. Two tensors to\n * feed, still one session and one model load.\n */\nexport type CropSource = \"detector_input\" | \"original\";\n\n/** Value of the `ovs.kind` metadata key for a detector→classifier pipeline. */\nexport const FUSION_KIND_DETECT_CLASSIFY = \"detect_classify\";\n\n/**\n * Namespace for every metadata key the fusion writes.\n *\n * Namespaced on purpose: the detector's own Ultralytics metadata (`names`,\n * `task`, `imgsz`) is carried over into the fused model, and an un-prefixed key\n * would either collide with it or be mistaken for it.\n */\nexport const METADATA_PREFIX = \"ovs.\";\n\n/** Name of the fused graph's letterboxed detector input, `[1, 3, H, W]` float32 in `[0, 1]`. */\nexport const INPUT_IMAGE = \"images\";\n\n/** Name of the full-resolution input. Present only when `cropSource === \"original\"`. */\nexport const INPUT_SOURCE = \"source_image\";\n\n/** Name of the `[1]` float32 letterbox scale factor. Only with `cropSource === \"original\"`. */\nexport const INPUT_SCALE = \"letterbox_scale\";\n\n/** Name of the `[2]` float32 `[padLeft, padTop]`. Only with `cropSource === \"original\"`. */\nexport const INPUT_PAD = \"letterbox_pad\";\n\n/** Name of the `[K, 4]` float32 xyxy output, in **letterboxed** input pixels. */\nexport const OUTPUT_BOXES = \"boxes\";\n\n/** Name of the `[K]` float32 detection-confidence output. */\nexport const OUTPUT_SCORES = \"scores\";\n\n/** Name of the `[K]` int64 detector-class output. */\nexport const OUTPUT_CLASSES = \"classes\";\n\n/** Name of the `[1]` int64 output holding how many of the `K` rows are real. */\nexport const OUTPUT_NUM_DETECTIONS = \"num_detections\";\n\n/** Name of the `[K, numClassifierClasses]` float32 classifier output, one row per box. */\nexport const OUTPUT_PROBS = \"probs\";\n\n/** Everything a fused pipeline declares about how it must be driven. */\nexport interface FusionSpec {\n /** Pipeline family. Only `\"detect_classify\"` exists today. */\n readonly kind: string;\n /** `[width, height]` the detector stage expects — the resolution to letterbox to. */\n readonly inputSize: readonly [number, number];\n /** `[width, height]` every crop is resampled to inside the graph. */\n readonly cropSize: readonly [number, number];\n /** Which tensor the crops are taken from. */\n readonly cropSource: CropSource;\n /**\n * Fixed number of rows `K` every output carries, surplus zero-padded and\n * counted by {@link OUTPUT_NUM_DETECTIONS}. `null` means the graph emits\n * exactly as many rows as survived NMS.\n */\n readonly maxDetections: number | null;\n /** Score threshold baked into the graph's NMS node. */\n readonly confThreshold: number;\n /** IoU threshold baked into the graph's NMS node. */\n readonly iouThreshold: number;\n /** Whether the classifier stage emits logits that still need a softmax. */\n readonly applySoftmax: boolean;\n /** Detector class names in class-id order, or `null` when the fusion recorded none. */\n readonly detectorNames: readonly string[] | null;\n /** Classifier class names in class-id order, or `null`. */\n readonly classifierNames: readonly string[] | null;\n /** Version of `ort-vision-sdk` that produced the file. */\n readonly sdkVersion: string;\n /** Whether driving this pipeline requires feeding the full-resolution input. */\n readonly needsSourceImage: boolean;\n}\n\nconst KEY_KIND = \"kind\";\nconst KEY_SDK_VERSION = \"sdk_version\";\nconst KEY_INPUT_SIZE = \"input_size\";\nconst KEY_CROP_SIZE = \"crop_size\";\nconst KEY_CROP_SOURCE = \"crop_source\";\nconst KEY_MAX_DETECTIONS = \"max_detections\";\nconst KEY_CONF_THRESHOLD = \"conf_threshold\";\nconst KEY_IOU_THRESHOLD = \"iou_threshold\";\nconst KEY_APPLY_SOFTMAX = \"apply_softmax\";\nconst KEY_DETECTOR_NAMES = \"detector_names\";\nconst KEY_CLASSIFIER_NAMES = \"classifier_names\";\n\nconst DYNAMIC = \"dynamic\";\n\n/**\n * Decode a `\"640,640\"` pair.\n *\n * @param raw The encoded pair.\n * @returns `[width, height]`, or `null` when the value is missing or malformed.\n */\nfunction decodeSize(raw: string | undefined): readonly [number, number] | null {\n if (!raw) return null;\n const parts = raw.split(\",\");\n if (parts.length !== 2) return null;\n const width = Number(parts[0]);\n const height = Number(parts[1]);\n if (!Number.isInteger(width) || !Number.isInteger(height)) return null;\n if (width < 1 || height < 1) return null;\n return [width, height];\n}\n\n/**\n * Decode a float, falling back when the value is missing or malformed.\n *\n * @param raw The encoded value.\n * @param fallback Value to use when `raw` cannot be read.\n * @returns The parsed number, or `fallback`.\n */\nfunction decodeFloat(raw: string | undefined, fallback: number): number {\n if (!raw) return fallback;\n const value = Number(raw);\n return Number.isFinite(value) ? value : fallback;\n}\n\n/**\n * Read a pipeline spec out of a model's custom metadata.\n *\n * Individual malformed entries fall back to the value a fusion would have used\n * by default — a single bad float is not a reason to reject an otherwise\n * loadable pipeline. A malformed resolution is fatal, because there is no safe\n * default for one.\n *\n * @param metadata A model's custom metadata map, as read by\n * {@link readModelMetadata}.\n * @returns The decoded spec, or `null` when the model is not a fused pipeline —\n * it carries no `ovs.kind` entry, or one naming a pipeline kind this version\n * does not know how to drive.\n */\nexport function readFusionSpec(\n metadata: Readonly<Record<string, string>> | undefined,\n): FusionSpec | null {\n if (!metadata) return null;\n\n const read: Record<string, string> = {};\n for (const [key, value] of Object.entries(metadata)) {\n if (key.startsWith(METADATA_PREFIX)) read[key.slice(METADATA_PREFIX.length)] = value;\n }\n if (read[KEY_KIND] !== FUSION_KIND_DETECT_CLASSIFY) return null;\n\n const inputSize = decodeSize(read[KEY_INPUT_SIZE]);\n const cropSize = decodeSize(read[KEY_CROP_SIZE]);\n if (inputSize === null || cropSize === null) return null;\n\n const rawMax = read[KEY_MAX_DETECTIONS] ?? DYNAMIC;\n const parsedMax = Number(rawMax);\n const maxDetections =\n rawMax === DYNAMIC || !Number.isInteger(parsedMax) || parsedMax < 1 ? null : parsedMax;\n\n const cropSource: CropSource =\n read[KEY_CROP_SOURCE] === \"original\" ? \"original\" : \"detector_input\";\n\n return {\n kind: FUSION_KIND_DETECT_CLASSIFY,\n inputSize,\n cropSize,\n cropSource,\n maxDetections,\n confThreshold: decodeFloat(read[KEY_CONF_THRESHOLD], 0.25),\n iouThreshold: decodeFloat(read[KEY_IOU_THRESHOLD], 0.45),\n applySoftmax: (read[KEY_APPLY_SOFTMAX] ?? \"1\") !== \"0\",\n detectorNames: parseNames(read[KEY_DETECTOR_NAMES]),\n classifierNames: parseNames(read[KEY_CLASSIFIER_NAMES]),\n sdkVersion: read[KEY_SDK_VERSION] ?? \"\",\n needsSourceImage: cropSource === \"original\",\n };\n}\n"],"mappings":"uCAoCA,IAAa,EAA8B,kBAS9B,EAAkB,OAGlB,EAAc,SAGd,EAAe,eAGf,EAAc,kBAGd,EAAY,gBAGZ,EAAe,QAGf,EAAgB,SAGhB,EAAiB,UAGjB,EAAwB,iBAGxB,EAAe,QAkCtB,EAAW,OACX,EAAkB,cAClB,EAAiB,aACjB,EAAgB,YAChB,EAAkB,cAClB,EAAqB,iBACrB,EAAqB,iBACrB,EAAoB,gBACpB,EAAoB,gBACpB,EAAqB,iBACrB,EAAuB,mBAEvB,EAAU,UAQhB,SAAS,EAAW,EAA2D,CAC3E,GAAI,CAAC,EAAK,OAAO,KACjB,IAAM,EAAQ,EAAI,MAAM,GAAG,EAC3B,GAAI,EAAM,SAAW,EAAG,OAAO,KAC/B,IAAM,EAAQ,OAAO,EAAM,EAAE,EACvB,EAAS,OAAO,EAAM,EAAE,EAG9B,MAFI,CAAC,OAAO,UAAU,CAAK,GAAK,CAAC,OAAO,UAAU,CAAM,GACpD,EAAQ,GAAK,EAAS,EAAU,KAC7B,CAAC,EAAO,CAAM,CACzB,CASA,SAAS,EAAY,EAAyB,EAA0B,CACpE,GAAI,CAAC,EAAK,OAAO,EACjB,IAAM,EAAQ,OAAO,CAAG,EACxB,OAAO,OAAO,SAAS,CAAK,EAAI,EAAQ,CAC5C,CAgBA,SAAgB,EACZ,EACiB,CACjB,GAAI,CAAC,EAAU,OAAO,KAEtB,IAAM,EAA+B,CAAC,EACtC,IAAK,GAAM,CAAC,EAAK,KAAU,OAAO,QAAQ,CAAQ,EAC1C,EAAI,WAAA,MAA0B,IAAG,EAAK,EAAI,MAAM,CAAsB,GAAK,GAEnF,GAAI,EAAK,KAAA,kBAA2C,OAAO,KAE3D,IAAM,EAAY,EAAW,EAAK,EAAe,EAC3C,EAAW,EAAW,EAAK,EAAc,EAC/C,GAAI,IAAc,MAAQ,IAAa,KAAM,OAAO,KAEpD,IAAM,EAAS,EAAK,IAAuB,EACrC,EAAY,OAAO,CAAM,EACzB,EACF,IAAW,GAAW,CAAC,OAAO,UAAU,CAAS,GAAK,EAAY,EAAI,KAAO,EAE3E,EACF,EAAK,KAAqB,WAAa,WAAa,iBAExD,MAAO,CACH,KAAM,EACN,YACA,WACA,aACA,gBACA,cAAe,EAAY,EAAK,GAAqB,GAAI,EACzD,aAAc,EAAY,EAAK,GAAoB,GAAI,EACvD,cAAe,EAAK,IAAsB,OAAS,IACnD,cAAe,EAAA,WAAW,EAAK,EAAmB,EAClD,gBAAiB,EAAA,WAAW,EAAK,EAAqB,EACtD,WAAY,EAAK,IAAoB,GACrC,iBAAkB,IAAe,UACrC,CACJ"}
1
+ {"version":3,"file":"fusion.cjs","names":[],"sources":["../../src/vision/fusion.ts"],"sourcesContent":["/** @generated Vendored from @mauriciobenjamin700/ort-vision-sdk-web. Do not hand-edit — regenerate with `npm run vendor:vision`. */\n/**\n * The contract a fused pipeline carries inside its own `.onnx` file.\n *\n * A pipeline built by the Python SDK's `ort_vision_sdk.compose` is a single\n * graph that already contains the detector, the crop-and-resize bridge and the\n * classifier. Everything the runtime needs to drive it — the letterbox\n * resolution, the crop resolution, where the crops come from, how many\n * detections the graph emits, the class names of both stages — was decided at\n * fusion time and written into the model's metadata.\n *\n * This module reads it back. It is the browser half of a contract whose other\n * half lives in `ort_vision_sdk/fusion.py`: the same keys, the same encodings,\n * the same fallbacks. A pipeline fused once therefore runs identically in\n * Python and in a browser tab, off the same file.\n *\n * Building a pipeline stays a Python-side build step — there is no ONNX\n * protobuf writer here, and there is no reason for one: fusing is something you\n * do once next to your export pipeline, not in a page load.\n */\n\nimport { parseNames } from \"./core/metadata\";\n\n/**\n * Which tensor the bridge crops the detected boxes out of.\n *\n * - `\"detector_input\"`: the letterboxed tensor already fed to the detector.\n * The fused graph then has a **single** image input, but a small object is\n * cropped out of its downscaled copy.\n * - `\"original\"`: a second, full-resolution image input. The bridge undoes the\n * letterbox transform in-graph and crops at native resolution. Two tensors to\n * feed, still one session and one model load.\n */\nexport type CropSource = \"detector_input\" | \"original\";\n\n/** Value of the `ovs.kind` metadata key for a detector→classifier pipeline. */\nexport const FUSION_KIND_DETECT_CLASSIFY = \"detect_classify\";\n\n/**\n * Namespace for every metadata key the fusion writes.\n *\n * Namespaced on purpose: the detector's own Ultralytics metadata (`names`,\n * `task`, `imgsz`) is carried over into the fused model, and an un-prefixed key\n * would either collide with it or be mistaken for it.\n */\nexport const METADATA_PREFIX = \"ovs.\";\n\n/** Name of the fused graph's letterboxed detector input, `[1, 3, H, W]` float32 in `[0, 1]`. */\nexport const INPUT_IMAGE = \"images\";\n\n/** Name of the full-resolution input. Present only when `cropSource === \"original\"`. */\nexport const INPUT_SOURCE = \"source_image\";\n\n/** Name of the `[1]` float32 letterbox scale factor. Only with `cropSource === \"original\"`. */\nexport const INPUT_SCALE = \"letterbox_scale\";\n\n/** Name of the `[2]` float32 `[padLeft, padTop]`. Only with `cropSource === \"original\"`. */\nexport const INPUT_PAD = \"letterbox_pad\";\n\n/**\n * Name of the `[K, 4]` float32 xyxy output, in **letterboxed** input pixels.\n *\n * A file fused by `ort-vision-sdk` 0.9.0 or later reports the box that was\n * actually classified: clamped to the image the crop came from, exactly as\n * RoiAlign received it. Older files report the raw box, so one that ran off the\n * frame draws a rectangle wider than the region the classifier saw.\n */\nexport const OUTPUT_BOXES = \"boxes\";\n\n/** Name of the `[K]` float32 detection-confidence output. */\nexport const OUTPUT_SCORES = \"scores\";\n\n/** Name of the `[K]` int64 detector-class output. */\nexport const OUTPUT_CLASSES = \"classes\";\n\n/** Name of the `[1]` int64 output holding how many of the `K` rows are real. */\nexport const OUTPUT_NUM_DETECTIONS = \"num_detections\";\n\n/** Name of the `[K, numClassifierClasses]` float32 classifier output, one row per box. */\nexport const OUTPUT_PROBS = \"probs\";\n\n/** Everything a fused pipeline declares about how it must be driven. */\nexport interface FusionSpec {\n /** Pipeline family. Only `\"detect_classify\"` exists today. */\n readonly kind: string;\n /** `[width, height]` the detector stage expects — the resolution to letterbox to. */\n readonly inputSize: readonly [number, number];\n /** `[width, height]` every crop is resampled to inside the graph. */\n readonly cropSize: readonly [number, number];\n /** Which tensor the crops are taken from. */\n readonly cropSource: CropSource;\n /**\n * Fixed number of rows `K` every output carries, surplus zero-padded and\n * counted by {@link OUTPUT_NUM_DETECTIONS}. `null` means the graph emits\n * exactly as many rows as survived NMS.\n */\n readonly maxDetections: number | null;\n /** Score threshold baked into the graph's NMS node. */\n readonly confThreshold: number;\n /** IoU threshold baked into the graph's NMS node. */\n readonly iouThreshold: number;\n /** Whether the classifier stage emits logits that still need a softmax. */\n readonly applySoftmax: boolean;\n /** Detector class names in class-id order, or `null` when the fusion recorded none. */\n readonly detectorNames: readonly string[] | null;\n /** Classifier class names in class-id order, or `null`. */\n readonly classifierNames: readonly string[] | null;\n /** Version of `ort-vision-sdk` that produced the file. */\n readonly sdkVersion: string;\n /** Whether driving this pipeline requires feeding the full-resolution input. */\n readonly needsSourceImage: boolean;\n}\n\nconst KEY_KIND = \"kind\";\nconst KEY_SDK_VERSION = \"sdk_version\";\nconst KEY_INPUT_SIZE = \"input_size\";\nconst KEY_CROP_SIZE = \"crop_size\";\nconst KEY_CROP_SOURCE = \"crop_source\";\nconst KEY_MAX_DETECTIONS = \"max_detections\";\nconst KEY_CONF_THRESHOLD = \"conf_threshold\";\nconst KEY_IOU_THRESHOLD = \"iou_threshold\";\nconst KEY_APPLY_SOFTMAX = \"apply_softmax\";\nconst KEY_DETECTOR_NAMES = \"detector_names\";\nconst KEY_CLASSIFIER_NAMES = \"classifier_names\";\n\nconst DYNAMIC = \"dynamic\";\n\n/**\n * Decode a `\"640,640\"` pair.\n *\n * @param raw The encoded pair.\n * @returns `[width, height]`, or `null` when the value is missing or malformed.\n */\nfunction decodeSize(raw: string | undefined): readonly [number, number] | null {\n if (!raw) return null;\n const parts = raw.split(\",\");\n if (parts.length !== 2) return null;\n const width = Number(parts[0]);\n const height = Number(parts[1]);\n if (!Number.isInteger(width) || !Number.isInteger(height)) return null;\n if (width < 1 || height < 1) return null;\n return [width, height];\n}\n\n/**\n * Decode a float, falling back when the value is missing or malformed.\n *\n * @param raw The encoded value.\n * @param fallback Value to use when `raw` cannot be read.\n * @returns The parsed number, or `fallback`.\n */\nfunction decodeFloat(raw: string | undefined, fallback: number): number {\n if (!raw) return fallback;\n const value = Number(raw);\n return Number.isFinite(value) ? value : fallback;\n}\n\n/**\n * Read a pipeline spec out of a model's custom metadata.\n *\n * Individual malformed entries fall back to the value a fusion would have used\n * by default — a single bad float is not a reason to reject an otherwise\n * loadable pipeline. A malformed resolution is fatal, because there is no safe\n * default for one.\n *\n * @param metadata A model's custom metadata map, as read by\n * {@link readModelMetadata}.\n * @returns The decoded spec, or `null` when the model is not a fused pipeline —\n * it carries no `ovs.kind` entry, or one naming a pipeline kind this version\n * does not know how to drive.\n */\nexport function readFusionSpec(\n metadata: Readonly<Record<string, string>> | undefined,\n): FusionSpec | null {\n if (!metadata) return null;\n\n const read: Record<string, string> = {};\n for (const [key, value] of Object.entries(metadata)) {\n if (key.startsWith(METADATA_PREFIX)) read[key.slice(METADATA_PREFIX.length)] = value;\n }\n if (read[KEY_KIND] !== FUSION_KIND_DETECT_CLASSIFY) return null;\n\n const inputSize = decodeSize(read[KEY_INPUT_SIZE]);\n const cropSize = decodeSize(read[KEY_CROP_SIZE]);\n if (inputSize === null || cropSize === null) return null;\n\n const rawMax = read[KEY_MAX_DETECTIONS] ?? DYNAMIC;\n const parsedMax = Number(rawMax);\n const maxDetections =\n rawMax === DYNAMIC || !Number.isInteger(parsedMax) || parsedMax < 1 ? null : parsedMax;\n\n const cropSource: CropSource =\n read[KEY_CROP_SOURCE] === \"original\" ? \"original\" : \"detector_input\";\n\n return {\n kind: FUSION_KIND_DETECT_CLASSIFY,\n inputSize,\n cropSize,\n cropSource,\n maxDetections,\n confThreshold: decodeFloat(read[KEY_CONF_THRESHOLD], 0.25),\n iouThreshold: decodeFloat(read[KEY_IOU_THRESHOLD], 0.45),\n applySoftmax: (read[KEY_APPLY_SOFTMAX] ?? \"1\") !== \"0\",\n detectorNames: parseNames(read[KEY_DETECTOR_NAMES]),\n classifierNames: parseNames(read[KEY_CLASSIFIER_NAMES]),\n sdkVersion: read[KEY_SDK_VERSION] ?? \"\",\n needsSourceImage: cropSource === \"original\",\n };\n}\n"],"mappings":"uCAoCA,IAAa,EAA8B,kBAS9B,EAAkB,OAGlB,EAAc,SAGd,EAAe,eAGf,EAAc,kBAGd,EAAY,gBAUZ,EAAe,QAGf,EAAgB,SAGhB,EAAiB,UAGjB,EAAwB,iBAGxB,EAAe,QAkCtB,EAAW,OACX,EAAkB,cAClB,EAAiB,aACjB,EAAgB,YAChB,EAAkB,cAClB,EAAqB,iBACrB,EAAqB,iBACrB,EAAoB,gBACpB,EAAoB,gBACpB,EAAqB,iBACrB,EAAuB,mBAEvB,EAAU,UAQhB,SAAS,EAAW,EAA2D,CAC3E,GAAI,CAAC,EAAK,OAAO,KACjB,IAAM,EAAQ,EAAI,MAAM,GAAG,EAC3B,GAAI,EAAM,SAAW,EAAG,OAAO,KAC/B,IAAM,EAAQ,OAAO,EAAM,EAAE,EACvB,EAAS,OAAO,EAAM,EAAE,EAG9B,MAFI,CAAC,OAAO,UAAU,CAAK,GAAK,CAAC,OAAO,UAAU,CAAM,GACpD,EAAQ,GAAK,EAAS,EAAU,KAC7B,CAAC,EAAO,CAAM,CACzB,CASA,SAAS,EAAY,EAAyB,EAA0B,CACpE,GAAI,CAAC,EAAK,OAAO,EACjB,IAAM,EAAQ,OAAO,CAAG,EACxB,OAAO,OAAO,SAAS,CAAK,EAAI,EAAQ,CAC5C,CAgBA,SAAgB,EACZ,EACiB,CACjB,GAAI,CAAC,EAAU,OAAO,KAEtB,IAAM,EAA+B,CAAC,EACtC,IAAK,GAAM,CAAC,EAAK,KAAU,OAAO,QAAQ,CAAQ,EAC1C,EAAI,WAAA,MAA0B,IAAG,EAAK,EAAI,MAAM,CAAsB,GAAK,GAEnF,GAAI,EAAK,KAAA,kBAA2C,OAAO,KAE3D,IAAM,EAAY,EAAW,EAAK,EAAe,EAC3C,EAAW,EAAW,EAAK,EAAc,EAC/C,GAAI,IAAc,MAAQ,IAAa,KAAM,OAAO,KAEpD,IAAM,EAAS,EAAK,IAAuB,EACrC,EAAY,OAAO,CAAM,EACzB,EACF,IAAW,GAAW,CAAC,OAAO,UAAU,CAAS,GAAK,EAAY,EAAI,KAAO,EAE3E,EACF,EAAK,KAAqB,WAAa,WAAa,iBAExD,MAAO,CACH,KAAM,EACN,YACA,WACA,aACA,gBACA,cAAe,EAAY,EAAK,GAAqB,GAAI,EACzD,aAAc,EAAY,EAAK,GAAoB,GAAI,EACvD,cAAe,EAAK,IAAsB,OAAS,IACnD,cAAe,EAAA,WAAW,EAAK,EAAmB,EAClD,gBAAiB,EAAA,WAAW,EAAK,EAAqB,EACtD,WAAY,EAAK,IAAoB,GACrC,iBAAkB,IAAe,UACrC,CACJ"}
@@ -1 +1 @@
1
- {"version":3,"file":"fusion.js","names":[],"sources":["../../src/vision/fusion.ts"],"sourcesContent":["/** @generated Vendored from @mauriciobenjamin700/ort-vision-sdk-web. Do not hand-edit — regenerate with `npm run vendor:vision`. */\n/**\n * The contract a fused pipeline carries inside its own `.onnx` file.\n *\n * A pipeline built by the Python SDK's `ort_vision_sdk.compose` is a single\n * graph that already contains the detector, the crop-and-resize bridge and the\n * classifier. Everything the runtime needs to drive it — the letterbox\n * resolution, the crop resolution, where the crops come from, how many\n * detections the graph emits, the class names of both stages — was decided at\n * fusion time and written into the model's metadata.\n *\n * This module reads it back. It is the browser half of a contract whose other\n * half lives in `ort_vision_sdk/fusion.py`: the same keys, the same encodings,\n * the same fallbacks. A pipeline fused once therefore runs identically in\n * Python and in a browser tab, off the same file.\n *\n * Building a pipeline stays a Python-side build step — there is no ONNX\n * protobuf writer here, and there is no reason for one: fusing is something you\n * do once next to your export pipeline, not in a page load.\n */\n\nimport { parseNames } from \"./core/metadata\";\n\n/**\n * Which tensor the bridge crops the detected boxes out of.\n *\n * - `\"detector_input\"`: the letterboxed tensor already fed to the detector.\n * The fused graph then has a **single** image input, but a small object is\n * cropped out of its downscaled copy.\n * - `\"original\"`: a second, full-resolution image input. The bridge undoes the\n * letterbox transform in-graph and crops at native resolution. Two tensors to\n * feed, still one session and one model load.\n */\nexport type CropSource = \"detector_input\" | \"original\";\n\n/** Value of the `ovs.kind` metadata key for a detector→classifier pipeline. */\nexport const FUSION_KIND_DETECT_CLASSIFY = \"detect_classify\";\n\n/**\n * Namespace for every metadata key the fusion writes.\n *\n * Namespaced on purpose: the detector's own Ultralytics metadata (`names`,\n * `task`, `imgsz`) is carried over into the fused model, and an un-prefixed key\n * would either collide with it or be mistaken for it.\n */\nexport const METADATA_PREFIX = \"ovs.\";\n\n/** Name of the fused graph's letterboxed detector input, `[1, 3, H, W]` float32 in `[0, 1]`. */\nexport const INPUT_IMAGE = \"images\";\n\n/** Name of the full-resolution input. Present only when `cropSource === \"original\"`. */\nexport const INPUT_SOURCE = \"source_image\";\n\n/** Name of the `[1]` float32 letterbox scale factor. Only with `cropSource === \"original\"`. */\nexport const INPUT_SCALE = \"letterbox_scale\";\n\n/** Name of the `[2]` float32 `[padLeft, padTop]`. Only with `cropSource === \"original\"`. */\nexport const INPUT_PAD = \"letterbox_pad\";\n\n/** Name of the `[K, 4]` float32 xyxy output, in **letterboxed** input pixels. */\nexport const OUTPUT_BOXES = \"boxes\";\n\n/** Name of the `[K]` float32 detection-confidence output. */\nexport const OUTPUT_SCORES = \"scores\";\n\n/** Name of the `[K]` int64 detector-class output. */\nexport const OUTPUT_CLASSES = \"classes\";\n\n/** Name of the `[1]` int64 output holding how many of the `K` rows are real. */\nexport const OUTPUT_NUM_DETECTIONS = \"num_detections\";\n\n/** Name of the `[K, numClassifierClasses]` float32 classifier output, one row per box. */\nexport const OUTPUT_PROBS = \"probs\";\n\n/** Everything a fused pipeline declares about how it must be driven. */\nexport interface FusionSpec {\n /** Pipeline family. Only `\"detect_classify\"` exists today. */\n readonly kind: string;\n /** `[width, height]` the detector stage expects — the resolution to letterbox to. */\n readonly inputSize: readonly [number, number];\n /** `[width, height]` every crop is resampled to inside the graph. */\n readonly cropSize: readonly [number, number];\n /** Which tensor the crops are taken from. */\n readonly cropSource: CropSource;\n /**\n * Fixed number of rows `K` every output carries, surplus zero-padded and\n * counted by {@link OUTPUT_NUM_DETECTIONS}. `null` means the graph emits\n * exactly as many rows as survived NMS.\n */\n readonly maxDetections: number | null;\n /** Score threshold baked into the graph's NMS node. */\n readonly confThreshold: number;\n /** IoU threshold baked into the graph's NMS node. */\n readonly iouThreshold: number;\n /** Whether the classifier stage emits logits that still need a softmax. */\n readonly applySoftmax: boolean;\n /** Detector class names in class-id order, or `null` when the fusion recorded none. */\n readonly detectorNames: readonly string[] | null;\n /** Classifier class names in class-id order, or `null`. */\n readonly classifierNames: readonly string[] | null;\n /** Version of `ort-vision-sdk` that produced the file. */\n readonly sdkVersion: string;\n /** Whether driving this pipeline requires feeding the full-resolution input. */\n readonly needsSourceImage: boolean;\n}\n\nconst KEY_KIND = \"kind\";\nconst KEY_SDK_VERSION = \"sdk_version\";\nconst KEY_INPUT_SIZE = \"input_size\";\nconst KEY_CROP_SIZE = \"crop_size\";\nconst KEY_CROP_SOURCE = \"crop_source\";\nconst KEY_MAX_DETECTIONS = \"max_detections\";\nconst KEY_CONF_THRESHOLD = \"conf_threshold\";\nconst KEY_IOU_THRESHOLD = \"iou_threshold\";\nconst KEY_APPLY_SOFTMAX = \"apply_softmax\";\nconst KEY_DETECTOR_NAMES = \"detector_names\";\nconst KEY_CLASSIFIER_NAMES = \"classifier_names\";\n\nconst DYNAMIC = \"dynamic\";\n\n/**\n * Decode a `\"640,640\"` pair.\n *\n * @param raw The encoded pair.\n * @returns `[width, height]`, or `null` when the value is missing or malformed.\n */\nfunction decodeSize(raw: string | undefined): readonly [number, number] | null {\n if (!raw) return null;\n const parts = raw.split(\",\");\n if (parts.length !== 2) return null;\n const width = Number(parts[0]);\n const height = Number(parts[1]);\n if (!Number.isInteger(width) || !Number.isInteger(height)) return null;\n if (width < 1 || height < 1) return null;\n return [width, height];\n}\n\n/**\n * Decode a float, falling back when the value is missing or malformed.\n *\n * @param raw The encoded value.\n * @param fallback Value to use when `raw` cannot be read.\n * @returns The parsed number, or `fallback`.\n */\nfunction decodeFloat(raw: string | undefined, fallback: number): number {\n if (!raw) return fallback;\n const value = Number(raw);\n return Number.isFinite(value) ? value : fallback;\n}\n\n/**\n * Read a pipeline spec out of a model's custom metadata.\n *\n * Individual malformed entries fall back to the value a fusion would have used\n * by default — a single bad float is not a reason to reject an otherwise\n * loadable pipeline. A malformed resolution is fatal, because there is no safe\n * default for one.\n *\n * @param metadata A model's custom metadata map, as read by\n * {@link readModelMetadata}.\n * @returns The decoded spec, or `null` when the model is not a fused pipeline —\n * it carries no `ovs.kind` entry, or one naming a pipeline kind this version\n * does not know how to drive.\n */\nexport function readFusionSpec(\n metadata: Readonly<Record<string, string>> | undefined,\n): FusionSpec | null {\n if (!metadata) return null;\n\n const read: Record<string, string> = {};\n for (const [key, value] of Object.entries(metadata)) {\n if (key.startsWith(METADATA_PREFIX)) read[key.slice(METADATA_PREFIX.length)] = value;\n }\n if (read[KEY_KIND] !== FUSION_KIND_DETECT_CLASSIFY) return null;\n\n const inputSize = decodeSize(read[KEY_INPUT_SIZE]);\n const cropSize = decodeSize(read[KEY_CROP_SIZE]);\n if (inputSize === null || cropSize === null) return null;\n\n const rawMax = read[KEY_MAX_DETECTIONS] ?? DYNAMIC;\n const parsedMax = Number(rawMax);\n const maxDetections =\n rawMax === DYNAMIC || !Number.isInteger(parsedMax) || parsedMax < 1 ? null : parsedMax;\n\n const cropSource: CropSource =\n read[KEY_CROP_SOURCE] === \"original\" ? \"original\" : \"detector_input\";\n\n return {\n kind: FUSION_KIND_DETECT_CLASSIFY,\n inputSize,\n cropSize,\n cropSource,\n maxDetections,\n confThreshold: decodeFloat(read[KEY_CONF_THRESHOLD], 0.25),\n iouThreshold: decodeFloat(read[KEY_IOU_THRESHOLD], 0.45),\n applySoftmax: (read[KEY_APPLY_SOFTMAX] ?? \"1\") !== \"0\",\n detectorNames: parseNames(read[KEY_DETECTOR_NAMES]),\n classifierNames: parseNames(read[KEY_CLASSIFIER_NAMES]),\n sdkVersion: read[KEY_SDK_VERSION] ?? \"\",\n needsSourceImage: cropSource === \"original\",\n };\n}\n"],"mappings":";;AAoCA,IAAa,IAA8B,mBAS9B,IAAkB,QAGlB,IAAc,UAGd,IAAe,gBAGf,IAAc,mBAGd,IAAY,iBAGZ,IAAe,SAGf,IAAgB,UAGhB,IAAiB,WAGjB,IAAwB,kBAGxB,IAAe,SAkCtB,IAAW,QACX,IAAkB,eAClB,IAAiB,cACjB,IAAgB,aAChB,IAAkB,eAClB,IAAqB,kBACrB,IAAqB,kBACrB,IAAoB,iBACpB,IAAoB,iBACpB,IAAqB,kBACrB,IAAuB,oBAEvB,IAAU;AAQhB,SAAS,EAAW,GAA2D;CAC3E,IAAI,CAAC,GAAK,OAAO;CACjB,IAAM,IAAQ,EAAI,MAAM,GAAG;CAC3B,IAAI,EAAM,WAAW,GAAG,OAAO;CAC/B,IAAM,IAAQ,OAAO,EAAM,EAAE,GACvB,IAAS,OAAO,EAAM,EAAE;CAG9B,OAFI,CAAC,OAAO,UAAU,CAAK,KAAK,CAAC,OAAO,UAAU,CAAM,KACpD,IAAQ,KAAK,IAAS,IAAU,OAC7B,CAAC,GAAO,CAAM;AACzB;AASA,SAAS,EAAY,GAAyB,GAA0B;CACpE,IAAI,CAAC,GAAK,OAAO;CACjB,IAAM,IAAQ,OAAO,CAAG;CACxB,OAAO,OAAO,SAAS,CAAK,IAAI,IAAQ;AAC5C;AAgBA,SAAgB,EACZ,GACiB;CACjB,IAAI,CAAC,GAAU,OAAO;CAEtB,IAAM,IAA+B,CAAC;CACtC,KAAK,IAAM,CAAC,GAAK,MAAU,OAAO,QAAQ,CAAQ,GAC9C,AAAI,EAAI,WAAA,MAA0B,MAAG,EAAK,EAAI,MAAM,CAAsB,KAAK;CAEnF,IAAI,EAAK,OAAA,mBAA2C,OAAO;CAE3D,IAAM,IAAY,EAAW,EAAK,EAAe,GAC3C,IAAW,EAAW,EAAK,EAAc;CAC/C,IAAI,MAAc,QAAQ,MAAa,MAAM,OAAO;CAEpD,IAAM,IAAS,EAAK,MAAuB,GACrC,IAAY,OAAO,CAAM,GACzB,IACF,MAAW,KAAW,CAAC,OAAO,UAAU,CAAS,KAAK,IAAY,IAAI,OAAO,GAE3E,IACF,EAAK,OAAqB,aAAa,aAAa;CAExD,OAAO;EACH,MAAM;EACN;EACA;EACA;EACA;EACA,eAAe,EAAY,EAAK,IAAqB,GAAI;EACzD,cAAc,EAAY,EAAK,IAAoB,GAAI;EACvD,eAAe,EAAK,MAAsB,SAAS;EACnD,eAAe,EAAW,EAAK,EAAmB;EAClD,iBAAiB,EAAW,EAAK,EAAqB;EACtD,YAAY,EAAK,MAAoB;EACrC,kBAAkB,MAAe;CACrC;AACJ"}
1
+ {"version":3,"file":"fusion.js","names":[],"sources":["../../src/vision/fusion.ts"],"sourcesContent":["/** @generated Vendored from @mauriciobenjamin700/ort-vision-sdk-web. Do not hand-edit — regenerate with `npm run vendor:vision`. */\n/**\n * The contract a fused pipeline carries inside its own `.onnx` file.\n *\n * A pipeline built by the Python SDK's `ort_vision_sdk.compose` is a single\n * graph that already contains the detector, the crop-and-resize bridge and the\n * classifier. Everything the runtime needs to drive it — the letterbox\n * resolution, the crop resolution, where the crops come from, how many\n * detections the graph emits, the class names of both stages — was decided at\n * fusion time and written into the model's metadata.\n *\n * This module reads it back. It is the browser half of a contract whose other\n * half lives in `ort_vision_sdk/fusion.py`: the same keys, the same encodings,\n * the same fallbacks. A pipeline fused once therefore runs identically in\n * Python and in a browser tab, off the same file.\n *\n * Building a pipeline stays a Python-side build step — there is no ONNX\n * protobuf writer here, and there is no reason for one: fusing is something you\n * do once next to your export pipeline, not in a page load.\n */\n\nimport { parseNames } from \"./core/metadata\";\n\n/**\n * Which tensor the bridge crops the detected boxes out of.\n *\n * - `\"detector_input\"`: the letterboxed tensor already fed to the detector.\n * The fused graph then has a **single** image input, but a small object is\n * cropped out of its downscaled copy.\n * - `\"original\"`: a second, full-resolution image input. The bridge undoes the\n * letterbox transform in-graph and crops at native resolution. Two tensors to\n * feed, still one session and one model load.\n */\nexport type CropSource = \"detector_input\" | \"original\";\n\n/** Value of the `ovs.kind` metadata key for a detector→classifier pipeline. */\nexport const FUSION_KIND_DETECT_CLASSIFY = \"detect_classify\";\n\n/**\n * Namespace for every metadata key the fusion writes.\n *\n * Namespaced on purpose: the detector's own Ultralytics metadata (`names`,\n * `task`, `imgsz`) is carried over into the fused model, and an un-prefixed key\n * would either collide with it or be mistaken for it.\n */\nexport const METADATA_PREFIX = \"ovs.\";\n\n/** Name of the fused graph's letterboxed detector input, `[1, 3, H, W]` float32 in `[0, 1]`. */\nexport const INPUT_IMAGE = \"images\";\n\n/** Name of the full-resolution input. Present only when `cropSource === \"original\"`. */\nexport const INPUT_SOURCE = \"source_image\";\n\n/** Name of the `[1]` float32 letterbox scale factor. Only with `cropSource === \"original\"`. */\nexport const INPUT_SCALE = \"letterbox_scale\";\n\n/** Name of the `[2]` float32 `[padLeft, padTop]`. Only with `cropSource === \"original\"`. */\nexport const INPUT_PAD = \"letterbox_pad\";\n\n/**\n * Name of the `[K, 4]` float32 xyxy output, in **letterboxed** input pixels.\n *\n * A file fused by `ort-vision-sdk` 0.9.0 or later reports the box that was\n * actually classified: clamped to the image the crop came from, exactly as\n * RoiAlign received it. Older files report the raw box, so one that ran off the\n * frame draws a rectangle wider than the region the classifier saw.\n */\nexport const OUTPUT_BOXES = \"boxes\";\n\n/** Name of the `[K]` float32 detection-confidence output. */\nexport const OUTPUT_SCORES = \"scores\";\n\n/** Name of the `[K]` int64 detector-class output. */\nexport const OUTPUT_CLASSES = \"classes\";\n\n/** Name of the `[1]` int64 output holding how many of the `K` rows are real. */\nexport const OUTPUT_NUM_DETECTIONS = \"num_detections\";\n\n/** Name of the `[K, numClassifierClasses]` float32 classifier output, one row per box. */\nexport const OUTPUT_PROBS = \"probs\";\n\n/** Everything a fused pipeline declares about how it must be driven. */\nexport interface FusionSpec {\n /** Pipeline family. Only `\"detect_classify\"` exists today. */\n readonly kind: string;\n /** `[width, height]` the detector stage expects — the resolution to letterbox to. */\n readonly inputSize: readonly [number, number];\n /** `[width, height]` every crop is resampled to inside the graph. */\n readonly cropSize: readonly [number, number];\n /** Which tensor the crops are taken from. */\n readonly cropSource: CropSource;\n /**\n * Fixed number of rows `K` every output carries, surplus zero-padded and\n * counted by {@link OUTPUT_NUM_DETECTIONS}. `null` means the graph emits\n * exactly as many rows as survived NMS.\n */\n readonly maxDetections: number | null;\n /** Score threshold baked into the graph's NMS node. */\n readonly confThreshold: number;\n /** IoU threshold baked into the graph's NMS node. */\n readonly iouThreshold: number;\n /** Whether the classifier stage emits logits that still need a softmax. */\n readonly applySoftmax: boolean;\n /** Detector class names in class-id order, or `null` when the fusion recorded none. */\n readonly detectorNames: readonly string[] | null;\n /** Classifier class names in class-id order, or `null`. */\n readonly classifierNames: readonly string[] | null;\n /** Version of `ort-vision-sdk` that produced the file. */\n readonly sdkVersion: string;\n /** Whether driving this pipeline requires feeding the full-resolution input. */\n readonly needsSourceImage: boolean;\n}\n\nconst KEY_KIND = \"kind\";\nconst KEY_SDK_VERSION = \"sdk_version\";\nconst KEY_INPUT_SIZE = \"input_size\";\nconst KEY_CROP_SIZE = \"crop_size\";\nconst KEY_CROP_SOURCE = \"crop_source\";\nconst KEY_MAX_DETECTIONS = \"max_detections\";\nconst KEY_CONF_THRESHOLD = \"conf_threshold\";\nconst KEY_IOU_THRESHOLD = \"iou_threshold\";\nconst KEY_APPLY_SOFTMAX = \"apply_softmax\";\nconst KEY_DETECTOR_NAMES = \"detector_names\";\nconst KEY_CLASSIFIER_NAMES = \"classifier_names\";\n\nconst DYNAMIC = \"dynamic\";\n\n/**\n * Decode a `\"640,640\"` pair.\n *\n * @param raw The encoded pair.\n * @returns `[width, height]`, or `null` when the value is missing or malformed.\n */\nfunction decodeSize(raw: string | undefined): readonly [number, number] | null {\n if (!raw) return null;\n const parts = raw.split(\",\");\n if (parts.length !== 2) return null;\n const width = Number(parts[0]);\n const height = Number(parts[1]);\n if (!Number.isInteger(width) || !Number.isInteger(height)) return null;\n if (width < 1 || height < 1) return null;\n return [width, height];\n}\n\n/**\n * Decode a float, falling back when the value is missing or malformed.\n *\n * @param raw The encoded value.\n * @param fallback Value to use when `raw` cannot be read.\n * @returns The parsed number, or `fallback`.\n */\nfunction decodeFloat(raw: string | undefined, fallback: number): number {\n if (!raw) return fallback;\n const value = Number(raw);\n return Number.isFinite(value) ? value : fallback;\n}\n\n/**\n * Read a pipeline spec out of a model's custom metadata.\n *\n * Individual malformed entries fall back to the value a fusion would have used\n * by default — a single bad float is not a reason to reject an otherwise\n * loadable pipeline. A malformed resolution is fatal, because there is no safe\n * default for one.\n *\n * @param metadata A model's custom metadata map, as read by\n * {@link readModelMetadata}.\n * @returns The decoded spec, or `null` when the model is not a fused pipeline —\n * it carries no `ovs.kind` entry, or one naming a pipeline kind this version\n * does not know how to drive.\n */\nexport function readFusionSpec(\n metadata: Readonly<Record<string, string>> | undefined,\n): FusionSpec | null {\n if (!metadata) return null;\n\n const read: Record<string, string> = {};\n for (const [key, value] of Object.entries(metadata)) {\n if (key.startsWith(METADATA_PREFIX)) read[key.slice(METADATA_PREFIX.length)] = value;\n }\n if (read[KEY_KIND] !== FUSION_KIND_DETECT_CLASSIFY) return null;\n\n const inputSize = decodeSize(read[KEY_INPUT_SIZE]);\n const cropSize = decodeSize(read[KEY_CROP_SIZE]);\n if (inputSize === null || cropSize === null) return null;\n\n const rawMax = read[KEY_MAX_DETECTIONS] ?? DYNAMIC;\n const parsedMax = Number(rawMax);\n const maxDetections =\n rawMax === DYNAMIC || !Number.isInteger(parsedMax) || parsedMax < 1 ? null : parsedMax;\n\n const cropSource: CropSource =\n read[KEY_CROP_SOURCE] === \"original\" ? \"original\" : \"detector_input\";\n\n return {\n kind: FUSION_KIND_DETECT_CLASSIFY,\n inputSize,\n cropSize,\n cropSource,\n maxDetections,\n confThreshold: decodeFloat(read[KEY_CONF_THRESHOLD], 0.25),\n iouThreshold: decodeFloat(read[KEY_IOU_THRESHOLD], 0.45),\n applySoftmax: (read[KEY_APPLY_SOFTMAX] ?? \"1\") !== \"0\",\n detectorNames: parseNames(read[KEY_DETECTOR_NAMES]),\n classifierNames: parseNames(read[KEY_CLASSIFIER_NAMES]),\n sdkVersion: read[KEY_SDK_VERSION] ?? \"\",\n needsSourceImage: cropSource === \"original\",\n };\n}\n"],"mappings":";;AAoCA,IAAa,IAA8B,mBAS9B,IAAkB,QAGlB,IAAc,UAGd,IAAe,gBAGf,IAAc,mBAGd,IAAY,iBAUZ,IAAe,SAGf,IAAgB,UAGhB,IAAiB,WAGjB,IAAwB,kBAGxB,IAAe,SAkCtB,IAAW,QACX,IAAkB,eAClB,IAAiB,cACjB,IAAgB,aAChB,IAAkB,eAClB,IAAqB,kBACrB,IAAqB,kBACrB,IAAoB,iBACpB,IAAoB,iBACpB,IAAqB,kBACrB,IAAuB,oBAEvB,IAAU;AAQhB,SAAS,EAAW,GAA2D;CAC3E,IAAI,CAAC,GAAK,OAAO;CACjB,IAAM,IAAQ,EAAI,MAAM,GAAG;CAC3B,IAAI,EAAM,WAAW,GAAG,OAAO;CAC/B,IAAM,IAAQ,OAAO,EAAM,EAAE,GACvB,IAAS,OAAO,EAAM,EAAE;CAG9B,OAFI,CAAC,OAAO,UAAU,CAAK,KAAK,CAAC,OAAO,UAAU,CAAM,KACpD,IAAQ,KAAK,IAAS,IAAU,OAC7B,CAAC,GAAO,CAAM;AACzB;AASA,SAAS,EAAY,GAAyB,GAA0B;CACpE,IAAI,CAAC,GAAK,OAAO;CACjB,IAAM,IAAQ,OAAO,CAAG;CACxB,OAAO,OAAO,SAAS,CAAK,IAAI,IAAQ;AAC5C;AAgBA,SAAgB,EACZ,GACiB;CACjB,IAAI,CAAC,GAAU,OAAO;CAEtB,IAAM,IAA+B,CAAC;CACtC,KAAK,IAAM,CAAC,GAAK,MAAU,OAAO,QAAQ,CAAQ,GAC9C,AAAI,EAAI,WAAA,MAA0B,MAAG,EAAK,EAAI,MAAM,CAAsB,KAAK;CAEnF,IAAI,EAAK,OAAA,mBAA2C,OAAO;CAE3D,IAAM,IAAY,EAAW,EAAK,EAAe,GAC3C,IAAW,EAAW,EAAK,EAAc;CAC/C,IAAI,MAAc,QAAQ,MAAa,MAAM,OAAO;CAEpD,IAAM,IAAS,EAAK,MAAuB,GACrC,IAAY,OAAO,CAAM,GACzB,IACF,MAAW,KAAW,CAAC,OAAO,UAAU,CAAS,KAAK,IAAY,IAAI,OAAO,GAE3E,IACF,EAAK,OAAqB,aAAa,aAAa;CAExD,OAAO;EACH,MAAM;EACN;EACA;EACA;EACA;EACA,eAAe,EAAY,EAAK,IAAqB,GAAI;EACzD,cAAc,EAAY,EAAK,IAAoB,GAAI;EACvD,eAAe,EAAK,MAAsB,SAAS;EACnD,eAAe,EAAW,EAAK,EAAmB;EAClD,iBAAiB,EAAW,EAAK,EAAqB;EACtD,YAAY,EAAK,MAAoB;EACrC,kBAAkB,MAAe;CACrC;AACJ"}
@@ -1,2 +1,2 @@
1
- const e=require("./core/exceptions.cjs"),t=require("./types.cjs"),n=require("./core/timing.cjs"),r=require("./results.cjs"),i=require("./labels.cjs"),a=require("./core/graph.cjs"),o=require("./core/metadata.cjs"),s=require("./core/providers.cjs"),c=require("./core/session.cjs"),l=require("./io/image.cjs"),u=require("./fusion.cjs"),d=require("./preprocess/image.cjs"),f=require("./preprocess/pipeline.cjs"),p=require("./postprocess/classification.cjs"),m=require("./postprocess/detection.cjs"),h=require("./postprocess/segmentation.cjs"),g=require("./tasks/base.cjs"),_=require("./tasks/classifier.cjs"),v=require("./tasks/detectClassify.cjs"),y=require("./tasks/detector.cjs"),b=require("./tasks/segmenter.cjs");var x=`0.7.1`;exports.BoundingBox=t.BoundingBox,exports.Boxes=r.Boxes,exports.COCO_CLASSES=i.COCO_CLASSES,exports.ClassificationResults=r.ClassificationResults,exports.Classifier=_.Classifier,exports.DEFAULT_PROVIDERS=s.DEFAULT_PROVIDERS,exports.DetectClassify=v.DetectClassify,exports.DetectClassifyResults=r.DetectClassifyResults,exports.DetectionResults=r.DetectionResults,exports.Detector=y.Detector,exports.FUSION_KIND_DETECT_CLASSIFY=u.FUSION_KIND_DETECT_CLASSIFY,exports.FusionError=e.FusionError,exports.INPUT_IMAGE=u.INPUT_IMAGE,exports.INPUT_PAD=u.INPUT_PAD,exports.INPUT_SCALE=u.INPUT_SCALE,exports.INPUT_SOURCE=u.INPUT_SOURCE,exports.ImageLoadError=e.ImageLoadError,exports.InferenceError=e.InferenceError,exports.LabelMapError=e.LabelMapError,exports.LetterboxPipeline=f.LetterboxPipeline,exports.METADATA_PREFIX=u.METADATA_PREFIX,exports.Mask=t.Mask,exports.Masks=r.Masks,exports.ModelLoadError=e.ModelLoadError,exports.NoDetectionsError=e.NoDetectionsError,exports.OUTPUT_BOXES=u.OUTPUT_BOXES,exports.OUTPUT_CLASSES=u.OUTPUT_CLASSES,exports.OUTPUT_NUM_DETECTIONS=u.OUTPUT_NUM_DETECTIONS,exports.OUTPUT_PROBS=u.OUTPUT_PROBS,exports.OUTPUT_SCORES=u.OUTPUT_SCORES,exports.OrtSession=c.OrtSession,exports.OrtVisionError=e.OrtVisionError,exports.Probs=r.Probs,exports.ProviderNotAvailableError=e.ProviderNotAvailableError,exports.RGBImage=t.RGBImage,exports.ResizePipeline=f.ResizePipeline,exports.SegmentationResults=r.SegmentationResults,exports.Segmenter=b.Segmenter,exports.SpeedTimer=n.SpeedTimer,exports.VERSION=x,exports.VisionTask=g.VisionTask,exports.batchedNms=m.batchedNms,exports.classificationNumClasses=a.classificationNumClasses,exports.declaredShapesFrom=a.declaredShapesFrom,exports.decodeYolo=m.decodeYolo,exports.decodeYoloAnchors=m.decodeYoloAnchors,exports.decodeYoloSeg=h.decodeYoloSeg,exports.defaultLabels=i.defaultLabels,exports.detectionNumClasses=a.detectionNumClasses,exports.fromCv2=d.fromCv2,exports.letterbox=d.letterbox,exports.letterboxToTensorData=f.letterboxToTensorData,exports.loadImage=l.loadImage,exports.modelNames=o.modelNames,exports.nms=m.nms,exports.normalize=d.normalize,exports.parseNames=o.parseNames,exports.readFusionSpec=u.readFusionSpec,exports.readModelMetadata=o.readModelMetadata,exports.requireDetections=g.requireDetections,exports.resize=d.resize,exports.resizeToTensorData=f.resizeToTensorData,exports.resolveInputSize=a.resolveInputSize,exports.resolveLabels=i.resolveLabels,exports.resolveProviders=s.resolveProviders,exports.softmax=p.softmax,exports.spatialInputSize=a.spatialInputSize,exports.toCHW=d.toCHW,exports.toCv2=d.toCv2,exports.toFloat32=d.toFloat32,exports.toFloat32Tensor=d.toFloat32Tensor,exports.toTensor=d.toTensor,exports.topK=p.topK,exports.writePlanarFloat32=f.writePlanarFloat32,exports.zeroTensorData=f.zeroTensorData;
1
+ const e=require("./core/exceptions.cjs"),t=require("./types.cjs"),n=require("./core/timing.cjs"),r=require("./results.cjs"),i=require("./labels.cjs"),a=require("./core/graph.cjs"),o=require("./core/metadata.cjs"),s=require("./core/providers.cjs"),c=require("./core/session.cjs"),l=require("./normalization.cjs"),u=require("./io/image.cjs"),d=require("./fusion.cjs"),f=require("./preprocess/image.cjs"),p=require("./preprocess/pipeline.cjs"),m=require("./postprocess/classification.cjs"),h=require("./postprocess/detection.cjs"),g=require("./postprocess/segmentation.cjs"),_=require("./tasks/base.cjs"),v=require("./tasks/classifier.cjs"),y=require("./tasks/detectClassify.cjs"),b=require("./tasks/detector.cjs"),x=require("./tasks/segmenter.cjs");var S=`0.8.1`;exports.BoundingBox=t.BoundingBox,exports.Boxes=r.Boxes,exports.COCO_CLASSES=i.COCO_CLASSES,exports.CUSTOM_NORMALIZATION=l.CUSTOM_NORMALIZATION,exports.ClassificationResults=r.ClassificationResults,exports.Classifier=v.Classifier,exports.DEFAULT_PROVIDERS=s.DEFAULT_PROVIDERS,exports.DetectClassify=y.DetectClassify,exports.DetectClassifyResults=r.DetectClassifyResults,exports.DetectionResults=r.DetectionResults,exports.Detector=b.Detector,exports.FUSION_KIND_DETECT_CLASSIFY=d.FUSION_KIND_DETECT_CLASSIFY,exports.FusionError=e.FusionError,exports.IDENTITY_MEAN=l.IDENTITY_MEAN,exports.IDENTITY_STD=l.IDENTITY_STD,exports.IMAGENET_MEAN=l.IMAGENET_MEAN,exports.IMAGENET_STD=l.IMAGENET_STD,exports.INPUT_IMAGE=d.INPUT_IMAGE,exports.INPUT_PAD=d.INPUT_PAD,exports.INPUT_SCALE=d.INPUT_SCALE,exports.INPUT_SOURCE=d.INPUT_SOURCE,exports.ImageLoadError=e.ImageLoadError,exports.InferenceError=e.InferenceError,exports.LabelMapError=e.LabelMapError,exports.LetterboxPipeline=p.LetterboxPipeline,exports.METADATA_PREFIX=d.METADATA_PREFIX,exports.Mask=t.Mask,exports.Masks=r.Masks,exports.ModelLoadError=e.ModelLoadError,exports.NoDetectionsError=e.NoDetectionsError,exports.OUTPUT_BOXES=d.OUTPUT_BOXES,exports.OUTPUT_CLASSES=d.OUTPUT_CLASSES,exports.OUTPUT_NUM_DETECTIONS=d.OUTPUT_NUM_DETECTIONS,exports.OUTPUT_PROBS=d.OUTPUT_PROBS,exports.OUTPUT_SCORES=d.OUTPUT_SCORES,exports.OrtSession=c.OrtSession,exports.OrtVisionError=e.OrtVisionError,exports.Probs=r.Probs,exports.ProviderNotAvailableError=e.ProviderNotAvailableError,exports.RGBImage=t.RGBImage,exports.ResizePipeline=p.ResizePipeline,exports.SegmentationResults=r.SegmentationResults,exports.Segmenter=x.Segmenter,exports.SpeedTimer=n.SpeedTimer,exports.VERSION=S,exports.VisionTask=_.VisionTask,exports.batchedNms=h.batchedNms,exports.classificationNumClasses=a.classificationNumClasses,exports.declaredShapesFrom=a.declaredShapesFrom,exports.decodeYolo=h.decodeYolo,exports.decodeYoloAnchors=h.decodeYoloAnchors,exports.decodeYoloSeg=g.decodeYoloSeg,exports.defaultLabels=i.defaultLabels,exports.detectProviders=s.detectProviders,exports.detectionNumClasses=a.detectionNumClasses,exports.fromCv2=f.fromCv2,exports.isUltralyticsClassifier=l.isUltralyticsClassifier,exports.letterbox=f.letterbox,exports.letterboxToTensorData=p.letterboxToTensorData,exports.loadImage=u.loadImage,exports.modelNames=o.modelNames,exports.nms=h.nms,exports.normalize=f.normalize,exports.parseNames=o.parseNames,exports.readFusionSpec=d.readFusionSpec,exports.readModelMetadata=o.readModelMetadata,exports.requireDetections=_.requireDetections,exports.resize=f.resize,exports.resizeToTensorData=p.resizeToTensorData,exports.resolveInputSize=a.resolveInputSize,exports.resolveLabels=i.resolveLabels,exports.resolveNormalization=l.resolveNormalization,exports.resolveProviders=s.resolveProviders,exports.softmax=m.softmax,exports.spatialInputSize=a.spatialInputSize,exports.toCHW=f.toCHW,exports.toCv2=f.toCv2,exports.toFloat32=f.toFloat32,exports.toFloat32Tensor=f.toFloat32Tensor,exports.toTensor=f.toTensor,exports.topK=m.topK,exports.writePlanarFloat32=p.writePlanarFloat32,exports.zeroTensorData=p.zeroTensorData;
2
2
  //# sourceMappingURL=index.cjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.cjs","names":[],"sources":["../../src/vision/index.ts"],"sourcesContent":["/**\n * `tempest-react-sdk/vision` — browser computer-vision inference with ONNX\n * Runtime Web (classification, detection, segmentation).\n *\n * Vendored from `@mauriciobenjamin700/ort-vision-sdk-web@0.7.1` (MIT, same\n * author) so it ships inside this SDK without an extra package install.\n * `onnxruntime-web` stays an optional peer dependency — install it (and ship\n * the matching `.wasm` files) only when you use this subpath.\n *\n * Do not hand-edit — regenerate with `npm run vendor:vision`.\n */\n\nexport {\n BoundingBox,\n Mask,\n RGBImage,\n type ClassProbability,\n type ClassificationResult,\n type DetectionResult,\n type SegmentationResult,\n} from \"./types\";\n\nexport {\n Boxes,\n ClassificationResults,\n DetectClassifyResults,\n DetectionResults,\n Masks,\n Probs,\n SegmentationResults,\n} from \"./results\";\n\nexport {\n COCO_CLASSES,\n type LabelSpec,\n type ResolveLabelsOptions,\n defaultLabels,\n resolveLabels,\n} from \"./labels\";\n\nexport {\n FusionError,\n ImageLoadError,\n InferenceError,\n LabelMapError,\n ModelLoadError,\n NoDetectionsError,\n OrtVisionError,\n ProviderNotAvailableError,\n} from \"./core/exceptions\";\n\nexport { type ModelSource, type OrtSessionOptions, OrtSession } from \"./core/session\";\nexport {\n type DeclaredDim,\n type DeclaredShape,\n type ResolveInputSizeOptions,\n classificationNumClasses,\n declaredShapesFrom,\n detectionNumClasses,\n resolveInputSize,\n spatialInputSize,\n} from \"./core/graph\";\nexport { modelNames, parseNames, readModelMetadata } from \"./core/metadata\";\nexport { DEFAULT_PROVIDERS, resolveProviders } from \"./core/providers\";\nexport { type Speed, SpeedTimer } from \"./core/timing\";\n\nexport { type ImageInput, loadImage } from \"./io/image\";\n\nexport {\n FUSION_KIND_DETECT_CLASSIFY,\n INPUT_IMAGE,\n INPUT_PAD,\n INPUT_SCALE,\n INPUT_SOURCE,\n METADATA_PREFIX,\n OUTPUT_BOXES,\n OUTPUT_CLASSES,\n OUTPUT_NUM_DETECTIONS,\n OUTPUT_PROBS,\n OUTPUT_SCORES,\n type CropSource,\n type FusionSpec,\n readFusionSpec,\n} from \"./fusion\";\n\nexport {\n type LetterboxResult,\n fromCv2,\n letterbox,\n normalize,\n resize,\n toCHW,\n toCv2,\n toFloat32,\n toFloat32Tensor,\n toTensor,\n} from \"./preprocess/image\";\n\nexport {\n type FusedLetterboxResult,\n type FusedResizeResult,\n LetterboxPipeline,\n ResizePipeline,\n letterboxToTensorData,\n resizeToTensorData,\n writePlanarFloat32,\n zeroTensorData,\n} from \"./preprocess/pipeline\";\n\nexport { type TopKResult, softmax, topK } from \"./postprocess/classification\";\n\nexport {\n type DecodeYoloAnchorsOptions,\n type DecodeYoloOptions,\n type DecodedAnchors,\n type DecodedDetection,\n batchedNms,\n decodeYolo,\n decodeYoloAnchors,\n nms,\n} from \"./postprocess/detection\";\n\nexport {\n type DecodeYoloSegOptions,\n type DecodedSegmentation,\n decodeYoloSeg,\n} from \"./postprocess/segmentation\";\n\nexport { VisionTask, requireDetections } from \"./tasks/base\";\nexport {\n type ClassifierOptions,\n type ClassifierPredictOptions,\n Classifier,\n} from \"./tasks/classifier\";\nexport {\n type DetectClassifyOptions,\n type DetectClassifyPredictOptions,\n DetectClassify,\n} from \"./tasks/detectClassify\";\nexport {\n type DetectorHead,\n type DetectorOptions,\n type DetectorPredictOptions,\n Detector,\n} from \"./tasks/detector\";\nexport {\n type SegmenterHead,\n type SegmenterOptions,\n type SegmenterPredictOptions,\n Segmenter,\n} from \"./tasks/segmenter\";\n\nexport const VERSION: string = \"0.7.1\";\n"],"mappings":"0sBAwJA,IAAa,EAAkB"}
1
+ {"version":3,"file":"index.cjs","names":[],"sources":["../../src/vision/index.ts"],"sourcesContent":["/**\n * `tempest-react-sdk/vision` — browser computer-vision inference with ONNX\n * Runtime Web (classification, detection, segmentation).\n *\n * Vendored from `@mauriciobenjamin700/ort-vision-sdk-web@0.8.1` (MIT, same\n * author) so it ships inside this SDK without an extra package install.\n * `onnxruntime-web` stays an optional peer dependency — install it (and ship\n * the matching `.wasm` files) only when you use this subpath.\n *\n * Do not hand-edit — regenerate with `npm run vendor:vision`.\n */\n\nexport {\n BoundingBox,\n Mask,\n RGBImage,\n type ClassProbability,\n type ClassificationResult,\n type DetectionResult,\n type SegmentationResult,\n} from \"./types\";\n\nexport {\n Boxes,\n ClassificationResults,\n DetectClassifyResults,\n DetectionResults,\n Masks,\n Probs,\n SegmentationResults,\n} from \"./results\";\n\nexport {\n COCO_CLASSES,\n type LabelSpec,\n type ResolveLabelsOptions,\n defaultLabels,\n resolveLabels,\n} from \"./labels\";\n\nexport {\n FusionError,\n ImageLoadError,\n InferenceError,\n LabelMapError,\n ModelLoadError,\n NoDetectionsError,\n OrtVisionError,\n ProviderNotAvailableError,\n} from \"./core/exceptions\";\n\nexport { type ModelSource, type OrtSessionOptions, OrtSession } from \"./core/session\";\nexport {\n type DeclaredDim,\n type DeclaredShape,\n type ResolveInputSizeOptions,\n classificationNumClasses,\n declaredShapesFrom,\n detectionNumClasses,\n resolveInputSize,\n spatialInputSize,\n} from \"./core/graph\";\nexport { modelNames, parseNames, readModelMetadata } from \"./core/metadata\";\nexport { DEFAULT_PROVIDERS, detectProviders, resolveProviders } from \"./core/providers\";\nexport { type Speed, SpeedTimer } from \"./core/timing\";\nexport {\n CUSTOM_NORMALIZATION,\n IDENTITY_MEAN,\n IDENTITY_STD,\n IMAGENET_MEAN,\n IMAGENET_STD,\n type Normalization,\n type ResolvedNormalization,\n isUltralyticsClassifier,\n resolveNormalization,\n} from \"./normalization\";\n\nexport { type ImageInput, loadImage } from \"./io/image\";\n\nexport {\n FUSION_KIND_DETECT_CLASSIFY,\n INPUT_IMAGE,\n INPUT_PAD,\n INPUT_SCALE,\n INPUT_SOURCE,\n METADATA_PREFIX,\n OUTPUT_BOXES,\n OUTPUT_CLASSES,\n OUTPUT_NUM_DETECTIONS,\n OUTPUT_PROBS,\n OUTPUT_SCORES,\n type CropSource,\n type FusionSpec,\n readFusionSpec,\n} from \"./fusion\";\n\nexport {\n type LetterboxResult,\n fromCv2,\n letterbox,\n normalize,\n resize,\n toCHW,\n toCv2,\n toFloat32,\n toFloat32Tensor,\n toTensor,\n} from \"./preprocess/image\";\n\nexport {\n type FusedLetterboxResult,\n type FusedResizeResult,\n LetterboxPipeline,\n ResizePipeline,\n letterboxToTensorData,\n resizeToTensorData,\n writePlanarFloat32,\n zeroTensorData,\n} from \"./preprocess/pipeline\";\n\nexport { type TopKResult, softmax, topK } from \"./postprocess/classification\";\n\nexport {\n type DecodeYoloAnchorsOptions,\n type DecodeYoloOptions,\n type DecodedAnchors,\n type DecodedDetection,\n batchedNms,\n decodeYolo,\n decodeYoloAnchors,\n nms,\n} from \"./postprocess/detection\";\n\nexport {\n type DecodeYoloSegOptions,\n type DecodedSegmentation,\n decodeYoloSeg,\n} from \"./postprocess/segmentation\";\n\nexport { VisionTask, requireDetections } from \"./tasks/base\";\nexport {\n type ClassifierOptions,\n type ClassifierPredictOptions,\n Classifier,\n} from \"./tasks/classifier\";\nexport {\n type DetectClassifyOptions,\n type DetectClassifyPredictOptions,\n DetectClassify,\n} from \"./tasks/detectClassify\";\nexport {\n type DetectorHead,\n type DetectorOptions,\n type DetectorPredictOptions,\n Detector,\n} from \"./tasks/detector\";\nexport {\n type SegmenterHead,\n type SegmenterOptions,\n type SegmenterPredictOptions,\n Segmenter,\n} from \"./tasks/segmenter\";\n\nexport const VERSION: string = \"0.8.1\";\n"],"mappings":"2uBAmKA,IAAa,EAAkB"}
@@ -5,23 +5,24 @@ import { Boxes as f, ClassificationResults as p, DetectClassifyResults as m, Det
5
5
  import { COCO_CLASSES as y, defaultLabels as b, resolveLabels as x } from "./labels.js";
6
6
  import { classificationNumClasses as S, declaredShapesFrom as C, detectionNumClasses as w, resolveInputSize as T, spatialInputSize as E } from "./core/graph.js";
7
7
  import { modelNames as D, parseNames as O, readModelMetadata as k } from "./core/metadata.js";
8
- import { DEFAULT_PROVIDERS as A, resolveProviders as j } from "./core/providers.js";
9
- import { OrtSession as M } from "./core/session.js";
10
- import { loadImage as N } from "./io/image.js";
11
- import { FUSION_KIND_DETECT_CLASSIFY as P, INPUT_IMAGE as F, INPUT_PAD as I, INPUT_SCALE as L, INPUT_SOURCE as R, METADATA_PREFIX as z, OUTPUT_BOXES as B, OUTPUT_CLASSES as V, OUTPUT_NUM_DETECTIONS as H, OUTPUT_PROBS as U, OUTPUT_SCORES as W, readFusionSpec as G } from "./fusion.js";
12
- import { fromCv2 as K, letterbox as q, normalize as J, resize as Y, toCHW as X, toCv2 as Z, toFloat32 as Q, toFloat32Tensor as $, toTensor as ee } from "./preprocess/image.js";
13
- import { LetterboxPipeline as te, ResizePipeline as ne, letterboxToTensorData as re, resizeToTensorData as ie, writePlanarFloat32 as ae, zeroTensorData as oe } from "./preprocess/pipeline.js";
14
- import { softmax as se, topK as ce } from "./postprocess/classification.js";
15
- import { batchedNms as le, decodeYolo as ue, decodeYoloAnchors as de, nms as fe } from "./postprocess/detection.js";
16
- import { decodeYoloSeg as pe } from "./postprocess/segmentation.js";
17
- import { VisionTask as me, requireDetections as he } from "./tasks/base.js";
18
- import { Classifier as ge } from "./tasks/classifier.js";
19
- import { DetectClassify as _e } from "./tasks/detectClassify.js";
20
- import { Detector as ve } from "./tasks/detector.js";
21
- import { Segmenter as ye } from "./tasks/segmenter.js";
8
+ import { DEFAULT_PROVIDERS as A, detectProviders as j, resolveProviders as M } from "./core/providers.js";
9
+ import { OrtSession as N } from "./core/session.js";
10
+ import { CUSTOM_NORMALIZATION as P, IDENTITY_MEAN as F, IDENTITY_STD as I, IMAGENET_MEAN as L, IMAGENET_STD as R, isUltralyticsClassifier as z, resolveNormalization as B } from "./normalization.js";
11
+ import { loadImage as V } from "./io/image.js";
12
+ import { FUSION_KIND_DETECT_CLASSIFY as H, INPUT_IMAGE as U, INPUT_PAD as W, INPUT_SCALE as G, INPUT_SOURCE as K, METADATA_PREFIX as q, OUTPUT_BOXES as J, OUTPUT_CLASSES as Y, OUTPUT_NUM_DETECTIONS as X, OUTPUT_PROBS as Z, OUTPUT_SCORES as Q, readFusionSpec as $ } from "./fusion.js";
13
+ import { fromCv2 as ee, letterbox as te, normalize as ne, resize as re, toCHW as ie, toCv2 as ae, toFloat32 as oe, toFloat32Tensor as se, toTensor as ce } from "./preprocess/image.js";
14
+ import { LetterboxPipeline as le, ResizePipeline as ue, letterboxToTensorData as de, resizeToTensorData as fe, writePlanarFloat32 as pe, zeroTensorData as me } from "./preprocess/pipeline.js";
15
+ import { softmax as he, topK as ge } from "./postprocess/classification.js";
16
+ import { batchedNms as _e, decodeYolo as ve, decodeYoloAnchors as ye, nms as be } from "./postprocess/detection.js";
17
+ import { decodeYoloSeg as xe } from "./postprocess/segmentation.js";
18
+ import { VisionTask as Se, requireDetections as Ce } from "./tasks/base.js";
19
+ import { Classifier as we } from "./tasks/classifier.js";
20
+ import { DetectClassify as Te } from "./tasks/detectClassify.js";
21
+ import { Detector as Ee } from "./tasks/detector.js";
22
+ import { Segmenter as De } from "./tasks/segmenter.js";
22
23
  //#region src/vision/index.ts
23
- var be = "0.7.1";
24
+ var Oe = "0.8.1";
24
25
  //#endregion
25
- export { c as BoundingBox, f as Boxes, y as COCO_CLASSES, p as ClassificationResults, ge as Classifier, A as DEFAULT_PROVIDERS, _e as DetectClassify, m as DetectClassifyResults, h as DetectionResults, ve as Detector, P as FUSION_KIND_DETECT_CLASSIFY, e as FusionError, F as INPUT_IMAGE, I as INPUT_PAD, L as INPUT_SCALE, R as INPUT_SOURCE, t as ImageLoadError, n as InferenceError, r as LabelMapError, te as LetterboxPipeline, z as METADATA_PREFIX, l as Mask, g as Masks, i as ModelLoadError, a as NoDetectionsError, B as OUTPUT_BOXES, V as OUTPUT_CLASSES, H as OUTPUT_NUM_DETECTIONS, U as OUTPUT_PROBS, W as OUTPUT_SCORES, M as OrtSession, o as OrtVisionError, _ as Probs, s as ProviderNotAvailableError, u as RGBImage, ne as ResizePipeline, v as SegmentationResults, ye as Segmenter, d as SpeedTimer, be as VERSION, me as VisionTask, le as batchedNms, S as classificationNumClasses, C as declaredShapesFrom, ue as decodeYolo, de as decodeYoloAnchors, pe as decodeYoloSeg, b as defaultLabels, w as detectionNumClasses, K as fromCv2, q as letterbox, re as letterboxToTensorData, N as loadImage, D as modelNames, fe as nms, J as normalize, O as parseNames, G as readFusionSpec, k as readModelMetadata, he as requireDetections, Y as resize, ie as resizeToTensorData, T as resolveInputSize, x as resolveLabels, j as resolveProviders, se as softmax, E as spatialInputSize, X as toCHW, Z as toCv2, Q as toFloat32, $ as toFloat32Tensor, ee as toTensor, ce as topK, ae as writePlanarFloat32, oe as zeroTensorData };
26
+ export { c as BoundingBox, f as Boxes, y as COCO_CLASSES, P as CUSTOM_NORMALIZATION, p as ClassificationResults, we as Classifier, A as DEFAULT_PROVIDERS, Te as DetectClassify, m as DetectClassifyResults, h as DetectionResults, Ee as Detector, H as FUSION_KIND_DETECT_CLASSIFY, e as FusionError, F as IDENTITY_MEAN, I as IDENTITY_STD, L as IMAGENET_MEAN, R as IMAGENET_STD, U as INPUT_IMAGE, W as INPUT_PAD, G as INPUT_SCALE, K as INPUT_SOURCE, t as ImageLoadError, n as InferenceError, r as LabelMapError, le as LetterboxPipeline, q as METADATA_PREFIX, l as Mask, g as Masks, i as ModelLoadError, a as NoDetectionsError, J as OUTPUT_BOXES, Y as OUTPUT_CLASSES, X as OUTPUT_NUM_DETECTIONS, Z as OUTPUT_PROBS, Q as OUTPUT_SCORES, N as OrtSession, o as OrtVisionError, _ as Probs, s as ProviderNotAvailableError, u as RGBImage, ue as ResizePipeline, v as SegmentationResults, De as Segmenter, d as SpeedTimer, Oe as VERSION, Se as VisionTask, _e as batchedNms, S as classificationNumClasses, C as declaredShapesFrom, ve as decodeYolo, ye as decodeYoloAnchors, xe as decodeYoloSeg, b as defaultLabels, j as detectProviders, w as detectionNumClasses, ee as fromCv2, z as isUltralyticsClassifier, te as letterbox, de as letterboxToTensorData, V as loadImage, D as modelNames, be as nms, ne as normalize, O as parseNames, $ as readFusionSpec, k as readModelMetadata, Ce as requireDetections, re as resize, fe as resizeToTensorData, T as resolveInputSize, x as resolveLabels, B as resolveNormalization, M as resolveProviders, he as softmax, E as spatialInputSize, ie as toCHW, ae as toCv2, oe as toFloat32, se as toFloat32Tensor, ce as toTensor, ge as topK, pe as writePlanarFloat32, me as zeroTensorData };
26
27
 
27
28
  //# sourceMappingURL=index.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":[],"sources":["../../src/vision/index.ts"],"sourcesContent":["/**\n * `tempest-react-sdk/vision` — browser computer-vision inference with ONNX\n * Runtime Web (classification, detection, segmentation).\n *\n * Vendored from `@mauriciobenjamin700/ort-vision-sdk-web@0.7.1` (MIT, same\n * author) so it ships inside this SDK without an extra package install.\n * `onnxruntime-web` stays an optional peer dependency — install it (and ship\n * the matching `.wasm` files) only when you use this subpath.\n *\n * Do not hand-edit — regenerate with `npm run vendor:vision`.\n */\n\nexport {\n BoundingBox,\n Mask,\n RGBImage,\n type ClassProbability,\n type ClassificationResult,\n type DetectionResult,\n type SegmentationResult,\n} from \"./types\";\n\nexport {\n Boxes,\n ClassificationResults,\n DetectClassifyResults,\n DetectionResults,\n Masks,\n Probs,\n SegmentationResults,\n} from \"./results\";\n\nexport {\n COCO_CLASSES,\n type LabelSpec,\n type ResolveLabelsOptions,\n defaultLabels,\n resolveLabels,\n} from \"./labels\";\n\nexport {\n FusionError,\n ImageLoadError,\n InferenceError,\n LabelMapError,\n ModelLoadError,\n NoDetectionsError,\n OrtVisionError,\n ProviderNotAvailableError,\n} from \"./core/exceptions\";\n\nexport { type ModelSource, type OrtSessionOptions, OrtSession } from \"./core/session\";\nexport {\n type DeclaredDim,\n type DeclaredShape,\n type ResolveInputSizeOptions,\n classificationNumClasses,\n declaredShapesFrom,\n detectionNumClasses,\n resolveInputSize,\n spatialInputSize,\n} from \"./core/graph\";\nexport { modelNames, parseNames, readModelMetadata } from \"./core/metadata\";\nexport { DEFAULT_PROVIDERS, resolveProviders } from \"./core/providers\";\nexport { type Speed, SpeedTimer } from \"./core/timing\";\n\nexport { type ImageInput, loadImage } from \"./io/image\";\n\nexport {\n FUSION_KIND_DETECT_CLASSIFY,\n INPUT_IMAGE,\n INPUT_PAD,\n INPUT_SCALE,\n INPUT_SOURCE,\n METADATA_PREFIX,\n OUTPUT_BOXES,\n OUTPUT_CLASSES,\n OUTPUT_NUM_DETECTIONS,\n OUTPUT_PROBS,\n OUTPUT_SCORES,\n type CropSource,\n type FusionSpec,\n readFusionSpec,\n} from \"./fusion\";\n\nexport {\n type LetterboxResult,\n fromCv2,\n letterbox,\n normalize,\n resize,\n toCHW,\n toCv2,\n toFloat32,\n toFloat32Tensor,\n toTensor,\n} from \"./preprocess/image\";\n\nexport {\n type FusedLetterboxResult,\n type FusedResizeResult,\n LetterboxPipeline,\n ResizePipeline,\n letterboxToTensorData,\n resizeToTensorData,\n writePlanarFloat32,\n zeroTensorData,\n} from \"./preprocess/pipeline\";\n\nexport { type TopKResult, softmax, topK } from \"./postprocess/classification\";\n\nexport {\n type DecodeYoloAnchorsOptions,\n type DecodeYoloOptions,\n type DecodedAnchors,\n type DecodedDetection,\n batchedNms,\n decodeYolo,\n decodeYoloAnchors,\n nms,\n} from \"./postprocess/detection\";\n\nexport {\n type DecodeYoloSegOptions,\n type DecodedSegmentation,\n decodeYoloSeg,\n} from \"./postprocess/segmentation\";\n\nexport { VisionTask, requireDetections } from \"./tasks/base\";\nexport {\n type ClassifierOptions,\n type ClassifierPredictOptions,\n Classifier,\n} from \"./tasks/classifier\";\nexport {\n type DetectClassifyOptions,\n type DetectClassifyPredictOptions,\n DetectClassify,\n} from \"./tasks/detectClassify\";\nexport {\n type DetectorHead,\n type DetectorOptions,\n type DetectorPredictOptions,\n Detector,\n} from \"./tasks/detector\";\nexport {\n type SegmenterHead,\n type SegmenterOptions,\n type SegmenterPredictOptions,\n Segmenter,\n} from \"./tasks/segmenter\";\n\nexport const VERSION: string = \"0.7.1\";\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;AAwJA,IAAa,KAAkB"}
1
+ {"version":3,"file":"index.js","names":[],"sources":["../../src/vision/index.ts"],"sourcesContent":["/**\n * `tempest-react-sdk/vision` — browser computer-vision inference with ONNX\n * Runtime Web (classification, detection, segmentation).\n *\n * Vendored from `@mauriciobenjamin700/ort-vision-sdk-web@0.8.1` (MIT, same\n * author) so it ships inside this SDK without an extra package install.\n * `onnxruntime-web` stays an optional peer dependency — install it (and ship\n * the matching `.wasm` files) only when you use this subpath.\n *\n * Do not hand-edit — regenerate with `npm run vendor:vision`.\n */\n\nexport {\n BoundingBox,\n Mask,\n RGBImage,\n type ClassProbability,\n type ClassificationResult,\n type DetectionResult,\n type SegmentationResult,\n} from \"./types\";\n\nexport {\n Boxes,\n ClassificationResults,\n DetectClassifyResults,\n DetectionResults,\n Masks,\n Probs,\n SegmentationResults,\n} from \"./results\";\n\nexport {\n COCO_CLASSES,\n type LabelSpec,\n type ResolveLabelsOptions,\n defaultLabels,\n resolveLabels,\n} from \"./labels\";\n\nexport {\n FusionError,\n ImageLoadError,\n InferenceError,\n LabelMapError,\n ModelLoadError,\n NoDetectionsError,\n OrtVisionError,\n ProviderNotAvailableError,\n} from \"./core/exceptions\";\n\nexport { type ModelSource, type OrtSessionOptions, OrtSession } from \"./core/session\";\nexport {\n type DeclaredDim,\n type DeclaredShape,\n type ResolveInputSizeOptions,\n classificationNumClasses,\n declaredShapesFrom,\n detectionNumClasses,\n resolveInputSize,\n spatialInputSize,\n} from \"./core/graph\";\nexport { modelNames, parseNames, readModelMetadata } from \"./core/metadata\";\nexport { DEFAULT_PROVIDERS, detectProviders, resolveProviders } from \"./core/providers\";\nexport { type Speed, SpeedTimer } from \"./core/timing\";\nexport {\n CUSTOM_NORMALIZATION,\n IDENTITY_MEAN,\n IDENTITY_STD,\n IMAGENET_MEAN,\n IMAGENET_STD,\n type Normalization,\n type ResolvedNormalization,\n isUltralyticsClassifier,\n resolveNormalization,\n} from \"./normalization\";\n\nexport { type ImageInput, loadImage } from \"./io/image\";\n\nexport {\n FUSION_KIND_DETECT_CLASSIFY,\n INPUT_IMAGE,\n INPUT_PAD,\n INPUT_SCALE,\n INPUT_SOURCE,\n METADATA_PREFIX,\n OUTPUT_BOXES,\n OUTPUT_CLASSES,\n OUTPUT_NUM_DETECTIONS,\n OUTPUT_PROBS,\n OUTPUT_SCORES,\n type CropSource,\n type FusionSpec,\n readFusionSpec,\n} from \"./fusion\";\n\nexport {\n type LetterboxResult,\n fromCv2,\n letterbox,\n normalize,\n resize,\n toCHW,\n toCv2,\n toFloat32,\n toFloat32Tensor,\n toTensor,\n} from \"./preprocess/image\";\n\nexport {\n type FusedLetterboxResult,\n type FusedResizeResult,\n LetterboxPipeline,\n ResizePipeline,\n letterboxToTensorData,\n resizeToTensorData,\n writePlanarFloat32,\n zeroTensorData,\n} from \"./preprocess/pipeline\";\n\nexport { type TopKResult, softmax, topK } from \"./postprocess/classification\";\n\nexport {\n type DecodeYoloAnchorsOptions,\n type DecodeYoloOptions,\n type DecodedAnchors,\n type DecodedDetection,\n batchedNms,\n decodeYolo,\n decodeYoloAnchors,\n nms,\n} from \"./postprocess/detection\";\n\nexport {\n type DecodeYoloSegOptions,\n type DecodedSegmentation,\n decodeYoloSeg,\n} from \"./postprocess/segmentation\";\n\nexport { VisionTask, requireDetections } from \"./tasks/base\";\nexport {\n type ClassifierOptions,\n type ClassifierPredictOptions,\n Classifier,\n} from \"./tasks/classifier\";\nexport {\n type DetectClassifyOptions,\n type DetectClassifyPredictOptions,\n DetectClassify,\n} from \"./tasks/detectClassify\";\nexport {\n type DetectorHead,\n type DetectorOptions,\n type DetectorPredictOptions,\n Detector,\n} from \"./tasks/detector\";\nexport {\n type SegmenterHead,\n type SegmenterOptions,\n type SegmenterPredictOptions,\n Segmenter,\n} from \"./tasks/segmenter\";\n\nexport const VERSION: string = \"0.8.1\";\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AAmKA,IAAa,KAAkB"}
@@ -0,0 +1,2 @@
1
+ var e=[.485,.456,.406],t=[.229,.224,.225],n=[0,0,0],r=[1,1,1],i=`custom`,a={imagenet:[e,t],ultralytics:[n,r],none:[n,r]};function o(e){return(e.author??``).trim().toLowerCase()===`ultralytics`&&(e.task??``).trim().toLowerCase()===`classify`}function s(e,t={}){let s=t.normalization??`auto`,l=t.mean!==void 0||t.std!==void 0;if(s!==`auto`&&a[s]===void 0)throw RangeError(`normalization must be one of 'auto', 'imagenet', 'ultralytics', 'none'; got ${JSON.stringify(s)}.`);if(l&&s!==`auto`)throw RangeError(`Pass either normalization=${JSON.stringify(s)} or explicit mean/std, not both.`);let u=o(e),d=s===`auto`?u?`ultralytics`:`imagenet`:s,[f,p]=a[d];if(!l)return{name:d,mean:f,std:p};let m=t.mean??f,h=t.std??p;return u&&!(c(m,n)&&c(h,r))&&console.warn(`The classifier is an Ultralytics export, whose classification head is trained on raw [0, 1] images, but mean=${JSON.stringify(m)} / std=${JSON.stringify(h)} was requested. It will be fed images normalized in a way it never saw in training, which degrades accuracy without raising anything. Drop mean/std to let normalization='auto' pick the identity.`),{name:i,mean:m,std:h}}function c(e,t){return e.every((e,n)=>e===t[n])}exports.CUSTOM_NORMALIZATION=i,exports.IDENTITY_MEAN=n,exports.IDENTITY_STD=r,exports.IMAGENET_MEAN=e,exports.IMAGENET_STD=t,exports.isUltralyticsClassifier=o,exports.resolveNormalization=s;
2
+ //# sourceMappingURL=normalization.cjs.map