tempest-react-sdk 0.34.0 → 0.36.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 (259) hide show
  1. package/README.md +72 -68
  2. package/dist/audio/audio-output.cjs +2 -0
  3. package/dist/audio/audio-output.cjs.map +1 -0
  4. package/dist/audio/audio-output.js +17 -0
  5. package/dist/audio/audio-output.js.map +1 -0
  6. package/dist/audio/audio-player.cjs +1 -1
  7. package/dist/audio/audio-player.cjs.map +1 -1
  8. package/dist/audio/audio-player.js +21 -20
  9. package/dist/audio/audio-player.js.map +1 -1
  10. package/dist/audio/audio-recorder.cjs +2 -0
  11. package/dist/audio/audio-recorder.cjs.map +1 -0
  12. package/dist/audio/audio-recorder.js +30 -0
  13. package/dist/audio/audio-recorder.js.map +1 -0
  14. package/dist/audio/duration.cjs +2 -0
  15. package/dist/audio/duration.cjs.map +1 -0
  16. package/dist/audio/duration.js +10 -0
  17. package/dist/audio/duration.js.map +1 -0
  18. package/dist/audio/level-meter.cjs +2 -0
  19. package/dist/audio/level-meter.cjs.map +1 -0
  20. package/dist/audio/level-meter.js +34 -0
  21. package/dist/audio/level-meter.js.map +1 -0
  22. package/dist/audio/media-access.cjs +2 -0
  23. package/dist/audio/media-access.cjs.map +1 -0
  24. package/dist/audio/media-access.js +51 -0
  25. package/dist/audio/media-access.js.map +1 -0
  26. package/dist/audio/use-audio-recorder.cjs +2 -0
  27. package/dist/audio/use-audio-recorder.cjs.map +1 -0
  28. package/dist/audio/use-audio-recorder.js +94 -0
  29. package/dist/audio/use-audio-recorder.js.map +1 -0
  30. package/dist/audio/use-audio.cjs.map +1 -1
  31. package/dist/audio/use-audio.js.map +1 -1
  32. package/dist/audio/use-microphone.cjs +2 -0
  33. package/dist/audio/use-microphone.cjs.map +1 -0
  34. package/dist/audio/use-microphone.js +54 -0
  35. package/dist/audio/use-microphone.js.map +1 -0
  36. package/dist/audio/wav.cjs +2 -0
  37. package/dist/audio/wav.cjs.map +1 -0
  38. package/dist/audio/wav.js +49 -0
  39. package/dist/audio/wav.js.map +1 -0
  40. package/dist/auth/passkey.cjs +2 -0
  41. package/dist/auth/passkey.cjs.map +1 -0
  42. package/dist/auth/passkey.js +171 -0
  43. package/dist/auth/passkey.js.map +1 -0
  44. package/dist/auth/use-passkey.cjs +2 -0
  45. package/dist/auth/use-passkey.cjs.map +1 -0
  46. package/dist/auth/use-passkey.js +120 -0
  47. package/dist/auth/use-passkey.js.map +1 -0
  48. package/dist/br/PixQRCode.cjs +2 -0
  49. package/dist/br/PixQRCode.cjs.map +1 -0
  50. package/dist/br/PixQRCode.js +70 -0
  51. package/dist/br/PixQRCode.js.map +1 -0
  52. package/dist/br/PixQRCode.module.cjs +2 -0
  53. package/dist/br/PixQRCode.module.cjs.map +1 -0
  54. package/dist/br/PixQRCode.module.js +15 -0
  55. package/dist/br/PixQRCode.module.js.map +1 -0
  56. package/dist/br/boleto.cjs +2 -0
  57. package/dist/br/boleto.cjs.map +1 -0
  58. package/dist/br/boleto.js +225 -0
  59. package/dist/br/boleto.js.map +1 -0
  60. package/dist/br/holidays.cjs +2 -0
  61. package/dist/br/holidays.cjs.map +1 -0
  62. package/dist/br/holidays.js +148 -0
  63. package/dist/br/holidays.js.map +1 -0
  64. package/dist/br/nfe.cjs +2 -0
  65. package/dist/br/nfe.cjs.map +1 -0
  66. package/dist/br/nfe.js +104 -0
  67. package/dist/br/nfe.js.map +1 -0
  68. package/dist/br/pix.cjs +2 -0
  69. package/dist/br/pix.cjs.map +1 -0
  70. package/dist/br/pix.js +148 -0
  71. package/dist/br/pix.js.map +1 -0
  72. package/dist/br.cjs +1 -1
  73. package/dist/br.cjs.map +1 -1
  74. package/dist/br.d.ts +878 -0
  75. package/dist/br.js +7 -2
  76. package/dist/br.js.map +1 -1
  77. package/dist/capture/barcode.cjs +2 -0
  78. package/dist/capture/barcode.cjs.map +1 -0
  79. package/dist/capture/barcode.js +59 -0
  80. package/dist/capture/barcode.js.map +1 -0
  81. package/dist/capture/media-recorder.cjs +2 -0
  82. package/dist/capture/media-recorder.cjs.map +1 -0
  83. package/dist/capture/media-recorder.js +64 -0
  84. package/dist/capture/media-recorder.js.map +1 -0
  85. package/dist/capture/use-barcode-scanner.cjs +2 -0
  86. package/dist/capture/use-barcode-scanner.cjs.map +1 -0
  87. package/dist/capture/use-barcode-scanner.js +86 -0
  88. package/dist/capture/use-barcode-scanner.js.map +1 -0
  89. package/dist/capture/use-screen-capture.cjs +2 -0
  90. package/dist/capture/use-screen-capture.cjs.map +1 -0
  91. package/dist/capture/use-screen-capture.js +79 -0
  92. package/dist/capture/use-screen-capture.js.map +1 -0
  93. package/dist/capture/use-speech-recognition.cjs +2 -0
  94. package/dist/capture/use-speech-recognition.cjs.map +1 -0
  95. package/dist/capture/use-speech-recognition.js +118 -0
  96. package/dist/capture/use-speech-recognition.js.map +1 -0
  97. package/dist/capture/use-torch.cjs +2 -0
  98. package/dist/capture/use-torch.cjs.map +1 -0
  99. package/dist/capture/use-torch.js +33 -0
  100. package/dist/capture/use-torch.js.map +1 -0
  101. package/dist/capture/use-video-recorder.cjs +2 -0
  102. package/dist/capture/use-video-recorder.cjs.map +1 -0
  103. package/dist/capture/use-video-recorder.js +90 -0
  104. package/dist/capture/use-video-recorder.js.map +1 -0
  105. package/dist/capture/video-recorder.cjs +2 -0
  106. package/dist/capture/video-recorder.cjs.map +1 -0
  107. package/dist/capture/video-recorder.js +31 -0
  108. package/dist/capture/video-recorder.js.map +1 -0
  109. package/dist/components/AIChat/AIChat.cjs +1 -1
  110. package/dist/components/AIChat/AIChat.cjs.map +1 -1
  111. package/dist/components/AIChat/AIChat.js +93 -97
  112. package/dist/components/AIChat/AIChat.js.map +1 -1
  113. package/dist/components/AIChat/AIChatComposer.cjs +1 -1
  114. package/dist/components/AIChat/AIChatComposer.cjs.map +1 -1
  115. package/dist/components/AIChat/AIChatComposer.js +2 -1
  116. package/dist/components/AIChat/AIChatComposer.js.map +1 -1
  117. package/dist/components/AIChat/AIChatTurn.cjs +2 -2
  118. package/dist/components/AIChat/AIChatTurn.js +6 -6
  119. package/dist/components/AIChat/AIChatTurn.js.map +1 -1
  120. package/dist/components/Alert/Alert.module.cjs.map +1 -1
  121. package/dist/components/Alert/Alert.module.js.map +1 -1
  122. package/dist/components/AudioPlayer/AudioPlayer.cjs +2 -0
  123. package/dist/components/AudioPlayer/AudioPlayer.cjs.map +1 -0
  124. package/dist/components/AudioPlayer/AudioPlayer.js +123 -0
  125. package/dist/components/AudioPlayer/AudioPlayer.js.map +1 -0
  126. package/dist/components/AudioPlayer/AudioPlayer.module.cjs +2 -0
  127. package/dist/components/AudioPlayer/AudioPlayer.module.cjs.map +1 -0
  128. package/dist/components/AudioPlayer/AudioPlayer.module.js +12 -0
  129. package/dist/components/AudioPlayer/AudioPlayer.module.js.map +1 -0
  130. package/dist/components/AudioRecorder/AudioRecorder.cjs +2 -0
  131. package/dist/components/AudioRecorder/AudioRecorder.cjs.map +1 -0
  132. package/dist/components/AudioRecorder/AudioRecorder.js +179 -0
  133. package/dist/components/AudioRecorder/AudioRecorder.js.map +1 -0
  134. package/dist/components/AudioRecorder/AudioRecorder.module.cjs +2 -0
  135. package/dist/components/AudioRecorder/AudioRecorder.module.cjs.map +1 -0
  136. package/dist/components/AudioRecorder/AudioRecorder.module.js +19 -0
  137. package/dist/components/AudioRecorder/AudioRecorder.module.js.map +1 -0
  138. package/dist/components/Badge/Badge.module.cjs.map +1 -1
  139. package/dist/components/Badge/Badge.module.js.map +1 -1
  140. package/dist/components/BarcodeScanner/BarcodeScanner.cjs +2 -0
  141. package/dist/components/BarcodeScanner/BarcodeScanner.cjs.map +1 -0
  142. package/dist/components/BarcodeScanner/BarcodeScanner.js +123 -0
  143. package/dist/components/BarcodeScanner/BarcodeScanner.js.map +1 -0
  144. package/dist/components/BarcodeScanner/BarcodeScanner.module.cjs +2 -0
  145. package/dist/components/BarcodeScanner/BarcodeScanner.module.cjs.map +1 -0
  146. package/dist/components/BarcodeScanner/BarcodeScanner.module.js +22 -0
  147. package/dist/components/BarcodeScanner/BarcodeScanner.module.js.map +1 -0
  148. package/dist/components/BottomNavigation/BottomNavigation.module.cjs.map +1 -1
  149. package/dist/components/BottomNavigation/BottomNavigation.module.js.map +1 -1
  150. package/dist/components/Button/Button.module.cjs.map +1 -1
  151. package/dist/components/Button/Button.module.js.map +1 -1
  152. package/dist/components/Combobox/Combobox.module.cjs.map +1 -1
  153. package/dist/components/Combobox/Combobox.module.js.map +1 -1
  154. package/dist/components/DataTable/DataTable.cjs +1 -1
  155. package/dist/components/DataTable/DataTable.cjs.map +1 -1
  156. package/dist/components/DataTable/DataTable.js +203 -66
  157. package/dist/components/DataTable/DataTable.js.map +1 -1
  158. package/dist/components/DataTable/DataTable.module.cjs +1 -1
  159. package/dist/components/DataTable/DataTable.module.cjs.map +1 -1
  160. package/dist/components/DataTable/DataTable.module.js +9 -3
  161. package/dist/components/DataTable/DataTable.module.js.map +1 -1
  162. package/dist/components/DataTable/EditableCell.cjs +2 -0
  163. package/dist/components/DataTable/EditableCell.cjs.map +1 -0
  164. package/dist/components/DataTable/EditableCell.js +77 -0
  165. package/dist/components/DataTable/EditableCell.js.map +1 -0
  166. package/dist/components/DataTable/edit-labels.cjs +2 -0
  167. package/dist/components/DataTable/edit-labels.cjs.map +1 -0
  168. package/dist/components/DataTable/edit-labels.js +11 -0
  169. package/dist/components/DataTable/edit-labels.js.map +1 -0
  170. package/dist/components/DateRangePicker/DateRangePicker.module.cjs.map +1 -1
  171. package/dist/components/DateRangePicker/DateRangePicker.module.js.map +1 -1
  172. package/dist/components/MultiSelect/MultiSelect.module.cjs.map +1 -1
  173. package/dist/components/MultiSelect/MultiSelect.module.js.map +1 -1
  174. package/dist/components/NavigationRail/NavigationRail.module.cjs.map +1 -1
  175. package/dist/components/NavigationRail/NavigationRail.module.js.map +1 -1
  176. package/dist/components/SyncStatusBadge/SyncStatusBadge.cjs +1 -1
  177. package/dist/components/SyncStatusBadge/SyncStatusBadge.cjs.map +1 -1
  178. package/dist/components/SyncStatusBadge/SyncStatusBadge.js +33 -32
  179. package/dist/components/SyncStatusBadge/SyncStatusBadge.js.map +1 -1
  180. package/dist/components/Toast/ToastProvider.cjs +1 -1
  181. package/dist/components/Toast/ToastProvider.cjs.map +1 -1
  182. package/dist/components/Toast/ToastProvider.js +1 -2
  183. package/dist/components/Toast/ToastProvider.js.map +1 -1
  184. package/dist/hooks/use-announce.cjs +2 -0
  185. package/dist/hooks/use-announce.cjs.map +1 -0
  186. package/dist/hooks/use-announce.js +50 -0
  187. package/dist/hooks/use-announce.js.map +1 -0
  188. package/dist/hooks/use-media-devices.cjs +2 -0
  189. package/dist/hooks/use-media-devices.cjs.map +1 -0
  190. package/dist/hooks/use-media-devices.js +46 -0
  191. package/dist/hooks/use-media-devices.js.map +1 -0
  192. package/dist/hooks/use-media-permission.cjs +2 -0
  193. package/dist/hooks/use-media-permission.cjs.map +1 -0
  194. package/dist/hooks/use-media-permission.js +33 -0
  195. package/dist/hooks/use-media-permission.js.map +1 -0
  196. package/dist/http/resumable-upload.cjs +2 -0
  197. package/dist/http/resumable-upload.cjs.map +1 -0
  198. package/dist/http/resumable-upload.js +249 -0
  199. package/dist/http/resumable-upload.js.map +1 -0
  200. package/dist/perf/cache-size.cjs +2 -0
  201. package/dist/perf/cache-size.cjs.map +1 -0
  202. package/dist/perf/cache-size.js +16 -0
  203. package/dist/perf/cache-size.js.map +1 -0
  204. package/dist/perf/device.cjs +2 -0
  205. package/dist/perf/device.cjs.map +1 -0
  206. package/dist/perf/device.js +22 -0
  207. package/dist/perf/device.js.map +1 -0
  208. package/dist/perf/format.cjs +2 -0
  209. package/dist/perf/format.cjs.map +1 -0
  210. package/dist/perf/format.js +8 -0
  211. package/dist/perf/format.js.map +1 -0
  212. package/dist/perf/profiler.cjs +2 -0
  213. package/dist/perf/profiler.cjs.map +1 -0
  214. package/dist/perf/profiler.js +46 -0
  215. package/dist/perf/profiler.js.map +1 -0
  216. package/dist/styles.css +1 -1
  217. package/dist/tempest-react-sdk.cjs +1 -1
  218. package/dist/tempest-react-sdk.d.ts +2705 -38
  219. package/dist/tempest-react-sdk.js +268 -240
  220. package/dist/vision/core/timing.cjs +2 -0
  221. package/dist/vision/core/timing.cjs.map +1 -0
  222. package/dist/vision/core/timing.js +24 -0
  223. package/dist/vision/core/timing.js.map +1 -0
  224. package/dist/vision/index.cjs +1 -1
  225. package/dist/vision/index.cjs.map +1 -1
  226. package/dist/vision/index.js +16 -15
  227. package/dist/vision/index.js.map +1 -1
  228. package/dist/vision/postprocess/detection.cjs +1 -1
  229. package/dist/vision/postprocess/detection.cjs.map +1 -1
  230. package/dist/vision/postprocess/detection.js +2 -2
  231. package/dist/vision/postprocess/detection.js.map +1 -1
  232. package/dist/vision/postprocess/segmentation.cjs +1 -1
  233. package/dist/vision/postprocess/segmentation.cjs.map +1 -1
  234. package/dist/vision/postprocess/segmentation.js +1 -1
  235. package/dist/vision/postprocess/segmentation.js.map +1 -1
  236. package/dist/vision/results.cjs +1 -1
  237. package/dist/vision/results.cjs.map +1 -1
  238. package/dist/vision/results.js +18 -13
  239. package/dist/vision/results.js.map +1 -1
  240. package/dist/vision/tasks/classifier.cjs +1 -1
  241. package/dist/vision/tasks/classifier.cjs.map +1 -1
  242. package/dist/vision/tasks/classifier.js +46 -39
  243. package/dist/vision/tasks/classifier.js.map +1 -1
  244. package/dist/vision/tasks/detector.cjs +1 -1
  245. package/dist/vision/tasks/detector.cjs.map +1 -1
  246. package/dist/vision/tasks/detector.js +40 -33
  247. package/dist/vision/tasks/detector.js.map +1 -1
  248. package/dist/vision/tasks/segmenter.cjs +1 -1
  249. package/dist/vision/tasks/segmenter.cjs.map +1 -1
  250. package/dist/vision/tasks/segmenter.js +35 -28
  251. package/dist/vision/tasks/segmenter.js.map +1 -1
  252. package/dist/vision/use-camera-stream.cjs +1 -1
  253. package/dist/vision/use-camera-stream.cjs.map +1 -1
  254. package/dist/vision/use-camera-stream.js +40 -57
  255. package/dist/vision/use-camera-stream.js.map +1 -1
  256. package/dist/vision.cjs +1 -1
  257. package/dist/vision.d.ts +93 -13
  258. package/dist/vision.js +21 -20
  259. package/package.json +1 -1
@@ -0,0 +1 @@
1
+ {"version":3,"file":"resumable-upload.js","names":[],"sources":["../../src/http/resumable-upload.ts"],"sourcesContent":["import { buildApiError, TempestApiError } from \"./errors\";\nimport { generateIdempotencyKey } from \"./idempotency\";\nimport { retry, type RetryOptions } from \"./retry\";\n\n/** The tus protocol version this client speaks. */\nexport const TUS_VERSION = \"1.0.0\";\n\n/** Default chunk size: 5 MiB, the size most tus servers are tuned for. */\nexport const DEFAULT_CHUNK_SIZE = 5 * 1024 * 1024;\n\n/**\n * Where a resumable upload is.\n *\n * `\"paused\"` and `\"aborted\"` are both \"not running\", but only `\"paused\"` keeps the\n * persisted offset — `abort({ discard: true })` throws it away.\n */\nexport type ResumableUploadState =\n \"idle\" | \"creating\" | \"uploading\" | \"paused\" | \"done\" | \"error\" | \"aborted\";\n\n/** Byte-level progress for a resumable upload. */\nexport interface ResumableUploadProgress {\n /** Bytes the server holds, including anything a resume skipped. */\n loaded: number;\n /** Total size of the file. */\n total: number;\n /** `loaded / total`, between 0 and 1. */\n fraction: number;\n /** Bytes already on the server when this run started. `0` on a fresh upload. */\n resumedFrom: number;\n}\n\n/** What has to survive a page reload for a resume to be possible. */\nexport interface ResumableUploadRecord {\n /** Upload URL the creation POST returned, absolute. */\n url: string;\n /** Last offset the server confirmed. */\n offset: number;\n /** File size, so a different file under the same key is not resumed into. */\n size: number;\n /** Idempotency key of the creation request, reused if creation is retried. */\n idempotencyKey: string;\n /** Epoch ms of the last write, so an app can sweep stale records. */\n updatedAt: number;\n}\n\n/**\n * Persistence for resume state. Sync or async — both are awaited.\n *\n * Implement it over anything: the default is `localStorage`, and\n * `createOfflineStore` from `@/offline` slots in when you already have a Dexie\n * database open.\n */\nexport interface ResumableUploadStorage {\n /** Read the record for `key`, or `null`. */\n get(key: string): Promise<ResumableUploadRecord | null> | ResumableUploadRecord | null;\n /** Write the record for `key`. */\n set(key: string, record: ResumableUploadRecord): Promise<void> | void;\n /** Forget the record for `key`. */\n delete(key: string): Promise<void> | void;\n}\n\n/** Options for {@link createResumableUpload}. */\nexport interface ResumableUploadOptions {\n /** tus creation endpoint, e.g. `\"/api/uploads\"`. */\n endpoint: string;\n /** The bytes to upload. A `File` also supplies the default resume key. */\n file: Blob | File;\n /** Bytes per `PATCH`. Default {@link DEFAULT_CHUNK_SIZE}. */\n chunkSize?: number;\n /** Sent as `Upload-Metadata` (base64-encoded values), e.g. `{ filename }`. */\n metadata?: Record<string, string>;\n /** Extra headers on every request. */\n headers?: Record<string, string>;\n /** Returns the current bearer token, read before each request. */\n getToken?: () => string | null | undefined;\n /** Send cookies. Default `false`. */\n withCredentials?: boolean;\n /**\n * Resume key. Defaults to a fingerprint of endpoint + file name/size/mtime, so\n * picking the same file after a reload resumes instead of restarting.\n */\n key?: string;\n /**\n * Where to persist resume state. Defaults to `localStorage`. Pass `null` to\n * disable persistence — resume then only survives a network blip, not a reload.\n */\n storage?: ResumableUploadStorage | null;\n /** Backoff for a failed chunk. Forwarded to `retry`. Default 5 attempts. */\n retry?: RetryOptions;\n /** Called on every upload-progress tick and after every confirmed chunk. */\n onProgress?: (progress: ResumableUploadProgress) => void;\n /** Called whenever {@link ResumableUpload.state} changes. */\n onStateChange?: (state: ResumableUploadState) => void;\n}\n\n/** What a finished upload resolves with. */\nexport interface ResumableUploadResult {\n /** The tus upload URL — hand this to your API to link the stored file. */\n url: string;\n /** Total bytes uploaded. */\n size: number;\n}\n\n/** A resumable upload in progress. Build one with {@link createResumableUpload}. */\nexport interface ResumableUpload {\n /**\n * Create (or re-attach to) the upload and push chunks until it is complete.\n *\n * Resolves `null` when the run stopped because of `pause()` or `abort()` —\n * neither is a failure. Rejects with a `TempestApiError` when the server\n * refused and the retries ran out.\n */\n start(): Promise<ResumableUploadResult | null>;\n /** Stop after the in-flight chunk is dropped, keeping the resume point. */\n pause(): void;\n /** Continue from the server's offset. Same resolution contract as `start`. */\n resume(): Promise<ResumableUploadResult | null>;\n /**\n * Stop for good.\n *\n * @param options - `discard: true` also sends `DELETE` (tus termination) and\n * forgets the persisted record, so the next `start()` uploads from zero.\n */\n abort(options?: { discard?: boolean }): Promise<void>;\n /** Current state. */\n readonly state: ResumableUploadState;\n /** Bytes the server has confirmed. */\n readonly offset: number;\n /** The upload URL, once creation succeeded. */\n readonly url: string | null;\n /** The resume key in use. */\n readonly key: string;\n}\n\ninterface RawResponse {\n status: number;\n text: string;\n header(name: string): string | null;\n}\n\n/**\n * Encode a string as standard base64 (padded), UTF-8 first.\n *\n * `Upload-Metadata` carries base64 values precisely so a filename with accents\n * survives an HTTP header, so the UTF-8 step is not optional: `btoa` alone throws\n * on any code point above U+00FF.\n *\n * @param value - Text to encode.\n * @returns Padded base64.\n */\nfunction base64Utf8(value: string): string {\n const bytes = new TextEncoder().encode(value);\n let binary = \"\";\n for (const byte of bytes) binary += String.fromCharCode(byte);\n return btoa(binary);\n}\n\n/**\n * Build the `Upload-Metadata` header value: comma-separated `key base64(value)`.\n *\n * @param metadata - Plain string map.\n * @returns The header value, or `null` when there is nothing to send.\n */\nfunction encodeMetadata(metadata: Record<string, string> | undefined): string | null {\n if (!metadata) return null;\n const parts = Object.entries(metadata).map(([name, value]) => `${name} ${base64Utf8(value)}`);\n return parts.length > 0 ? parts.join(\",\") : null;\n}\n\n/**\n * A stable-enough identity for a file, used as the default resume key.\n *\n * Name + size + last-modified is what the tus reference clients fingerprint on:\n * it is cheap (hashing the bytes of a 400 MB recording is not) and it changes\n * whenever the file does, which is the property that matters — resuming into the\n * wrong file would corrupt it silently.\n *\n * @param endpoint - Creation endpoint, so the same file to two servers is two uploads.\n * @param file - The blob or file being uploaded.\n * @returns A key safe to use in `localStorage`.\n */\nexport function uploadFingerprint(endpoint: string, file: Blob | File): string {\n const named = file as File;\n const name = typeof named.name === \"string\" ? named.name : \"blob\";\n const modified = typeof named.lastModified === \"number\" ? named.lastModified : 0;\n return `${endpoint}|${name}|${file.size}|${file.type}|${modified}`;\n}\n\n/**\n * `localStorage`-backed resume storage — the default.\n *\n * `localStorage` and not IndexedDB on purpose. The record is four fields and a\n * URL; the requirement is only that it survives a reload, and pulling Dexie in for\n * that would put an IndexedDB dependency in the bundle of every app that uploads a\n * file. Apps that already have `createOfflineStore` open can pass their own\n * {@link ResumableUploadStorage} instead.\n *\n * @param prefix - Key prefix. Default `\"tempest-upload:\"`.\n * @returns A storage that no-ops when `localStorage` is unavailable.\n */\nexport function createLocalUploadStorage(prefix = \"tempest-upload:\"): ResumableUploadStorage {\n function backend(): Storage | null {\n try {\n return typeof localStorage === \"undefined\" ? null : localStorage;\n } catch {\n return null;\n }\n }\n\n return {\n get(key) {\n const raw = backend()?.getItem(prefix + key);\n if (!raw) return null;\n try {\n return JSON.parse(raw) as ResumableUploadRecord;\n } catch {\n return null;\n }\n },\n set(key, record) {\n backend()?.setItem(prefix + key, JSON.stringify(record));\n },\n delete(key) {\n backend()?.removeItem(prefix + key);\n },\n };\n}\n\n/**\n * Send one request over `XMLHttpRequest`.\n *\n * `XMLHttpRequest` rather than `fetch` for the same reason `uploadWithProgress`\n * uses it — `fetch` still cannot report upload progress in any browser — plus one\n * more: tus answers every write with the new `Upload-Offset` in a **response\n * header**, and `uploadWithProgress` only hands back a parsed body, so it could\n * not be reused here.\n *\n * @param init - Method, URL, headers, optional body and progress callback.\n * @returns Status, raw text and a header reader.\n */\nfunction sendRequest(init: {\n method: \"POST\" | \"HEAD\" | \"PATCH\" | \"DELETE\";\n url: string;\n headers: Record<string, string>;\n body?: Blob;\n withCredentials: boolean;\n onProgress?: (loaded: number) => void;\n register: (xhr: XMLHttpRequest) => void;\n}): Promise<RawResponse> {\n return new Promise<RawResponse>((resolve, reject) => {\n const xhr = new XMLHttpRequest();\n xhr.open(init.method, init.url);\n xhr.withCredentials = init.withCredentials;\n for (const [name, value] of Object.entries(init.headers)) {\n xhr.setRequestHeader(name, value);\n }\n if (init.onProgress) {\n const report = init.onProgress;\n xhr.upload.onprogress = (event: ProgressEvent) => report(event.loaded);\n }\n xhr.onload = () =>\n resolve({\n status: xhr.status,\n text: xhr.responseText,\n header: (name) => xhr.getResponseHeader(name),\n });\n xhr.onerror = () =>\n reject(\n new TempestApiError({\n status: 0,\n detail: \"Falha de rede no upload resumível.\",\n }),\n );\n xhr.onabort = () => reject(new DOMException(\"Aborted\", \"AbortError\"));\n init.register(xhr);\n xhr.send(init.body);\n });\n}\n\nfunction parseOffset(response: RawResponse): number | null {\n const raw = response.header(\"Upload-Offset\");\n if (raw === null) return null;\n const value = Number(raw);\n return Number.isFinite(value) && value >= 0 ? value : null;\n}\n\n/**\n * Read an error body without assuming it is JSON.\n *\n * A tus proxy that rejects a chunk often answers with plain text or an HTML error\n * page, and `JSON.parse` throwing there would replace a useful status with a parse\n * error.\n *\n * @param text - Raw response text.\n * @returns The parsed object, the raw text, or `null` when the body was empty.\n */\nfunction parseErrorBody(text: string): unknown {\n if (!text) return null;\n try {\n return JSON.parse(text);\n } catch {\n return text;\n }\n}\n\n/**\n * Turn a refused tus response into a `TempestApiError`.\n *\n * The fallback `detail` is used unless the server sent a real error envelope,\n * because `buildApiError`'s own fallback (`\"Erro 409\"`) says nothing about which\n * step of the protocol broke — and that is the whole diagnostic value here.\n *\n * @param response - The raw response that was not acceptable.\n * @param detail - Message to use when the body carries none.\n * @returns The error to throw.\n */\nfunction failed(response: RawResponse, detail: string): TempestApiError {\n const body = parseErrorBody(response.text);\n const envelope = buildApiError(response.status, body, { get: response.header });\n const hasDetail =\n typeof body === \"object\" && body !== null && (\"detail\" in body || \"message\" in body);\n return new TempestApiError({ ...envelope, detail: hasDetail ? envelope.detail : detail });\n}\n\n/**\n * Resolve a `Location` header against the page, so a relative upload URL works.\n *\n * tus servers are free to answer creation with either an absolute URL or a\n * path, and the spec does not prefer one — a client that only handles absolute\n * URLs breaks against half the implementations.\n *\n * @param value - The raw `Location` header.\n * @returns An absolute URL, or the input when there is no base to resolve against.\n */\nfunction resolveUploadUrl(value: string): string {\n const base = typeof window === \"undefined\" ? undefined : window.location.href;\n try {\n return new URL(value, base).href;\n } catch {\n return value;\n }\n}\n\n/**\n * Chunked, resumable upload speaking the **tus 1.0.0** protocol (core plus the\n * *creation* and *termination* extensions).\n *\n * ## Why tus and not a bespoke scheme\n *\n * A resumable client whose wire format is undocumented cannot be integrated, and\n * inventing one means the backend is ours forever. tus is a published spec with\n * off-the-shelf servers (`tusd`, `tuspy`, `tus-node-server`), so a caller can point\n * this at something they did not write.\n *\n * ## What the backend must implement\n *\n * Every request carries `Tus-Resumable: 1.0.0`.\n *\n * | Step | Request | Expected response |\n * | --- | --- | --- |\n * | Create | `POST {endpoint}` + `Upload-Length`, `Upload-Metadata`, `Idempotency-Key` | `201` + `Location` (the upload URL, absolute or endpoint-relative) |\n * | Probe | `HEAD {uploadUrl}` | `200`/`204` + `Upload-Offset` |\n * | Write | `PATCH {uploadUrl}` + `Upload-Offset`, `Content-Type: application/offset+octet-stream`, chunk body | `204` + the new `Upload-Offset`; `409` when the offset does not match |\n * | Discard | `DELETE {uploadUrl}` | `204` |\n *\n * ## The failure that actually happens\n *\n * A chunk that the server stored but whose response never arrived. The client\n * cannot tell that from a chunk that was lost, and re-sending it blindly would\n * duplicate bytes. Two things prevent that:\n *\n * - **Writes are addressed, not appended.** Every `PATCH` states the offset it\n * writes at, so a retry after a lost response is asked to write bytes the server\n * already has and answers `409`. On any retry the client re-reads the truth with\n * `HEAD` first and continues from there.\n * - **Creation carries an `Idempotency-Key`** (from `generateIdempotencyKey`),\n * persisted before the first attempt and reused on retry. tus has no idempotent\n * creation of its own, so without this a lost `201` leaves an orphan upload on\n * the server. A backend that honours the header returns the same `Location`; one\n * that ignores it still works, it just keeps the orphan.\n *\n * @param options - Endpoint, file, and the knobs above.\n * @returns A handle with `start`/`pause`/`resume`/`abort` and live `state`/`offset`.\n *\n * @example\n * const upload = createResumableUpload({\n * endpoint: \"/api/uploads\",\n * file: recording,\n * metadata: { filename: \"nota.webm\", ticket: ticketId },\n * getToken: () => auth.getToken(),\n * onProgress: ({ fraction }) => setPercent(Math.round(fraction * 100)),\n * });\n *\n * const done = await upload.start();\n * if (done) await api.post(\"/api/tickets/1/audio\", { body: { url: done.url } });\n */\nexport function createResumableUpload(options: ResumableUploadOptions): ResumableUpload {\n const {\n endpoint,\n file,\n chunkSize = DEFAULT_CHUNK_SIZE,\n metadata,\n headers = {},\n getToken,\n withCredentials = false,\n key = uploadFingerprint(endpoint, file),\n storage = createLocalUploadStorage(),\n retry: retryOptions,\n onProgress,\n onStateChange,\n } = options;\n\n let state: ResumableUploadState = \"idle\";\n let offset = 0;\n let url: string | null = null;\n let idempotencyKey: string | null = null;\n let stopping: \"pause\" | \"abort\" | null = null;\n let inFlight: XMLHttpRequest | null = null;\n let resumedFrom = 0;\n\n function setState(next: ResumableUploadState): void {\n if (state === next) return;\n state = next;\n onStateChange?.(next);\n }\n\n function report(loaded: number): void {\n onProgress?.({\n loaded,\n total: file.size,\n fraction: file.size === 0 ? 1 : loaded / file.size,\n resumedFrom,\n });\n }\n\n function baseHeaders(): Record<string, string> {\n const result: Record<string, string> = { ...headers, \"Tus-Resumable\": TUS_VERSION };\n const token = getToken?.();\n if (token && !(\"Authorization\" in result)) result.Authorization = `Bearer ${token}`;\n return result;\n }\n\n function register(xhr: XMLHttpRequest): void {\n inFlight = xhr;\n }\n\n async function persist(): Promise<void> {\n if (!storage || !url || !idempotencyKey) return;\n await storage.set(key, {\n url,\n offset,\n size: file.size,\n idempotencyKey,\n updatedAt: Date.now(),\n });\n }\n\n /**\n * Ask the server how much it holds. The only source of truth after any failure.\n */\n async function probe(target: string): Promise<number> {\n const response = await sendRequest({\n method: \"HEAD\",\n url: target,\n headers: baseHeaders(),\n withCredentials,\n register,\n });\n if (response.status === 404 || response.status === 410) {\n throw new TempestApiError({\n status: response.status,\n detail: \"O upload expirou no servidor. Comece de novo.\",\n });\n }\n const confirmed = parseOffset(response);\n if (confirmed === null) throw failed(response, \"HEAD sem Upload-Offset.\");\n return confirmed;\n }\n\n /**\n * Re-attach to a persisted upload, or create a new one.\n *\n * The persisted record is only trusted when the file size still matches, and the\n * offset it holds is re-checked with `HEAD` — the client's copy can be ahead of\n * the server's whenever the last response was lost.\n */\n async function ensureUpload(): Promise<string> {\n const stored = storage ? await storage.get(key) : null;\n if (stored && stored.size === file.size) {\n idempotencyKey = stored.idempotencyKey;\n if (stored.url) {\n try {\n offset = await probe(stored.url);\n url = stored.url;\n return stored.url;\n } catch {\n offset = 0;\n }\n }\n }\n\n setState(\"creating\");\n idempotencyKey ??= generateIdempotencyKey();\n url = null;\n offset = 0;\n if (storage) {\n await storage.set(key, {\n url: \"\",\n offset: 0,\n size: file.size,\n idempotencyKey,\n updatedAt: Date.now(),\n });\n }\n\n const creationHeaders: Record<string, string> = {\n ...baseHeaders(),\n \"Upload-Length\": String(file.size),\n \"Idempotency-Key\": idempotencyKey,\n };\n const encoded = encodeMetadata(metadata);\n if (encoded) creationHeaders[\"Upload-Metadata\"] = encoded;\n\n const response = await sendRequest({\n method: \"POST\",\n url: endpoint,\n headers: creationHeaders,\n withCredentials,\n register,\n });\n if (response.status !== 201) throw failed(response, \"Criação do upload recusada.\");\n const locationHeader = response.header(\"Location\");\n if (!locationHeader) throw failed(response, \"Criação do upload sem cabeçalho Location.\");\n\n url = resolveUploadUrl(locationHeader);\n await persist();\n return url;\n }\n\n /** Push one chunk, resyncing the offset first when a previous attempt failed. */\n async function writeChunk(target: string, resync: { needed: boolean }): Promise<void> {\n if (resync.needed) {\n offset = await probe(target);\n resync.needed = false;\n report(offset);\n await persist();\n if (offset >= file.size) return;\n }\n\n const end = Math.min(offset + chunkSize, file.size);\n const from = offset;\n const response = await sendRequest({\n method: \"PATCH\",\n url: target,\n headers: {\n ...baseHeaders(),\n \"Content-Type\": \"application/offset+octet-stream\",\n \"Upload-Offset\": String(from),\n },\n body: file.slice(from, end),\n withCredentials,\n onProgress: (loaded) => report(Math.min(from + loaded, file.size)),\n register,\n });\n\n if (response.status === 409 || response.status === 412) {\n resync.needed = true;\n throw failed(response, \"Offset divergente — o servidor já tinha esses bytes.\");\n }\n if (response.status !== 204 && response.status !== 200) {\n throw failed(response, \"Chunk recusado pelo servidor.\");\n }\n\n offset = parseOffset(response) ?? end;\n report(offset);\n await persist();\n }\n\n /**\n * Drive the whole upload: attach or create, then chunk until complete.\n *\n * The `shouldRetry` predicate does double duty — besides deciding, it arms\n * `resync` so the next attempt re-reads the server's offset with `HEAD` before\n * writing. That is deliberate: it is the one place that sees *every* chunk\n * failure, whatever the cause, and after any failure the client's idea of the\n * offset is exactly what cannot be trusted.\n *\n * @returns The result, or `null` when `pause`/`abort` stopped the run.\n */\n async function run(): Promise<ResumableUploadResult | null> {\n stopping = null;\n const target = await ensureUpload();\n resumedFrom = offset;\n setState(\"uploading\");\n report(offset);\n\n const resync = { needed: false };\n while (offset < file.size) {\n if (stopping) break;\n await retry(() => writeChunk(target, resync), {\n retries: 5,\n ...retryOptions,\n shouldRetry: (error, attempt) => {\n if (stopping) return false;\n if (error instanceof DOMException && error.name === \"AbortError\") return false;\n resync.needed = true;\n return retryOptions?.shouldRetry?.(error, attempt) ?? true;\n },\n });\n }\n\n if (stopping === \"pause\") {\n setState(\"paused\");\n return null;\n }\n if (stopping === \"abort\") {\n setState(\"aborted\");\n return null;\n }\n\n setState(\"done\");\n if (storage) await storage.delete(key);\n return { url: target, size: file.size };\n }\n\n async function guarded(): Promise<ResumableUploadResult | null> {\n try {\n return await run();\n } catch (error) {\n if (\n stopping !== null ||\n (error instanceof DOMException && error.name === \"AbortError\")\n ) {\n setState(stopping === \"abort\" ? \"aborted\" : \"paused\");\n return null;\n }\n setState(\"error\");\n throw error;\n } finally {\n inFlight = null;\n }\n }\n\n function stop(reason: \"pause\" | \"abort\"): void {\n stopping = reason;\n inFlight?.abort();\n inFlight = null;\n }\n\n return {\n start: guarded,\n resume: guarded,\n pause: () => stop(\"pause\"),\n abort: async ({ discard = false } = {}) => {\n stop(\"abort\");\n setState(\"aborted\");\n if (!discard) return;\n if (url) {\n await sendRequest({\n method: \"DELETE\",\n url,\n headers: baseHeaders(),\n withCredentials,\n register: () => undefined,\n }).catch(() => undefined);\n }\n if (storage) await storage.delete(key);\n },\n get state() {\n return state;\n },\n get offset() {\n return offset;\n },\n get url() {\n return url;\n },\n key,\n };\n}\n"],"mappings":";;;;AAKA,IAAa,IAAc,SAGd,IAAqB,IAAI,OAAO;AA8I7C,SAAS,EAAW,GAAuB;CACvC,IAAM,IAAQ,IAAI,YAAY,CAAC,CAAC,OAAO,CAAK,GACxC,IAAS;CACb,KAAK,IAAM,KAAQ,GAAO,KAAU,OAAO,aAAa,CAAI;CAC5D,OAAO,KAAK,CAAM;AACtB;AAQA,SAAS,EAAe,GAA6D;CACjF,IAAI,CAAC,GAAU,OAAO;CACtB,IAAM,IAAQ,OAAO,QAAQ,CAAQ,CAAC,CAAC,KAAK,CAAC,GAAM,OAAW,GAAG,EAAK,GAAG,EAAW,CAAK,GAAG;CAC5F,OAAO,EAAM,SAAS,IAAI,EAAM,KAAK,GAAG,IAAI;AAChD;AAcA,SAAgB,EAAkB,GAAkB,GAA2B;CAC3E,IAAM,IAAQ,GACR,IAAO,OAAO,EAAM,QAAS,WAAW,EAAM,OAAO,QACrD,IAAW,OAAO,EAAM,gBAAiB,WAAW,EAAM,eAAe;CAC/E,OAAO,GAAG,EAAS,GAAG,EAAK,GAAG,EAAK,KAAK,GAAG,EAAK,KAAK,GAAG;AAC5D;AAcA,SAAgB,EAAyB,IAAS,mBAA2C;CACzF,SAAS,IAA0B;EAC/B,IAAI;GACA,OAAO,OAAO,eAAiB,MAAc,OAAO;EACxD,QAAQ;GACJ,OAAO;EACX;CACJ;CAEA,OAAO;EACH,IAAI,GAAK;GACL,IAAM,IAAM,EAAQ,CAAC,EAAE,QAAQ,IAAS,CAAG;GAC3C,IAAI,CAAC,GAAK,OAAO;GACjB,IAAI;IACA,OAAO,KAAK,MAA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EAAS,MAAM,GACX,KAAS,MAAM,EAAQ,OAAO,CAAG,GAC9B;GAAE,KAAK;GAAQ,MAAM,EAAK;EAAK;CAC1C;CAEA,eAAe,IAAiD;EAC5D,IAAI;GACA,OAAO,MAAM,EAAI;EACrB,SAAS,GAAO;GACZ,IACI,MAAa,QACZ,aAAiB,gBAAgB,EAAM,SAAS,cAGjD,OADA,EAAS,MAAa,UAAU,YAAY,QAAQ,GAC7C;GAGX,MADA,EAAS,OAAO,GACV;EACV,UAAU;GACN,IAAW;EACf;CACJ;CAEA,SAAS,EAAK,GAAiC;EAG3C,AAFA,IAAW,GACX,GAAU,MAAM,GAChB,IAAW;CACf;CAEA,OAAO;EACH,OAAO;EACP,QAAQ;EACR,aAAa,EAAK,OAAO;EACzB,OAAO,OAAO,EAAE,aAAU,OAAU,CAAC,MAAM;GACvC,EAAK,OAAO,GACZ,EAAS,SAAS,GACb,MACD,KACA,MAAM,EAAY;IACd,QAAQ;IACR;IACA,SAAS,EAAY;IACrB;IACA,gBAAgB,KAAA;GACpB,CAAC,CAAC,CAAC,YAAY,KAAA,CAAS,GAExB,KAAS,MAAM,EAAQ,OAAO,CAAG;EACzC;EACA,IAAI,QAAQ;GACR,OAAO;EACX;EACA,IAAI,SAAS;GACT,OAAO;EACX;EACA,IAAI,MAAM;GACN,OAAO;EACX;EACA;CACJ;AACJ"}
@@ -0,0 +1,2 @@
1
+ async function e(e,t){if(typeof caches>`u`)return null;try{let n=(await(await caches.open(e)).match(t))?.headers.get(`content-length`);if(!n)return null;let r=Number.parseInt(n,10);return Number.isFinite(r)?r:null}catch{return null}}exports.cachedResponseBytes=e;
2
+ //# sourceMappingURL=cache-size.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"cache-size.cjs","names":[],"sources":["../../src/perf/cache-size.ts"],"sourcesContent":["/**\n * How large the assets a page precached actually are.\n *\n * Reads the `Content-Length` of a stored response instead of its body:\n * materializing a cached ONNX model or WASM binary to learn its length would\n * pull tens of megabytes into memory on every measurement.\n */\n\n/**\n * Byte size of a response sitting in a Cache Storage bucket.\n *\n * @param cacheName The cache bucket to look in.\n * @param url The request URL the response was stored under.\n * @returns The size in bytes, or `null` when Cache Storage is unavailable,\n * the entry is absent, or the stored response carries no usable\n * `Content-Length` (a chunked transfer, typically).\n *\n * @example\n * ```typescript\n * const bytes = await cachedResponseBytes(\"app-models\", \"/models/detect.onnx\");\n * console.log(bytes === null ? \"—\" : formatBytes(bytes)); // \"12.0 MB\"\n * ```\n */\nexport async function cachedResponseBytes(cacheName: string, url: string): Promise<number | null> {\n if (typeof caches === \"undefined\") return null;\n try {\n const cache = await caches.open(cacheName);\n const response = await cache.match(url);\n const header = response?.headers.get(\"content-length\");\n if (!header) return null;\n const bytes = Number.parseInt(header, 10);\n return Number.isFinite(bytes) ? bytes : null;\n } catch {\n return null;\n }\n}\n"],"mappings":"AAuBA,eAAsB,EAAoB,EAAmB,EAAqC,CAC9F,GAAI,OAAO,OAAW,IAAa,OAAO,KAC1C,GAAI,CAGA,IAAM,GAAS,MADQ,MADH,OAAO,KAAK,CAAS,EAAA,CACZ,MAAM,CAAG,EAAA,EACb,QAAQ,IAAI,gBAAgB,EACrD,GAAI,CAAC,EAAQ,OAAO,KACpB,IAAM,EAAQ,OAAO,SAAS,EAAQ,EAAE,EACxC,OAAO,OAAO,SAAS,CAAK,EAAI,EAAQ,IAC5C,MAAQ,CACJ,OAAO,IACX,CACJ"}
@@ -0,0 +1,16 @@
1
+ //#region src/perf/cache-size.ts
2
+ async function e(e, t) {
3
+ if (typeof caches > "u") return null;
4
+ try {
5
+ let n = (await (await caches.open(e)).match(t))?.headers.get("content-length");
6
+ if (!n) return null;
7
+ let r = Number.parseInt(n, 10);
8
+ return Number.isFinite(r) ? r : null;
9
+ } catch {
10
+ return null;
11
+ }
12
+ }
13
+ //#endregion
14
+ export { e as cachedResponseBytes };
15
+
16
+ //# sourceMappingURL=cache-size.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"cache-size.js","names":[],"sources":["../../src/perf/cache-size.ts"],"sourcesContent":["/**\n * How large the assets a page precached actually are.\n *\n * Reads the `Content-Length` of a stored response instead of its body:\n * materializing a cached ONNX model or WASM binary to learn its length would\n * pull tens of megabytes into memory on every measurement.\n */\n\n/**\n * Byte size of a response sitting in a Cache Storage bucket.\n *\n * @param cacheName The cache bucket to look in.\n * @param url The request URL the response was stored under.\n * @returns The size in bytes, or `null` when Cache Storage is unavailable,\n * the entry is absent, or the stored response carries no usable\n * `Content-Length` (a chunked transfer, typically).\n *\n * @example\n * ```typescript\n * const bytes = await cachedResponseBytes(\"app-models\", \"/models/detect.onnx\");\n * console.log(bytes === null ? \"—\" : formatBytes(bytes)); // \"12.0 MB\"\n * ```\n */\nexport async function cachedResponseBytes(cacheName: string, url: string): Promise<number | null> {\n if (typeof caches === \"undefined\") return null;\n try {\n const cache = await caches.open(cacheName);\n const response = await cache.match(url);\n const header = response?.headers.get(\"content-length\");\n if (!header) return null;\n const bytes = Number.parseInt(header, 10);\n return Number.isFinite(bytes) ? bytes : null;\n } catch {\n return null;\n }\n}\n"],"mappings":";AAuBA,eAAsB,EAAoB,GAAmB,GAAqC;CAC9F,IAAI,OAAO,SAAW,KAAa,OAAO;CAC1C,IAAI;EAGA,IAAM,KAAS,OADQ,MADH,OAAO,KAAK,CAAS,EAAA,CACZ,MAAM,CAAG,EAAA,EACb,QAAQ,IAAI,gBAAgB;EACrD,IAAI,CAAC,GAAQ,OAAO;EACpB,IAAM,IAAQ,OAAO,SAAS,GAAQ,EAAE;EACxC,OAAO,OAAO,SAAS,CAAK,IAAI,IAAQ;CAC5C,QAAQ;EACJ,OAAO;CACX;AACJ"}
@@ -0,0 +1,2 @@
1
+ function e(){if(typeof performance>`u`)return null;let e=performance.memory;return e?Math.round(e.usedJSHeapSize/1048576*10)/10:null}function t(){if(typeof navigator>`u`)return{hardwareConcurrency:null,deviceMemoryGb:null,jsHeapUsedMb:null};let t=navigator;return{hardwareConcurrency:t.hardwareConcurrency??null,deviceMemoryGb:t.deviceMemory??null,jsHeapUsedMb:e()}}exports.readDeviceProfile=t;
2
+ //# sourceMappingURL=device.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"device.cjs","names":[],"sources":["../../src/perf/device.ts"],"sourcesContent":["import type { DeviceProfile } from \"./types\";\n\n/**\n * What the browser will tell us about the machine it is running on.\n */\n\nconst BYTES_PER_MIB = 1024 * 1024;\n\n/** `navigator.deviceMemory` is Chromium-only and absent from the DOM lib. */\ninterface DeviceMemoryNavigator extends Navigator {\n deviceMemory?: number;\n}\n\n/** `performance.memory` is a non-standard Chromium extension. */\ninterface HeapPerformance extends Performance {\n memory?: { usedJSHeapSize: number };\n}\n\n/**\n * Used JS heap in MiB, rounded to one decimal.\n *\n * @returns The heap usage, or `null` outside Chromium.\n */\nfunction readHeapUsedMb(): number | null {\n if (typeof performance === \"undefined\") return null;\n const memory = (performance as HeapPerformance).memory;\n if (!memory) return null;\n return Math.round((memory.usedJSHeapSize / BYTES_PER_MIB) * 10) / 10;\n}\n\n/**\n * Sample the device capabilities the browser reports.\n *\n * Safe to call during SSR: without a `navigator` every field is `null`.\n *\n * @returns The profile, with `null` for anything this platform withholds.\n *\n * @example\n * ```typescript\n * const device = readDeviceProfile();\n * console.log(device.hardwareConcurrency); // 8\n * console.log(device.deviceMemoryGb); // 8 on Chromium, null on Safari\n * ```\n */\nexport function readDeviceProfile(): DeviceProfile {\n if (typeof navigator === \"undefined\") {\n return { hardwareConcurrency: null, deviceMemoryGb: null, jsHeapUsedMb: null };\n }\n const nav = navigator as DeviceMemoryNavigator;\n return {\n hardwareConcurrency: nav.hardwareConcurrency ?? null,\n deviceMemoryGb: nav.deviceMemory ?? null,\n jsHeapUsedMb: readHeapUsedMb(),\n };\n}\n"],"mappings":"AAuBA,SAAS,GAAgC,CACrC,GAAI,OAAO,YAAgB,IAAa,OAAO,KAC/C,IAAM,EAAU,YAAgC,OAEhD,OADK,EACE,KAAK,MAAO,EAAO,eAAiB,QAAiB,EAAE,EAAI,GAD9C,IAExB,CAgBA,SAAgB,GAAmC,CAC/C,GAAI,OAAO,UAAc,IACrB,MAAO,CAAE,oBAAqB,KAAM,eAAgB,KAAM,aAAc,IAAK,EAEjF,IAAM,EAAM,UACZ,MAAO,CACH,oBAAqB,EAAI,qBAAuB,KAChD,eAAgB,EAAI,cAAgB,KACpC,aAAc,EAAe,CACjC,CACJ"}
@@ -0,0 +1,22 @@
1
+ function e() {
2
+ if (typeof performance > "u") return null;
3
+ let e = performance.memory;
4
+ return e ? Math.round(e.usedJSHeapSize / 1048576 * 10) / 10 : null;
5
+ }
6
+ function t() {
7
+ if (typeof navigator > "u") return {
8
+ hardwareConcurrency: null,
9
+ deviceMemoryGb: null,
10
+ jsHeapUsedMb: null
11
+ };
12
+ let t = navigator;
13
+ return {
14
+ hardwareConcurrency: t.hardwareConcurrency ?? null,
15
+ deviceMemoryGb: t.deviceMemory ?? null,
16
+ jsHeapUsedMb: e()
17
+ };
18
+ }
19
+ //#endregion
20
+ export { t as readDeviceProfile };
21
+
22
+ //# sourceMappingURL=device.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"device.js","names":[],"sources":["../../src/perf/device.ts"],"sourcesContent":["import type { DeviceProfile } from \"./types\";\n\n/**\n * What the browser will tell us about the machine it is running on.\n */\n\nconst BYTES_PER_MIB = 1024 * 1024;\n\n/** `navigator.deviceMemory` is Chromium-only and absent from the DOM lib. */\ninterface DeviceMemoryNavigator extends Navigator {\n deviceMemory?: number;\n}\n\n/** `performance.memory` is a non-standard Chromium extension. */\ninterface HeapPerformance extends Performance {\n memory?: { usedJSHeapSize: number };\n}\n\n/**\n * Used JS heap in MiB, rounded to one decimal.\n *\n * @returns The heap usage, or `null` outside Chromium.\n */\nfunction readHeapUsedMb(): number | null {\n if (typeof performance === \"undefined\") return null;\n const memory = (performance as HeapPerformance).memory;\n if (!memory) return null;\n return Math.round((memory.usedJSHeapSize / BYTES_PER_MIB) * 10) / 10;\n}\n\n/**\n * Sample the device capabilities the browser reports.\n *\n * Safe to call during SSR: without a `navigator` every field is `null`.\n *\n * @returns The profile, with `null` for anything this platform withholds.\n *\n * @example\n * ```typescript\n * const device = readDeviceProfile();\n * console.log(device.hardwareConcurrency); // 8\n * console.log(device.deviceMemoryGb); // 8 on Chromium, null on Safari\n * ```\n */\nexport function readDeviceProfile(): DeviceProfile {\n if (typeof navigator === \"undefined\") {\n return { hardwareConcurrency: null, deviceMemoryGb: null, jsHeapUsedMb: null };\n }\n const nav = navigator as DeviceMemoryNavigator;\n return {\n hardwareConcurrency: nav.hardwareConcurrency ?? null,\n deviceMemoryGb: nav.deviceMemory ?? null,\n jsHeapUsedMb: readHeapUsedMb(),\n };\n}\n"],"mappings":"AAuBA,SAAS,IAAgC;CACrC,IAAI,OAAO,cAAgB,KAAa,OAAO;CAC/C,IAAM,IAAU,YAAgC;CAEhD,OADK,IACE,KAAK,MAAO,EAAO,iBAAiB,UAAiB,EAAE,IAAI,KAD9C;AAExB;AAgBA,SAAgB,IAAmC;CAC/C,IAAI,OAAO,YAAc,KACrB,OAAO;EAAE,qBAAqB;EAAM,gBAAgB;EAAM,cAAc;CAAK;CAEjF,IAAM,IAAM;CACZ,OAAO;EACH,qBAAqB,EAAI,uBAAuB;EAChD,gBAAgB,EAAI,gBAAgB;EACpC,cAAc,EAAe;CACjC;AACJ"}
@@ -0,0 +1,2 @@
1
+ function e(e){return!Number.isFinite(e)||e<0?`—`:e<1?`<1 ms`:e<1e3?`${Math.round(e)} ms`:`${(e/1e3).toFixed(2)} s`}exports.formatDurationMs=e;
2
+ //# sourceMappingURL=format.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"format.cjs","names":[],"sources":["../../src/perf/format.ts"],"sourcesContent":["/**\n * Rendering helpers for the numbers a profiler produces.\n */\n\n/**\n * Format a millisecond duration for display.\n *\n * Sub-second values keep millisecond resolution — the interesting range for a\n * single forward pass — and anything longer switches to seconds so a cold\n * start that pays a model download does not read as a five-digit number.\n * Durations under `1 ms` render as `\"<1 ms\"` rather than `\"0 ms\"`, which\n * would read as \"not measured\".\n *\n * @param value Duration in milliseconds.\n * @returns The formatted string, or `\"—\"` for a non-finite or negative input.\n *\n * @example\n * ```typescript\n * formatDurationMs(0.04); // \"<1 ms\"\n * formatDurationMs(142.6); // \"143 ms\"\n * formatDurationMs(4321); // \"4.32 s\"\n * formatDurationMs(NaN); // \"—\"\n * ```\n */\nexport function formatDurationMs(value: number): string {\n if (!Number.isFinite(value) || value < 0) return \"—\";\n if (value < 1) return \"<1 ms\";\n if (value < 1000) return `${Math.round(value)} ms`;\n return `${(value / 1000).toFixed(2)} s`;\n}\n"],"mappings":"AAwBA,SAAgB,EAAiB,EAAuB,CAIpD,MAHI,CAAC,OAAO,SAAS,CAAK,GAAK,EAAQ,EAAU,IAC7C,EAAQ,EAAU,QAClB,EAAQ,IAAa,GAAG,KAAK,MAAM,CAAK,EAAE,KACvC,IAAI,EAAQ,IAAA,CAAM,QAAQ,CAAC,EAAE,GACxC"}
@@ -0,0 +1,8 @@
1
+ //#region src/perf/format.ts
2
+ function e(e) {
3
+ return !Number.isFinite(e) || e < 0 ? "—" : e < 1 ? "<1 ms" : e < 1e3 ? `${Math.round(e)} ms` : `${(e / 1e3).toFixed(2)} s`;
4
+ }
5
+ //#endregion
6
+ export { e as formatDurationMs };
7
+
8
+ //# sourceMappingURL=format.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"format.js","names":[],"sources":["../../src/perf/format.ts"],"sourcesContent":["/**\n * Rendering helpers for the numbers a profiler produces.\n */\n\n/**\n * Format a millisecond duration for display.\n *\n * Sub-second values keep millisecond resolution — the interesting range for a\n * single forward pass — and anything longer switches to seconds so a cold\n * start that pays a model download does not read as a five-digit number.\n * Durations under `1 ms` render as `\"<1 ms\"` rather than `\"0 ms\"`, which\n * would read as \"not measured\".\n *\n * @param value Duration in milliseconds.\n * @returns The formatted string, or `\"—\"` for a non-finite or negative input.\n *\n * @example\n * ```typescript\n * formatDurationMs(0.04); // \"<1 ms\"\n * formatDurationMs(142.6); // \"143 ms\"\n * formatDurationMs(4321); // \"4.32 s\"\n * formatDurationMs(NaN); // \"—\"\n * ```\n */\nexport function formatDurationMs(value: number): string {\n if (!Number.isFinite(value) || value < 0) return \"—\";\n if (value < 1) return \"<1 ms\";\n if (value < 1000) return `${Math.round(value)} ms`;\n return `${(value / 1000).toFixed(2)} s`;\n}\n"],"mappings":";AAwBA,SAAgB,EAAiB,GAAuB;CAIpD,OAHI,CAAC,OAAO,SAAS,CAAK,KAAK,IAAQ,IAAU,MAC7C,IAAQ,IAAU,UAClB,IAAQ,MAAa,GAAG,KAAK,MAAM,CAAK,EAAE,OACvC,IAAI,IAAQ,IAAA,CAAM,QAAQ,CAAC,EAAE;AACxC"}
@@ -0,0 +1,2 @@
1
+ const e=require("./cache-size.cjs"),t=require("./device.cjs");function n(){let n=performance.now(),r=new Map,i=(e,t)=>{r.set(e,(r.get(e)??0)+t)};return{async stage(e,t){let n=performance.now();try{return await t()}finally{i(e,performance.now()-n)}},stageSync(e,t){let n=performance.now();try{return t()}finally{i(e,performance.now()-n)}},mark(e,t){i(e,t)},async report(i={}){let a=performance.now()-n,o=await Promise.all((i.models??[]).map(async t=>({name:t.name,bytes:await e.cachedResponseBytes(t.cacheName,t.url)})));return{timings:Object.fromEntries(r),totalMs:a,device:t.readDeviceProfile(),models:o,measuredAt:Date.now()}}}}exports.createInferenceProfiler=n;
2
+ //# sourceMappingURL=profiler.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"profiler.cjs","names":[],"sources":["../../src/perf/profiler.ts"],"sourcesContent":["import { cachedResponseBytes } from \"./cache-size\";\nimport { readDeviceProfile } from \"./device\";\nimport type {\n InferenceProfiler,\n InferenceReport,\n InferenceReportOptions,\n ProfiledModelSize,\n} from \"./types\";\n\n/**\n * Timing and cost accounting for a pipeline that runs on the user's device.\n */\n\n/**\n * Create a profiler for one run of a pipeline.\n *\n * Wrap each step in {@link InferenceProfiler.stage}, fold in durations you\n * already have (an SDK `speed` breakdown, say) with\n * {@link InferenceProfiler.mark}, then call `report()` once the run finishes.\n *\n * Stages are timed independently rather than as a tiling of the run, so\n * concurrent work is charged its real wall-clock span to each stage and the\n * timings can sum to more than `totalMs`. Surface that to users when you\n * render the breakdown — a bar chart implying a partition of the total would\n * be wrong for a pipeline that overlaps stages.\n *\n * @returns A profiler bound to the moment it was created.\n *\n * @example\n * ```typescript\n * import { createInferenceProfiler } from \"tempest-react-sdk\";\n * import { Detector } from \"tempest-react-sdk/vision\";\n *\n * const profiler = createInferenceProfiler();\n * const detector = await profiler.stage(\"load-model\", () =>\n * Detector.create(\"/models/detect.onnx\"),\n * );\n * const results = await profiler.stage(\"detect\", () => detector.predict(blob));\n * profiler.mark(\"forward-pass\", results[0].speed.inference);\n *\n * const report = await profiler.report({\n * models: [\n * { name: \"detector\", cacheName: \"app-models\", url: \"/models/detect.onnx\" },\n * ],\n * });\n * console.log(report.timings, report.totalMs, report.device, report.models);\n * ```\n */\nexport function createInferenceProfiler(): InferenceProfiler {\n const startedAt = performance.now();\n const timings = new Map<string, number>();\n\n const add = (name: string, durationMs: number): void => {\n timings.set(name, (timings.get(name) ?? 0) + durationMs);\n };\n\n return {\n async stage<T>(name: string, run: () => Promise<T>): Promise<T> {\n const from = performance.now();\n try {\n return await run();\n } finally {\n add(name, performance.now() - from);\n }\n },\n\n stageSync<T>(name: string, run: () => T): T {\n const from = performance.now();\n try {\n return run();\n } finally {\n add(name, performance.now() - from);\n }\n },\n\n mark(name: string, durationMs: number): void {\n add(name, durationMs);\n },\n\n async report(options: InferenceReportOptions = {}): Promise<InferenceReport> {\n const totalMs = performance.now() - startedAt;\n const models: ProfiledModelSize[] = await Promise.all(\n (options.models ?? []).map(async (model) => ({\n name: model.name,\n bytes: await cachedResponseBytes(model.cacheName, model.url),\n })),\n );\n\n return {\n timings: Object.fromEntries(timings),\n totalMs,\n device: readDeviceProfile(),\n models,\n measuredAt: Date.now(),\n };\n },\n };\n}\n"],"mappings":"8DAgDA,SAAgB,GAA6C,CACzD,IAAM,EAAY,YAAY,IAAI,EAC5B,EAAU,IAAI,IAEd,GAAO,EAAc,IAA6B,CACpD,EAAQ,IAAI,GAAO,EAAQ,IAAI,CAAI,GAAK,GAAK,CAAU,CAC3D,EAEA,MAAO,CACH,MAAM,MAAS,EAAc,EAAmC,CAC5D,IAAM,EAAO,YAAY,IAAI,EAC7B,GAAI,CACA,OAAO,MAAM,EAAI,CACrB,QAAU,CACN,EAAI,EAAM,YAAY,IAAI,EAAI,CAAI,CACtC,CACJ,EAEA,UAAa,EAAc,EAAiB,CACxC,IAAM,EAAO,YAAY,IAAI,EAC7B,GAAI,CACA,OAAO,EAAI,CACf,QAAU,CACN,EAAI,EAAM,YAAY,IAAI,EAAI,CAAI,CACtC,CACJ,EAEA,KAAK,EAAc,EAA0B,CACzC,EAAI,EAAM,CAAU,CACxB,EAEA,MAAM,OAAO,EAAkC,CAAC,EAA6B,CACzE,IAAM,EAAU,YAAY,IAAI,EAAI,EAC9B,EAA8B,MAAM,QAAQ,KAC7C,EAAQ,QAAU,CAAC,EAAA,CAAG,IAAI,KAAO,KAAW,CACzC,KAAM,EAAM,KACZ,MAAO,MAAM,EAAA,oBAAoB,EAAM,UAAW,EAAM,GAAG,CAC/D,EAAE,CACN,EAEA,MAAO,CACH,QAAS,OAAO,YAAY,CAAO,EACnC,UACA,OAAQ,EAAA,kBAAkB,EAC1B,SACA,WAAY,KAAK,IAAI,CACzB,CACJ,CACJ,CACJ"}
@@ -0,0 +1,46 @@
1
+ import { cachedResponseBytes as e } from "./cache-size.js";
2
+ import { readDeviceProfile as t } from "./device.js";
3
+ //#region src/perf/profiler.ts
4
+ function n() {
5
+ let n = performance.now(), r = /* @__PURE__ */ new Map(), i = (e, t) => {
6
+ r.set(e, (r.get(e) ?? 0) + t);
7
+ };
8
+ return {
9
+ async stage(e, t) {
10
+ let n = performance.now();
11
+ try {
12
+ return await t();
13
+ } finally {
14
+ i(e, performance.now() - n);
15
+ }
16
+ },
17
+ stageSync(e, t) {
18
+ let n = performance.now();
19
+ try {
20
+ return t();
21
+ } finally {
22
+ i(e, performance.now() - n);
23
+ }
24
+ },
25
+ mark(e, t) {
26
+ i(e, t);
27
+ },
28
+ async report(i = {}) {
29
+ let a = performance.now() - n, o = await Promise.all((i.models ?? []).map(async (t) => ({
30
+ name: t.name,
31
+ bytes: await e(t.cacheName, t.url)
32
+ })));
33
+ return {
34
+ timings: Object.fromEntries(r),
35
+ totalMs: a,
36
+ device: t(),
37
+ models: o,
38
+ measuredAt: Date.now()
39
+ };
40
+ }
41
+ };
42
+ }
43
+ //#endregion
44
+ export { n as createInferenceProfiler };
45
+
46
+ //# sourceMappingURL=profiler.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"profiler.js","names":[],"sources":["../../src/perf/profiler.ts"],"sourcesContent":["import { cachedResponseBytes } from \"./cache-size\";\nimport { readDeviceProfile } from \"./device\";\nimport type {\n InferenceProfiler,\n InferenceReport,\n InferenceReportOptions,\n ProfiledModelSize,\n} from \"./types\";\n\n/**\n * Timing and cost accounting for a pipeline that runs on the user's device.\n */\n\n/**\n * Create a profiler for one run of a pipeline.\n *\n * Wrap each step in {@link InferenceProfiler.stage}, fold in durations you\n * already have (an SDK `speed` breakdown, say) with\n * {@link InferenceProfiler.mark}, then call `report()` once the run finishes.\n *\n * Stages are timed independently rather than as a tiling of the run, so\n * concurrent work is charged its real wall-clock span to each stage and the\n * timings can sum to more than `totalMs`. Surface that to users when you\n * render the breakdown — a bar chart implying a partition of the total would\n * be wrong for a pipeline that overlaps stages.\n *\n * @returns A profiler bound to the moment it was created.\n *\n * @example\n * ```typescript\n * import { createInferenceProfiler } from \"tempest-react-sdk\";\n * import { Detector } from \"tempest-react-sdk/vision\";\n *\n * const profiler = createInferenceProfiler();\n * const detector = await profiler.stage(\"load-model\", () =>\n * Detector.create(\"/models/detect.onnx\"),\n * );\n * const results = await profiler.stage(\"detect\", () => detector.predict(blob));\n * profiler.mark(\"forward-pass\", results[0].speed.inference);\n *\n * const report = await profiler.report({\n * models: [\n * { name: \"detector\", cacheName: \"app-models\", url: \"/models/detect.onnx\" },\n * ],\n * });\n * console.log(report.timings, report.totalMs, report.device, report.models);\n * ```\n */\nexport function createInferenceProfiler(): InferenceProfiler {\n const startedAt = performance.now();\n const timings = new Map<string, number>();\n\n const add = (name: string, durationMs: number): void => {\n timings.set(name, (timings.get(name) ?? 0) + durationMs);\n };\n\n return {\n async stage<T>(name: string, run: () => Promise<T>): Promise<T> {\n const from = performance.now();\n try {\n return await run();\n } finally {\n add(name, performance.now() - from);\n }\n },\n\n stageSync<T>(name: string, run: () => T): T {\n const from = performance.now();\n try {\n return run();\n } finally {\n add(name, performance.now() - from);\n }\n },\n\n mark(name: string, durationMs: number): void {\n add(name, durationMs);\n },\n\n async report(options: InferenceReportOptions = {}): Promise<InferenceReport> {\n const totalMs = performance.now() - startedAt;\n const models: ProfiledModelSize[] = await Promise.all(\n (options.models ?? []).map(async (model) => ({\n name: model.name,\n bytes: await cachedResponseBytes(model.cacheName, model.url),\n })),\n );\n\n return {\n timings: Object.fromEntries(timings),\n totalMs,\n device: readDeviceProfile(),\n models,\n measuredAt: Date.now(),\n };\n },\n };\n}\n"],"mappings":";;;AAgDA,SAAgB,IAA6C;CACzD,IAAM,IAAY,YAAY,IAAI,GAC5B,oBAAU,IAAI,IAAoB,GAElC,KAAO,GAAc,MAA6B;EACpD,EAAQ,IAAI,IAAO,EAAQ,IAAI,CAAI,KAAK,KAAK,CAAU;CAC3D;CAEA,OAAO;EACH,MAAM,MAAS,GAAc,GAAmC;GAC5D,IAAM,IAAO,YAAY,IAAI;GAC7B,IAAI;IACA,OAAO,MAAM,EAAI;GACrB,UAAU;IACN,EAAI,GAAM,YAAY,IAAI,IAAI,CAAI;GACtC;EACJ;EAEA,UAAa,GAAc,GAAiB;GACxC,IAAM,IAAO,YAAY,IAAI;GAC7B,IAAI;IACA,OAAO,EAAI;GACf,UAAU;IACN,EAAI,GAAM,YAAY,IAAI,IAAI,CAAI;GACtC;EACJ;EAEA,KAAK,GAAc,GAA0B;GACzC,EAAI,GAAM,CAAU;EACxB;EAEA,MAAM,OAAO,IAAkC,CAAC,GAA6B;GACzE,IAAM,IAAU,YAAY,IAAI,IAAI,GAC9B,IAA8B,MAAM,QAAQ,KAC7C,EAAQ,UAAU,CAAC,EAAA,CAAG,IAAI,OAAO,OAAW;IACzC,MAAM,EAAM;IACZ,OAAO,MAAM,EAAoB,EAAM,WAAW,EAAM,GAAG;GAC/D,EAAE,CACN;GAEA,OAAO;IACH,SAAS,OAAO,YAAY,CAAO;IACnC;IACA,QAAQ,EAAkB;IAC1B;IACA,YAAY,KAAK,IAAI;GACzB;EACJ;CACJ;AACJ"}