tempest-react-sdk 0.81.0 → 0.82.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 (179) hide show
  1. package/README.md +5 -6
  2. package/bin/create-tempest-app.e2e.test.mjs +31 -0
  3. package/bin/create-tempest-app.mjs +11 -1
  4. package/bin/lib/doctor/doctor.e2e.test.mjs +29 -0
  5. package/bin/lib/doctor/vitest.mjs +120 -0
  6. package/bin/lib/doctor/vitest.test.mjs +139 -0
  7. package/bin/lib/fs/contain.mjs +7 -0
  8. package/bin/lib/openapi/escape.mjs +68 -4
  9. package/bin/lib/openapi/generate.hostile.test.mjs +137 -0
  10. package/bin/lib/openapi/generate.mjs +78 -13
  11. package/bin/lib/openapi/pattern-risk.mjs +134 -0
  12. package/bin/lib/openapi/pattern-risk.test.mjs +45 -0
  13. package/bin/tempest-gen.test.mjs +100 -0
  14. package/bin/tempest.mjs +24 -8
  15. package/dist/access/use-can.cjs +1 -1
  16. package/dist/access/use-can.cjs.map +1 -1
  17. package/dist/access/use-can.js +25 -28
  18. package/dist/access/use-can.js.map +1 -1
  19. package/dist/auth/create-tempest-auth.cjs +1 -1
  20. package/dist/auth/create-tempest-auth.cjs.map +1 -1
  21. package/dist/auth/create-tempest-auth.js +192 -149
  22. package/dist/auth/create-tempest-auth.js.map +1 -1
  23. package/dist/auth/session-identity.cjs +2 -0
  24. package/dist/auth/session-identity.cjs.map +1 -0
  25. package/dist/auth/session-identity.js +12 -0
  26. package/dist/auth/session-identity.js.map +1 -0
  27. package/dist/br/boleto.cjs.map +1 -1
  28. package/dist/br/boleto.js.map +1 -1
  29. package/dist/components/AuthForm/AuthLinks.cjs +1 -1
  30. package/dist/components/AuthForm/AuthLinks.cjs.map +1 -1
  31. package/dist/components/AuthForm/AuthLinks.js +18 -15
  32. package/dist/components/AuthForm/AuthLinks.js.map +1 -1
  33. package/dist/components/AuthPage/AuthPage.cjs +1 -1
  34. package/dist/components/AuthPage/AuthPage.cjs.map +1 -1
  35. package/dist/components/AuthPage/AuthPage.js +58 -52
  36. package/dist/components/AuthPage/AuthPage.js.map +1 -1
  37. package/dist/components/Breadcrumbs/Breadcrumbs.cjs +1 -1
  38. package/dist/components/Breadcrumbs/Breadcrumbs.cjs.map +1 -1
  39. package/dist/components/Breadcrumbs/Breadcrumbs.js +22 -21
  40. package/dist/components/Breadcrumbs/Breadcrumbs.js.map +1 -1
  41. package/dist/components/Button/Button.cjs +1 -1
  42. package/dist/components/Button/Button.cjs.map +1 -1
  43. package/dist/components/Button/Button.js +41 -40
  44. package/dist/components/Button/Button.js.map +1 -1
  45. package/dist/components/Chat/ChatAttachments.cjs +1 -1
  46. package/dist/components/Chat/ChatAttachments.cjs.map +1 -1
  47. package/dist/components/Chat/ChatAttachments.js +38 -38
  48. package/dist/components/Form/Form.cjs +1 -1
  49. package/dist/components/Form/Form.cjs.map +1 -1
  50. package/dist/components/Form/Form.js +30 -32
  51. package/dist/components/Form/Form.js.map +1 -1
  52. package/dist/components/Layout/Layout.cjs +1 -1
  53. package/dist/components/Layout/Layout.cjs.map +1 -1
  54. package/dist/components/Layout/Layout.js +25 -24
  55. package/dist/components/Layout/Layout.js.map +1 -1
  56. package/dist/components/Layout/gap.cjs +2 -0
  57. package/dist/components/Layout/gap.cjs.map +1 -0
  58. package/dist/components/Layout/gap.js +15 -0
  59. package/dist/components/Layout/gap.js.map +1 -0
  60. package/dist/components/NavigationMenu/NavigationMenu.cjs +1 -1
  61. package/dist/components/NavigationMenu/NavigationMenu.cjs.map +1 -1
  62. package/dist/components/NavigationMenu/NavigationMenu.js +71 -70
  63. package/dist/components/NavigationMenu/NavigationMenu.js.map +1 -1
  64. package/dist/components/Sidebar/Sidebar.cjs.map +1 -1
  65. package/dist/components/Sidebar/Sidebar.js.map +1 -1
  66. package/dist/components/Sidebar/SidebarEntry.cjs +1 -1
  67. package/dist/components/Sidebar/SidebarEntry.cjs.map +1 -1
  68. package/dist/components/Sidebar/SidebarEntry.js +30 -29
  69. package/dist/components/Sidebar/SidebarEntry.js.map +1 -1
  70. package/dist/data/create-data-provider.cjs +1 -1
  71. package/dist/data/create-data-provider.cjs.map +1 -1
  72. package/dist/data/create-data-provider.js +1 -2
  73. package/dist/data/create-data-provider.js.map +1 -1
  74. package/dist/forms/validate-form.cjs +1 -1
  75. package/dist/forms/validate-form.cjs.map +1 -1
  76. package/dist/forms/validate-form.js +6 -1
  77. package/dist/forms/validate-form.js.map +1 -1
  78. package/dist/forms/zod-resolver.cjs +1 -1
  79. package/dist/forms/zod-resolver.cjs.map +1 -1
  80. package/dist/forms/zod-resolver.js +8 -3
  81. package/dist/forms/zod-resolver.js.map +1 -1
  82. package/dist/http/api-client.cjs +1 -1
  83. package/dist/http/api-client.cjs.map +1 -1
  84. package/dist/http/api-client.js +90 -72
  85. package/dist/http/api-client.js.map +1 -1
  86. package/dist/http/credential-scope.cjs +1 -1
  87. package/dist/http/credential-scope.cjs.map +1 -1
  88. package/dist/http/credential-scope.js +33 -9
  89. package/dist/http/credential-scope.js.map +1 -1
  90. package/dist/http/presigned-post.cjs.map +1 -1
  91. package/dist/http/presigned-post.js.map +1 -1
  92. package/dist/http/resumable-upload.cjs +1 -1
  93. package/dist/http/resumable-upload.cjs.map +1 -1
  94. package/dist/http/resumable-upload.js +90 -84
  95. package/dist/http/resumable-upload.js.map +1 -1
  96. package/dist/http/upload-with-progress.cjs +1 -1
  97. package/dist/http/upload-with-progress.cjs.map +1 -1
  98. package/dist/http/upload-with-progress.js +8 -8
  99. package/dist/http/upload-with-progress.js.map +1 -1
  100. package/dist/oauth/GoogleSignIn.cjs +1 -1
  101. package/dist/oauth/GoogleSignIn.cjs.map +1 -1
  102. package/dist/oauth/GoogleSignIn.js +5 -4
  103. package/dist/oauth/GoogleSignIn.js.map +1 -1
  104. package/dist/offline/create-offline-sync.cjs +1 -1
  105. package/dist/offline/create-offline-sync.cjs.map +1 -1
  106. package/dist/offline/create-offline-sync.js +87 -69
  107. package/dist/offline/create-offline-sync.js.map +1 -1
  108. package/dist/query/offline-persistence.cjs +1 -1
  109. package/dist/query/offline-persistence.cjs.map +1 -1
  110. package/dist/query/offline-persistence.js +54 -44
  111. package/dist/query/offline-persistence.js.map +1 -1
  112. package/dist/sse/create-event-stream.cjs +1 -1
  113. package/dist/sse/create-event-stream.cjs.map +1 -1
  114. package/dist/sse/create-event-stream.js +48 -41
  115. package/dist/sse/create-event-stream.js.map +1 -1
  116. package/dist/sse/ticket-event-stream.cjs +1 -1
  117. package/dist/sse/ticket-event-stream.cjs.map +1 -1
  118. package/dist/sse/ticket-event-stream.js +48 -19
  119. package/dist/sse/ticket-event-stream.js.map +1 -1
  120. package/dist/sse/use-event-stream.cjs +1 -1
  121. package/dist/sse/use-event-stream.cjs.map +1 -1
  122. package/dist/sse/use-event-stream.js +19 -14
  123. package/dist/sse/use-event-stream.js.map +1 -1
  124. package/dist/sw/background-sync.cjs +1 -1
  125. package/dist/sw/background-sync.cjs.map +1 -1
  126. package/dist/sw/background-sync.js +10 -8
  127. package/dist/sw/background-sync.js.map +1 -1
  128. package/dist/sw/cache.cjs +1 -1
  129. package/dist/sw/cache.cjs.map +1 -1
  130. package/dist/sw/cache.js +36 -30
  131. package/dist/sw/cache.js.map +1 -1
  132. package/dist/sw/create-push-handler.cjs +1 -1
  133. package/dist/sw/create-push-handler.cjs.map +1 -1
  134. package/dist/sw/create-push-handler.js +20 -10
  135. package/dist/sw/create-push-handler.js.map +1 -1
  136. package/dist/sw.d.ts +44 -13
  137. package/dist/tabular/compact.cjs +1 -1
  138. package/dist/tabular/compact.cjs.map +1 -1
  139. package/dist/tabular/compact.js +35 -16
  140. package/dist/tabular/compact.js.map +1 -1
  141. package/dist/tabular/manifest.cjs +1 -1
  142. package/dist/tabular/manifest.cjs.map +1 -1
  143. package/dist/tabular/manifest.js +33 -15
  144. package/dist/tabular/manifest.js.map +1 -1
  145. package/dist/tabular.d.ts +11 -1
  146. package/dist/tempest-react-sdk.cjs +1 -1
  147. package/dist/tempest-react-sdk.d.ts +457 -68
  148. package/dist/tempest-react-sdk.js +224 -224
  149. package/dist/theme/initial-theme.cjs +4 -4
  150. package/dist/theme/initial-theme.cjs.map +1 -1
  151. package/dist/theme/initial-theme.js +8 -5
  152. package/dist/theme/initial-theme.js.map +1 -1
  153. package/dist/utils/compressed-storage.cjs +1 -1
  154. package/dist/utils/compressed-storage.cjs.map +1 -1
  155. package/dist/utils/compressed-storage.js +13 -7
  156. package/dist/utils/compressed-storage.js.map +1 -1
  157. package/dist/utils/objects.cjs +1 -1
  158. package/dist/utils/objects.cjs.map +1 -1
  159. package/dist/utils/objects.js +13 -7
  160. package/dist/utils/objects.js.map +1 -1
  161. package/dist/utils/safe-url.cjs +1 -1
  162. package/dist/utils/safe-url.cjs.map +1 -1
  163. package/dist/utils/safe-url.js +4 -1
  164. package/dist/utils/safe-url.js.map +1 -1
  165. package/dist/webrtc/peer-mesh.cjs +1 -1
  166. package/dist/webrtc/peer-mesh.cjs.map +1 -1
  167. package/dist/webrtc/peer-mesh.js +7 -1
  168. package/dist/webrtc/peer-mesh.js.map +1 -1
  169. package/dist/ws/create-web-socket.cjs +1 -1
  170. package/dist/ws/create-web-socket.cjs.map +1 -1
  171. package/dist/ws/create-web-socket.js +77 -61
  172. package/dist/ws/create-web-socket.js.map +1 -1
  173. package/dist/ws/use-web-socket.cjs +1 -1
  174. package/dist/ws/use-web-socket.cjs.map +1 -1
  175. package/dist/ws/use-web-socket.js +4 -3
  176. package/dist/ws/use-web-socket.js.map +1 -1
  177. package/package.json +1 -1
  178. package/template-pwa/src/pwa.tsx +42 -0
  179. package/template-pwa/src/sw.ts +5 -4
@@ -1 +1 @@
1
- {"version":3,"file":"resumable-upload.cjs","names":["bytesToBase64","TempestApiError","isApiError","isRetriableStatus","buildApiError","ownerFingerprint","isTrustedCredentialTarget","csrfHeaders","generateIdempotencyKey","retry","require_errors","require_base64","require_credential_scope","require_csrf","require_retry","require_owner_fingerprint","require_idempotency","TUS_VERSION","DEFAULT_CHUNK_SIZE","ResumableUploadSupersededError","reason","clearGenerations","localGenerations","isUploadRecord","raw","value","base64Utf8","encodeMetadata","metadata","parts","name","uploadFingerprint","named","file","modified","endpoint","createLocalUploadStorage","backend","storage","prefix","key","record","store","owned","index","sendRequest","xhr","init","report","event","resolve","reject","parseOffset","response","parseErrorBody","text","RESYNCABLE_STATUSES","isRetriableChunkFailure","error","failed","body","envelope","hasDetail","detail","resolveUploadUrl","base","createResumableUpload","retryOptions","options","state","offset","url","idempotencyKey","owner","attached","generationOf","generation","assertCurrentOwner","getPrincipal","stopping","inFlight","resumedFrom","setState","next","onStateChange","onProgress","loaded","baseHeaders","result","headers","token","getToken","target","trustedOrigins","register","persist","probe","confirmed","ensureUpload","current","stored","creationHeaders","encoded","locationHeader","writeChunk","resync","end","chunkSize","from","run","again","attempt","guarded","stop","discard"],"sources":["../../src/http/resumable-upload.ts"],"sourcesContent":["/**\n * @tempest-limits file-lines, function-lines — a resumable upload is one long-lived\n * state machine: chunk the file, negotiate the offset the server already has, upload\n * with retry and backoff, honour pause, resume and abort, and report progress\n * throughout. Every stage reads the same cursor and the same abort signal, and\n * createResumableUpload is the closure that owns them.\n */\nimport { ownerFingerprint } from \"@/utils/owner-fingerprint\";\nimport { bytesToBase64 } from \"@/utils/base64\";\nimport { isTrustedCredentialTarget, reportSuppressedCredential } from \"./credential-scope\";\nimport { csrfHeaders } from \"./csrf\";\nimport type { CsrfOptions } from \"./csrf\";\nimport { buildApiError, isApiError, isRetriableStatus, 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 * Thrown by `start()`/`resume()` when the run can no longer go on as the\n * account that started it.\n *\n * - `\"principal\"` — `getPrincipal` names someone else than when the run\n * attached: the next chunk would carry the new account's token to the\n * previous account's upload URL, and the record would be stamped for the\n * wrong owner.\n * - `\"cleared\"` — `createLocalUploadStorage().clear()` ran for this storage's\n * prefix (typically in `onSessionEnd`): writing the record back would undo\n * the clear.\n *\n * Not a pause: the run cannot be resumed as the new account. The state moves\n * to `\"error\"`, and the previous owner's record is left as it was.\n */\nexport class ResumableUploadSupersededError extends Error {\n /** Why the run stopped. */\n readonly reason: \"principal\" | \"cleared\";\n\n /**\n * @param reason - Why the run stopped.\n */\n constructor(reason: \"principal\" | \"cleared\") {\n super(\n reason === \"principal\"\n ? \"O usuário mudou durante o upload resumível.\"\n : \"Os registros de upload resumível foram limpos durante o upload.\",\n );\n this.name = \"ResumableUploadSupersededError\";\n this.reason = reason;\n }\n}\n\n/**\n * How many times `clear()` ran per local-storage prefix, so a run can tell its\n * record was cleared under it — even through another\n * `createLocalUploadStorage()` object with the same prefix, which is what an\n * `onSessionEnd` builds.\n */\nconst clearGenerations = new Map<string, number>();\n\n/**\n * The clear generation reader of each storage built by\n * `createLocalUploadStorage`. A custom storage has none, and its runs only\n * stop on a principal change.\n */\nconst localGenerations = new WeakMap<ResumableUploadStorage, () => number>();\n\n/**\n * Whether a stored value has the shape of a {@link ResumableUploadRecord}.\n *\n * `clear()` matches keys by prefix, and a prefix with no delimiter (`\"app\"`)\n * also matches an app's own keys (`\"appSettings\"`). Changing how keys are\n * built would orphan every record already stored under a custom prefix, so\n * `clear()` removes only values this storage could have written.\n *\n * @param raw - The stored string.\n * @returns Whether it parses as a record.\n */\nfunction isUploadRecord(raw: string | null): boolean {\n if (!raw) return false;\n try {\n const value = JSON.parse(raw) as Partial<ResumableUploadRecord> | null;\n return (\n typeof value === \"object\" &&\n value !== null &&\n typeof value.url === \"string\" &&\n typeof value.offset === \"number\" &&\n typeof value.size === \"number\" &&\n typeof value.idempotencyKey === \"string\"\n );\n } catch {\n return false;\n }\n}\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 * One-way fingerprint of the principal that created the upload (`\"p:<hex>\"`),\n * `null` for an anonymous one. Absent when the upload ran without\n * {@link ResumableUploadOptions.getPrincipal}, and on records written before\n * 0.78.0.\n */\n owner?: string | null;\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/**\n * The default `localStorage` storage, which can also forget every record it\n * holds.\n */\nexport interface LocalUploadStorage extends ResumableUploadStorage {\n /**\n * Forget every record under this storage's prefix — the call for\n * `onSessionEnd`, so the next account on the browser does not find the\n * previous one's upload URLs. Synchronous; a no-op without `localStorage`.\n *\n * Only values shaped like a record are removed, so a prefix without a\n * delimiter does not take the app's own keys with it. A run still going on\n * this prefix stops before its next chunk with\n * {@link ResumableUploadSupersededError} (`\"cleared\"`) instead of writing\n * its record back.\n */\n clear(): 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 /**\n * Who is signed in — a user id, or `null`/`undefined` for nobody — read when\n * `start()`/`resume()` attaches to the upload. The same getter the error\n * reporter and `provideBackgroundSyncCredentials` take.\n *\n * The resume record is stamped with a one-way fingerprint of it, and a\n * record stamped by anyone else — another user, nobody, or no stamp at all\n * — is deleted instead of resumed: its upload URL is not probed, and its\n * `Idempotency-Key` is never replayed. Without it, the record is bound to\n * the file alone (endpoint, name, size, type, mtime), so after user A\n * signed out leaving an upload half-done, user B picking an identical file\n * sent `HEAD`/`PATCH` to A's upload URL with B's token, and on refusal\n * replayed A's `Idempotency-Key` with B's token (#479). Pass it on every\n * app with more than one account per browser, and also clear the storage\n * at session end (`createLocalUploadStorage().clear()` in `onSessionEnd`).\n *\n * It is read again before every chunk and every record write: when it\n * names someone else mid-run, the run stops with\n * {@link ResumableUploadSupersededError} (`\"principal\"`) before the new\n * account's token reaches the previous one's upload URL. Without it, call\n * `abort()` on the uploads in progress from `onSessionEnd`.\n */\n getPrincipal?: () => string | number | null | undefined;\n /**\n * Origins besides `endpoint`'s that may receive the `getToken` credential.\n *\n * Since 0.66.0 the bearer token is scoped to the origin of `endpoint`, and\n * the creation response's `Location` no longer decides where it goes. A\n * server that hands the upload to object storage on another host still\n * works — the `PATCH` requests simply carry no `Authorization`, which is\n * what a presigned storage URL expects anyway.\n *\n * List the storage origin here when it does need the API's token.\n */\n trustedOrigins?: readonly string[];\n /** Send cookies. Default `false`. */\n withCredentials?: boolean;\n /**\n * Send a CSRF token on the creation `POST`, every chunk `PATCH` and the\n * discarding `DELETE` — never on the offset `HEAD`. Off by default; `true`\n * reads the `csrf_token` cookie into `X-CSRF-Token`, as `createApiClient`\n * does.\n *\n * Scoped like the bearer token, to `endpoint`'s origin plus\n * {@link trustedOrigins}: a `Location` pointing at object storage on\n * another host gets neither.\n */\n csrf?: boolean | CsrfOptions;\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. Only that step is specific here — the\n * bytes-to-text half is {@link bytesToBase64}.\n *\n * @param value - Text to encode.\n * @returns Padded base64.\n */\nfunction base64Utf8(value: string): string {\n return bytesToBase64(new TextEncoder().encode(value));\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 * `clear()` forgets every record under the prefix. Call it from\n * `onSessionEnd`: a record outlives the session that wrote it, and only\n * completing the upload or `abort({ discard: true })` removes it otherwise.\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:\"): LocalUploadStorage {\n function backend(): Storage | null {\n try {\n return typeof localStorage === \"undefined\" ? null : localStorage;\n } catch {\n return null;\n }\n }\n\n const storage: LocalUploadStorage = {\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 clear() {\n clearGenerations.set(prefix, (clearGenerations.get(prefix) ?? 0) + 1);\n const store = backend();\n if (!store) return;\n const owned: string[] = [];\n for (let index = 0; index < store.length; index += 1) {\n const name = store.key(index);\n if (name?.startsWith(prefix) && isUploadRecord(store.getItem(name))) {\n owned.push(name);\n }\n }\n for (const name of owned) store.removeItem(name);\n },\n };\n localGenerations.set(storage, () => clearGenerations.get(prefix) ?? 0);\n return storage;\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 */\n/**\n * The two statuses a chunk retry fixes that the shared policy cannot know about.\n *\n * `409` and `412` are the offset-divergence answers, and they are the entire\n * reason `resync` exists: the next attempt re-reads the server's offset with\n * `HEAD` and writes from there. They are 4xx refusals a replay genuinely fixes,\n * which is the one thing {@link isRetriableStatus} has no way to tell — from\n * outside this protocol they look like any other deliberate rejection.\n */\nconst RESYNCABLE_STATUSES: ReadonlySet<number> = new Set([409, 412]);\n\n/**\n * Whether a chunk failure is worth another attempt.\n *\n * The default used to be `true` for everything, which cost five round trips\n * before surfacing an answer the first one already gave. Two groups matter here\n * and both are specific to the resume protocol:\n *\n * - **`409`/`412` retry**, even though the shared policy rejects 4xx: they mean\n * \"your offset is wrong\", and `resync` is how the next attempt fixes it.\n * - **`404`/`410` do not**, even though a lost resource can look transient.\n * `probe()` turns them into \"O upload expirou no servidor. Comece de novo.\" and\n * recreating the upload only happens in `ensureUpload`, at attach time — never\n * inside the chunk loop. So a retry here re-runs `HEAD` against a resource that\n * is gone, five times, and then reports the same thing with the backoff added\n * on top.\n *\n * Anything with no API shape still retries: a transport failure has no status to\n * judge, and losing a large upload to one dropped connection is the outcome this\n * whole module exists to avoid.\n *\n * @param error - Whatever the attempt threw.\n * @returns Whether the chunk loop should try again.\n */\nfunction isRetriableChunkFailure(error: unknown): boolean {\n if (!isApiError(error)) return true;\n if (RESYNCABLE_STATUSES.has(error.status)) return true;\n return isRetriableStatus(error.status);\n}\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 getPrincipal,\n trustedOrigins,\n withCredentials = false,\n csrf,\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 owner: string | null | undefined;\n let attached = false;\n const generationOf = storage ? localGenerations.get(storage) : undefined;\n let generation = generationOf?.() ?? 0;\n\n /**\n * Throw when the run can no longer go on as the account that attached it:\n * the principal changed, or the local storage was cleared under it.\n *\n * @throws {ResumableUploadSupersededError} In either case.\n */\n function assertCurrentOwner(): void {\n if (getPrincipal && ownerFingerprint(\"p\", getPrincipal()) !== owner) {\n throw new ResumableUploadSupersededError(\"principal\");\n }\n if (generationOf && generationOf() !== generation) {\n throw new ResumableUploadSupersededError(\"cleared\");\n }\n }\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 /**\n * Headers every tus request carries, with the credential scoped to the\n * endpoint's origin.\n *\n * The target is a parameter because after creation it is not ours: tus\n * answers `POST {endpoint}` with a `Location` the server chooses, and the\n * spec allows an absolute URL on another host — handing the upload to\n * object storage is the ordinary deployment, not an attack. Before 0.66.0\n * the bearer token followed that header wherever it pointed, along with the\n * file bytes.\n *\n * The CSRF token follows the same scope, and only on the methods that\n * write — which is why the method is a parameter too.\n *\n * @param target - The URL this particular request goes to.\n * @param method - The HTTP method of this request.\n * @returns The headers to send.\n */\n function baseHeaders(target: string, method: string): Record<string, string> {\n const result: Record<string, string> = { ...headers, \"Tus-Resumable\": TUS_VERSION };\n const token = getToken?.();\n if (token && !(\"Authorization\" in result)) {\n if (isTrustedCredentialTarget(target, endpoint, trustedOrigins)) {\n result.Authorization = `Bearer ${token}`;\n } else {\n reportSuppressedCredential(target, endpoint);\n }\n }\n Object.assign(\n result,\n csrfHeaders({\n method,\n url: target,\n reference: endpoint,\n csrf,\n trustedOrigins,\n headers,\n }),\n );\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 assertCurrentOwner();\n await storage.set(key, {\n url,\n offset,\n size: file.size,\n idempotencyKey,\n updatedAt: Date.now(),\n ...(owner === undefined ? {} : { owner }),\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(target, \"HEAD\"),\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 * With `getPrincipal`, it is also only trusted when it carries the current\n * principal's fingerprint; anyone else's is deleted, and the creation that\n * follows gets a fresh `Idempotency-Key`. The key this handle kept in memory\n * from an earlier run is reused only while the principal is the same, which\n * is what keeps creation idempotent across `resume()` without storage.\n */\n async function ensureUpload(): Promise<string> {\n const current = getPrincipal ? ownerFingerprint(\"p\", getPrincipal()) : undefined;\n if (attached && current !== owner) idempotencyKey = null;\n owner = current;\n attached = true;\n generation = generationOf?.() ?? 0;\n let stored = storage ? await storage.get(key) : null;\n if (stored && owner !== undefined && stored.owner !== owner) {\n await storage?.delete(key);\n stored = null;\n }\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 ...(owner === undefined ? {} : { owner }),\n });\n }\n\n const creationHeaders: Record<string, string> = {\n ...baseHeaders(endpoint, \"POST\"),\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 assertCurrentOwner();\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(target, \"PATCH\"),\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 * `resync` is armed only when the attempt is actually going to happen. A\n * caller's own `shouldRetry` still wins the decision, and still arms the\n * resync when it says yes — the flag describes what the *next* attempt must\n * do, so setting it for an attempt that never comes describes nothing.\n * {@link isRetriableChunkFailure} is the default, and it is where `409`/`412`\n * earn a retry the shared policy would refuse and `404`/`410` lose one it\n * would have granted.\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 ResumableUploadSupersededError) return false;\n if (error instanceof DOMException && error.name === \"AbortError\") return false;\n const again =\n retryOptions?.shouldRetry?.(error, attempt) ??\n isRetriableChunkFailure(error);\n if (again) resync.needed = true;\n return again;\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(url, \"DELETE\"),\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":"A,iOAiBA,IAAaiB,EAAc,QAGdC,EAAqB,QAiBrBC,EAAb,cAAoD,KAAM,CAEtD,OAKA,YAAY,EAAiC,CACzC,MACIC,IAAW,YACL,8CACA,iEACV,EACA,KAAK,KAAO,iCACZ,KAAK,OAASA,CAClB,CACJ,EAQMC,EAAmB,IAAI,IAOvBC,EAAmB,IAAI,QAa7B,SAASC,EAAe,EAA6B,CACjD,GAAI,CAACC,EAAK,MAAO,GACjB,GAAI,CACA,IAAMC,EAAQ,KAAK,MAAMD,CAAG,EAC5B,OACI,OAAOC,GAAU,YACjBA,GACA,OAAOA,EAAM,KAAQ,UACrB,OAAOA,EAAM,QAAW,UACxB,OAAOA,EAAM,MAAS,UACtB,OAAOA,EAAM,gBAAmB,QAExC,MAAQ,CACJ,MAAO,EACX,CACJ,CAuNA,SAASC,EAAW,EAAuB,CACvC,OAAO1B,EAAAA,cAAc,IAAI,YAAY,CAAC,CAAC,OAAOyB,CAAK,CAAC,CACxD,CAQA,SAASE,EAAe,EAA6D,CACjF,GAAI,CAACC,EAAU,OAAO,KACtB,IAAMC,EAAQ,OAAO,QAAQD,CAAQ,CAAC,CAAC,KAAK,CAACE,EAAML,KA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X,EACA,IAAI,KAAM,CACN,OAAOC,CACX,EACA,KACJ,CACJ,C"}
1
+ {"version":3,"file":"resumable-upload.cjs","names":["bytesToBase64","TempestApiError","isApiError","isRetriableStatus","buildApiError","resolveRequestUrl","sessionIdentityOf","ownerFingerprint","isTrustedCredentialTarget","csrfHeaders","generateIdempotencyKey","retry","require_errors","require_base64","require_credential_scope","require_csrf","require_retry","require_session_identity","require_owner_fingerprint","require_idempotency","TUS_VERSION","DEFAULT_CHUNK_SIZE","ResumableUploadSupersededError","reason","clearGenerations","localGenerations","isUploadRecord","raw","value","base64Utf8","encodeMetadata","metadata","parts","name","uploadFingerprint","named","file","modified","endpoint","createLocalUploadStorage","backend","storage","prefix","key","record","store","owned","index","sendRequest","xhr","init","report","event","resolve","reject","parseOffset","response","parseErrorBody","text","RESYNCABLE_STATUSES","isRetriableChunkFailure","error","failed","body","envelope","hasDetail","detail","resolveUploadUrl","createResumableUpload","principalOption","retryOptions","options","getPrincipal","getToken","state","offset","url","idempotencyKey","owner","attached","generationOf","generation","currentOwner","assertCurrentOwner","stopping","inFlight","resumedFrom","setState","next","onStateChange","onProgress","loaded","baseHeaders","inScope","target","trustedOrigins","result","headers","token","register","persist","probe","confirmed","ensureUpload","current","ownUrl","stored","ownRecord","creationHeaders","encoded","locationHeader","writeChunk","resync","end","chunkSize","from","run","again","attempt","guarded","stop","discard"],"sources":["../../src/http/resumable-upload.ts"],"sourcesContent":["/**\n * @tempest-limits file-lines, function-lines — a resumable upload is one long-lived\n * state machine: chunk the file, negotiate the offset the server already has, upload\n * with retry and backoff, honour pause, resume and abort, and report progress\n * throughout. Every stage reads the same cursor and the same abort signal, and\n * createResumableUpload is the closure that owns them.\n */\nimport { sessionIdentityOf } from \"@/auth/session-identity\";\nimport { ownerFingerprint } from \"@/utils/owner-fingerprint\";\nimport { bytesToBase64 } from \"@/utils/base64\";\nimport {\n isTrustedCredentialTarget,\n reportSuppressedCredential,\n resolveRequestUrl,\n} from \"./credential-scope\";\nimport { csrfHeaders } from \"./csrf\";\nimport type { CsrfOptions } from \"./csrf\";\nimport { buildApiError, isApiError, isRetriableStatus, 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 * Thrown by `start()`/`resume()` when the run can no longer go on as the\n * account that started it.\n *\n * - `\"principal\"` — `getPrincipal` names someone else than when the run\n * attached: the next chunk would carry the new account's token to the\n * previous account's upload URL, and the record would be stamped for the\n * wrong owner.\n * - `\"cleared\"` — `createLocalUploadStorage().clear()` ran for this storage's\n * prefix (typically in `onSessionEnd`): writing the record back would undo\n * the clear.\n *\n * Not a pause: the run cannot be resumed as the new account. The state moves\n * to `\"error\"`, and the previous owner's record is left as it was.\n */\nexport class ResumableUploadSupersededError extends Error {\n /** Why the run stopped. */\n readonly reason: \"principal\" | \"cleared\";\n\n /**\n * @param reason - Why the run stopped.\n */\n constructor(reason: \"principal\" | \"cleared\") {\n super(\n reason === \"principal\"\n ? \"O usuário mudou durante o upload resumível.\"\n : \"Os registros de upload resumível foram limpos durante o upload.\",\n );\n this.name = \"ResumableUploadSupersededError\";\n this.reason = reason;\n }\n}\n\n/**\n * How many times `clear()` ran per local-storage prefix, so a run can tell its\n * record was cleared under it — even through another\n * `createLocalUploadStorage()` object with the same prefix, which is what an\n * `onSessionEnd` builds.\n */\nconst clearGenerations = new Map<string, number>();\n\n/**\n * The clear generation reader of each storage built by\n * `createLocalUploadStorage`. A custom storage has none, and its runs only\n * stop on a principal change.\n */\nconst localGenerations = new WeakMap<ResumableUploadStorage, () => number>();\n\n/**\n * Whether a stored value has the shape of a {@link ResumableUploadRecord}.\n *\n * `clear()` matches keys by prefix, and a prefix with no delimiter (`\"app\"`)\n * also matches an app's own keys (`\"appSettings\"`). Changing how keys are\n * built would orphan every record already stored under a custom prefix, so\n * `clear()` removes only values this storage could have written.\n *\n * @param raw - The stored string.\n * @returns Whether it parses as a record.\n */\nfunction isUploadRecord(raw: string | null): boolean {\n if (!raw) return false;\n try {\n const value = JSON.parse(raw) as Partial<ResumableUploadRecord> | null;\n return (\n typeof value === \"object\" &&\n value !== null &&\n typeof value.url === \"string\" &&\n typeof value.offset === \"number\" &&\n typeof value.size === \"number\" &&\n typeof value.idempotencyKey === \"string\"\n );\n } catch {\n return false;\n }\n}\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 * One-way fingerprint of the principal that created the upload (`\"p:<hex>\"`)\n * or, without {@link ResumableUploadOptions.getPrincipal}, of the bearer\n * token of its last write (`\"t:<hex>\"`, since 0.82.0); `null` for an\n * anonymous one. Absent when the upload ran with neither getter, and on\n * records written before 0.78.0.\n */\n owner?: string | null;\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/**\n * The default `localStorage` storage, which can also forget every record it\n * holds.\n */\nexport interface LocalUploadStorage extends ResumableUploadStorage {\n /**\n * Forget every record under this storage's prefix — the call for\n * `onSessionEnd`, so the next account on the browser does not find the\n * previous one's upload URLs. Synchronous; a no-op without `localStorage`.\n *\n * Only values shaped like a record are removed, so a prefix without a\n * delimiter does not take the app's own keys with it. A run still going on\n * this prefix stops before its next chunk with\n * {@link ResumableUploadSupersededError} (`\"cleared\"`) instead of writing\n * its record back.\n */\n clear(): 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 /**\n * Extra headers on every request inside the credential scope — the\n * `endpoint`'s origin plus {@link trustedOrigins}. A `Location` on another\n * host gets only the tus headers, never these (since 0.82.0).\n */\n headers?: Record<string, string>;\n /** Returns the current bearer token, read before each request. */\n getToken?: () => string | null | undefined;\n /**\n * Who is signed in — a user id, or `null`/`undefined` for nobody — read when\n * `start()`/`resume()` attaches to the upload. The same getter the error\n * reporter and `provideBackgroundSyncCredentials` take.\n *\n * The resume record is stamped with a one-way fingerprint of it, and a\n * record stamped by anyone else — another user, nobody, or no stamp at all\n * — is deleted instead of resumed: its upload URL is not probed, and its\n * `Idempotency-Key` is never replayed (#479).\n *\n * Without it, since 0.82.0 the record is bound to a fingerprint of the\n * `getToken` token instead, so another account's record is still never\n * adopted (#528) — but a token rotates: a reload after a refresh that no\n * chunk landed under starts the upload over. Pass `getPrincipal` to keep\n * resuming across refreshes, and always with a cookie session, where there\n * is no token to bind to and the record stays unbound.\n *\n * `getToken: auth.getToken` — the getter of `createTempestAuth` itself, not\n * an arrow around it — binds to that preset's session instead, as if\n * `getPrincipal: auth.sessionKey` were passed: the record survives token\n * rotation, a switch of account stops the run, and a new `login()`, even\n * into the same account, starts over.\n *\n * It is read again before every chunk and every record write: when it\n * names someone else mid-run, the run stops with\n * {@link ResumableUploadSupersededError} (`\"principal\"`) before the new\n * account's token reaches the previous one's upload URL. Without it, call\n * `abort()` on the uploads in progress from `onSessionEnd`.\n */\n getPrincipal?: () => string | number | null | undefined;\n /**\n * Origins besides `endpoint`'s that may receive the `getToken` credential.\n *\n * Since 0.66.0 the bearer token is scoped to the origin of `endpoint`, and\n * the creation response's `Location` no longer decides where it goes. A\n * server that hands the upload to object storage on another host still\n * works — the `PATCH` requests simply carry no `Authorization`, which is\n * what a presigned storage URL expects anyway.\n *\n * List the storage origin here when it does need the API's token.\n */\n trustedOrigins?: readonly string[];\n /** Send cookies. Default `false`. */\n withCredentials?: boolean;\n /**\n * Send a CSRF token on the creation `POST`, every chunk `PATCH` and the\n * discarding `DELETE` — never on the offset `HEAD`. Off by default; `true`\n * reads the `csrf_token` cookie into `X-CSRF-Token`, as `createApiClient`\n * does.\n *\n * Scoped like the bearer token, to `endpoint`'s origin plus\n * {@link trustedOrigins}: a `Location` pointing at object storage on\n * another host gets neither.\n */\n csrf?: boolean | CsrfOptions;\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. Only that step is specific here — the\n * bytes-to-text half is {@link bytesToBase64}.\n *\n * @param value - Text to encode.\n * @returns Padded base64.\n */\nfunction base64Utf8(value: string): string {\n return bytesToBase64(new TextEncoder().encode(value));\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 * `clear()` forgets every record under the prefix. Call it from\n * `onSessionEnd`: a record outlives the session that wrote it, and only\n * completing the upload or `abort({ discard: true })` removes it otherwise.\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:\"): LocalUploadStorage {\n function backend(): Storage | null {\n try {\n return typeof localStorage === \"undefined\" ? null : localStorage;\n } catch {\n return null;\n }\n }\n\n const storage: LocalUploadStorage = {\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 clear() {\n clearGenerations.set(prefix, (clearGenerations.get(prefix) ?? 0) + 1);\n const store = backend();\n if (!store) return;\n const owned: string[] = [];\n for (let index = 0; index < store.length; index += 1) {\n const name = store.key(index);\n if (name?.startsWith(prefix) && isUploadRecord(store.getItem(name))) {\n owned.push(name);\n }\n }\n for (const name of owned) store.removeItem(name);\n },\n };\n localGenerations.set(storage, () => clearGenerations.get(prefix) ?? 0);\n return storage;\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 */\n/**\n * The two statuses a chunk retry fixes that the shared policy cannot know about.\n *\n * `409` and `412` are the offset-divergence answers, and they are the entire\n * reason `resync` exists: the next attempt re-reads the server's offset with\n * `HEAD` and writes from there. They are 4xx refusals a replay genuinely fixes,\n * which is the one thing {@link isRetriableStatus} has no way to tell — from\n * outside this protocol they look like any other deliberate rejection.\n */\nconst RESYNCABLE_STATUSES: ReadonlySet<number> = new Set([409, 412]);\n\n/**\n * Whether a chunk failure is worth another attempt.\n *\n * The default used to be `true` for everything, which cost five round trips\n * before surfacing an answer the first one already gave. Two groups matter here\n * and both are specific to the resume protocol:\n *\n * - **`409`/`412` retry**, even though the shared policy rejects 4xx: they mean\n * \"your offset is wrong\", and `resync` is how the next attempt fixes it.\n * - **`404`/`410` do not**, even though a lost resource can look transient.\n * `probe()` turns them into \"O upload expirou no servidor. Comece de novo.\" and\n * recreating the upload only happens in `ensureUpload`, at attach time — never\n * inside the chunk loop. So a retry here re-runs `HEAD` against a resource that\n * is gone, five times, and then reports the same thing with the backoff added\n * on top.\n *\n * Anything with no API shape still retries: a transport failure has no status to\n * judge, and losing a large upload to one dropped connection is the outcome this\n * whole module exists to avoid.\n *\n * @param error - Whatever the attempt threw.\n * @returns Whether the chunk loop should try again.\n */\nfunction isRetriableChunkFailure(error: unknown): boolean {\n if (!isApiError(error)) return true;\n if (RESYNCABLE_STATUSES.has(error.status)) return true;\n return isRetriableStatus(error.status);\n}\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 creation endpoint, so a relative\n * 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 * The base is the URL the creation `POST` went to, as RFC 9110 §10.2.2 says\n * for `Location`, resolved the way the transport resolved it. Until 0.82.0 it\n * was the page's address: with an absolute `endpoint` on a tus host, a\n * `Location: /files/abc` pointed the chunks at the app's own origin (#530).\n *\n * @param value - The raw `Location` header.\n * @param endpoint - The creation endpoint the `POST` went to.\n * @returns An absolute URL, or the input when there is no base to resolve against.\n */\nfunction resolveUploadUrl(value: string, endpoint: string): string {\n try {\n return new URL(value, resolveRequestUrl(endpoint) ?? undefined).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 getPrincipal: principalOption,\n trustedOrigins,\n withCredentials = false,\n csrf,\n key = uploadFingerprint(endpoint, file),\n storage = createLocalUploadStorage(),\n retry: retryOptions,\n onProgress,\n onStateChange,\n } = options;\n const getPrincipal = principalOption ?? sessionIdentityOf(getToken)?.current;\n\n let state: ResumableUploadState = \"idle\";\n let offset = 0;\n let url: string | null = null;\n let idempotencyKey: string | null = null;\n let owner: string | null | undefined;\n let attached = false;\n const generationOf = storage ? localGenerations.get(storage) : undefined;\n let generation = generationOf?.() ?? 0;\n\n /**\n * Who the resume record belongs to right now, as the fingerprint it is\n * stamped with.\n *\n * `getPrincipal` wins when given (`\"p:…\"`), and so does the session of a\n * `getToken` that `createTempestAuth` handed out, read as its principal.\n * Without either, a `getToken` getter\n * still names the credential every request carries, so the record is bound\n * to a fingerprint of the token (`\"t:…\"`) — never the token itself. Until\n * 0.82.0 a record written without `getPrincipal` had no owner at all and\n * was adopted by whoever picked an identical file next: `HEAD`/`PATCH` with\n * their token to the previous user's upload URL, and the previous user's\n * `Idempotency-Key` replayed on their creation (#528).\n *\n * A token rotates, a principal does not, which is why `getPrincipal` is\n * still the better binding: a reload after a refresh that happened while\n * no chunk was landing starts the upload over. `undefined` — no binding —\n * only when there is neither getter: an anonymous upload, or a cookie\n * session the SDK cannot see.\n *\n * @returns The fingerprint, `null` for nobody, `undefined` for unbound.\n */\n function currentOwner(): string | null | undefined {\n if (getPrincipal) return ownerFingerprint(\"p\", getPrincipal());\n if (getToken) return ownerFingerprint(\"t\", getToken());\n return undefined;\n }\n\n /**\n * Throw when the run can no longer go on as the account that attached it:\n * the principal changed, or the local storage was cleared under it.\n *\n * @throws {ResumableUploadSupersededError} In either case.\n */\n function assertCurrentOwner(): void {\n if (getPrincipal && ownerFingerprint(\"p\", getPrincipal()) !== owner) {\n throw new ResumableUploadSupersededError(\"principal\");\n }\n if (generationOf && generationOf() !== generation) {\n throw new ResumableUploadSupersededError(\"cleared\");\n }\n }\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 /**\n * Headers every tus request carries, with the credential scoped to the\n * endpoint's origin.\n *\n * The target is a parameter because after creation it is not ours: tus\n * answers `POST {endpoint}` with a `Location` the server chooses, and the\n * spec allows an absolute URL on another host — handing the upload to\n * object storage is the ordinary deployment, not an attack. Before 0.66.0\n * the bearer token followed that header wherever it pointed, along with the\n * file bytes.\n *\n * The CSRF token follows the same scope, and only on the methods that\n * write — which is why the method is a parameter too. So do the static\n * `headers` since 0.82.0: an `X-Api-Key` there is a credential, and until\n * then it went to a foreign `Location` along with the bytes (#530).\n *\n * @param target - The URL this particular request goes to.\n * @param method - The HTTP method of this request.\n * @returns The headers to send.\n */\n function baseHeaders(target: string, method: string): Record<string, string> {\n const inScope = isTrustedCredentialTarget(target, endpoint, trustedOrigins);\n const result: Record<string, string> = {\n ...(inScope ? headers : {}),\n \"Tus-Resumable\": TUS_VERSION,\n };\n const token = getToken?.();\n if (token && !(\"Authorization\" in headers)) {\n if (inScope) {\n result.Authorization = `Bearer ${token}`;\n } else {\n reportSuppressedCredential(target, endpoint);\n }\n }\n Object.assign(\n result,\n csrfHeaders({\n method,\n url: target,\n reference: endpoint,\n csrf,\n trustedOrigins,\n headers,\n }),\n );\n return result;\n }\n\n function register(xhr: XMLHttpRequest): void {\n inFlight = xhr;\n }\n\n /**\n * Write the resume record, stamped with whoever owns it now.\n *\n * Restamped on every write rather than fixed at attach, so a token refresh\n * mid-upload does not orphan the record: the next reload, with the new\n * token, still resumes it. With `getPrincipal` the stamp cannot drift —\n * {@link assertCurrentOwner} stops the run first.\n */\n async function persist(): Promise<void> {\n if (!storage || !url || !idempotencyKey) return;\n assertCurrentOwner();\n owner = currentOwner();\n await storage.set(key, {\n url,\n offset,\n size: file.size,\n idempotencyKey,\n updatedAt: Date.now(),\n ...(owner === undefined ? {} : { owner }),\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(target, \"HEAD\"),\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 * It is also only trusted when it carries the current owner's fingerprint\n * (see {@link currentOwner}); anyone else's is deleted, and the creation\n * that follows gets a fresh `Idempotency-Key`. With `getPrincipal`, the key\n * this handle kept in memory from an earlier run is reused only while the\n * principal is the same, which is what keeps creation idempotent across\n * `resume()` without storage.\n *\n * Bound by token, the handle's own record is the exception: a `resume()`\n * after a refresh finds the record it wrote itself, stamped with the token\n * of its last write, and continues it instead of starting over.\n */\n async function ensureUpload(): Promise<string> {\n const current = currentOwner();\n if (attached && getPrincipal && current !== owner) idempotencyKey = null;\n const ownUrl = attached && !getPrincipal ? url : null;\n owner = current;\n attached = true;\n generation = generationOf?.() ?? 0;\n let stored = storage ? await storage.get(key) : null;\n const ownRecord = stored !== null && ownUrl !== null && stored.url === ownUrl;\n if (stored && owner !== undefined && stored.owner !== owner && !ownRecord) {\n await storage?.delete(key);\n stored = null;\n }\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 ...(owner === undefined ? {} : { owner }),\n });\n }\n\n const creationHeaders: Record<string, string> = {\n ...baseHeaders(endpoint, \"POST\"),\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, endpoint);\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 assertCurrentOwner();\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(target, \"PATCH\"),\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 * `resync` is armed only when the attempt is actually going to happen. A\n * caller's own `shouldRetry` still wins the decision, and still arms the\n * resync when it says yes — the flag describes what the *next* attempt must\n * do, so setting it for an attempt that never comes describes nothing.\n * {@link isRetriableChunkFailure} is the default, and it is where `409`/`412`\n * earn a retry the shared policy would refuse and `404`/`410` lose one it\n * would have granted.\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 ResumableUploadSupersededError) return false;\n if (error instanceof DOMException && error.name === \"AbortError\") return false;\n const again =\n retryOptions?.shouldRetry?.(error, attempt) ??\n isRetriableChunkFailure(error);\n if (again) resync.needed = true;\n return again;\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(url, \"DELETE\"),\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":"A,4QAsBA,IAAaoB,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E,IAAMwD,EACF/C,GAAc,cAAcT,EAAOyD,CAAO,GAC1C1D,EAAwBC,CAAK,EAEjC,OADIwD,IAAO,EAAO,OAAS,IACpBA,CACX,CACJ,CAAC,EAcL,OAXIjC,IAAa,SACbG,EAAS,QAAQ,EACV,MAEPH,IAAa,SACbG,EAAS,SAAS,EACX,OAGXA,EAAS,MAAM,EACX9C,GAAS,MAAMA,EAAQ,OAAOE,CAAG,EAC9B,CAAE,IAAKmD,EAAQ,KAAM1D,EAAK,IAAK,EAC1C,CAEA,eAAemF,GAAiD,CAC5D,GAAI,CACA,OAAO,MAAMH,GAAI,CACrB,OAASvD,EAAO,CACZ,GACIuB,IAAa,MACZvB,aAAiB,cAAgBA,EAAM,OAAS,aAGjD,OADA0B,EAASH,IAAa,QAAU,UAAY,QAAQ,EAC7C,KAGX,MADAG,EAAS,OAAO,EACV1B,CACV,QAAU,CACN,EAAW,IACf,CACJ,CAEA,SAAS2D,EAAK,EAAiC,CAC3C,EAAWjG,EACX8D,GAAU,MAAM,EAChB,EAAW,IACf,CAEA,MAAO,CACH,MAAOkC,EACP,OAAQA,EACR,UAAaC,EAAK,OAAO,EACzB,MAAO,MAAO,CAAE,UAAU,IAAU,CAAC,IAAM,CACvCA,EAAK,OAAO,EACZjC,EAAS,SAAS,EACbkC,IACD7C,GACA,MAAM5B,EAAY,CACd,OAAQ,SACR,MACA,QAAS4C,EAAYhB,EAAK,QAAQ,EAClC,kBACA,aAAgB,IAAA,EACpB,CAAC,CAAC,CAAC,UAAY,IAAA,EAAS,EAExBnC,GAAS,MAAMA,EAAQ,OAAOE,CAAG,EACzC,EACA,IAAI,OAAQ,CACR,OAAO+B,CACX,EACA,IAAI,QAAS,CACT,OAAOC,CACX,EACA,IAAI,KAAM,CACN,OAAOC,CACX,EACA,KACJ,CACJ,C"}
@@ -1,18 +1,19 @@
1
1
  import { TempestApiError as e, buildApiError as t, isApiError as n, isRetriableStatus as r } from "./errors.js";
2
2
  import { bytesToBase64 as i } from "../utils/base64.js";
3
- import { isTrustedCredentialTarget as a, reportSuppressedCredential as o } from "./credential-scope.js";
4
- import { csrfHeaders as s } from "./csrf.js";
5
- import { retry as c } from "./retry.js";
6
- import { ownerFingerprint as l } from "../utils/owner-fingerprint.js";
7
- import { generateIdempotencyKey as u } from "./idempotency.js";
3
+ import { isTrustedCredentialTarget as a, reportSuppressedCredential as o, resolveRequestUrl as s } from "./credential-scope.js";
4
+ import { csrfHeaders as c } from "./csrf.js";
5
+ import { retry as l } from "./retry.js";
6
+ import { sessionIdentityOf as u } from "../auth/session-identity.js";
7
+ import { ownerFingerprint as d } from "../utils/owner-fingerprint.js";
8
+ import { generateIdempotencyKey as ee } from "./idempotency.js";
8
9
  //#region src/http/resumable-upload.ts
9
- var d = "1.0.0", f = 5242880, p = class extends Error {
10
+ var f = "1.0.0", p = 5242880, m = class extends Error {
10
11
  reason;
11
12
  constructor(e) {
12
13
  super(e === "principal" ? "O usuário mudou durante o upload resumível." : "Os registros de upload resumível foram limpos durante o upload."), this.name = "ResumableUploadSupersededError", this.reason = e;
13
14
  }
14
- }, m = /* @__PURE__ */ new Map(), h = /* @__PURE__ */ new WeakMap();
15
- function g(e) {
15
+ }, h = /* @__PURE__ */ new Map(), g = /* @__PURE__ */ new WeakMap();
16
+ function _(e) {
16
17
  if (!e) return !1;
17
18
  try {
18
19
  let t = JSON.parse(e);
@@ -21,12 +22,12 @@ function g(e) {
21
22
  return !1;
22
23
  }
23
24
  }
24
- function _(e) {
25
+ function v(e) {
25
26
  return i(new TextEncoder().encode(e));
26
27
  }
27
- function v(e) {
28
+ function te(e) {
28
29
  if (!e) return null;
29
- let t = Object.entries(e).map(([e, t]) => `${e} ${_(t)}`);
30
+ let t = Object.entries(e).map(([e, t]) => `${e} ${v(t)}`);
30
31
  return t.length > 0 ? t.join(",") : null;
31
32
  }
32
33
  function y(e, t) {
@@ -58,18 +59,18 @@ function b(e = "tempest-upload:") {
58
59
  t()?.removeItem(e + n);
59
60
  },
60
61
  clear() {
61
- m.set(e, (m.get(e) ?? 0) + 1);
62
+ h.set(e, (h.get(e) ?? 0) + 1);
62
63
  let n = t();
63
64
  if (!n) return;
64
65
  let r = [];
65
66
  for (let t = 0; t < n.length; t += 1) {
66
67
  let i = n.key(t);
67
- i?.startsWith(e) && g(n.getItem(i)) && r.push(i);
68
+ i?.startsWith(e) && _(n.getItem(i)) && r.push(i);
68
69
  }
69
70
  for (let e of r) n.removeItem(e);
70
71
  }
71
72
  };
72
- return h.set(n, () => m.get(e) ?? 0), n;
73
+ return g.set(n, () => h.get(e) ?? 0), n;
73
74
  }
74
75
  function x(t) {
75
76
  return new Promise((n, r) => {
@@ -105,7 +106,7 @@ function C(e) {
105
106
  }
106
107
  }
107
108
  var w = /* @__PURE__ */ new Set([409, 412]);
108
- function ee(e) {
109
+ function ne(e) {
109
110
  return !n(e) || w.has(e.status) ? !0 : r(e.status);
110
111
  }
111
112
  function T(n, r) {
@@ -115,26 +116,29 @@ function T(n, r) {
115
116
  detail: o ? a.detail : r
116
117
  });
117
118
  }
118
- function E(e) {
119
- let t = typeof window > "u" ? void 0 : window.location.href;
119
+ function re(e, t) {
120
120
  try {
121
- return new URL(e, t).href;
121
+ return new URL(e, s(t) ?? void 0).href;
122
122
  } catch {
123
123
  return e;
124
124
  }
125
125
  }
126
- function D(t) {
127
- let { endpoint: n, file: r, chunkSize: i = f, metadata: m, headers: g = {}, getToken: _, getPrincipal: C, trustedOrigins: w, withCredentials: D = !1, csrf: O, key: k = y(n, r), storage: A = b(), retry: j, onProgress: M, onStateChange: N } = t, P = "idle", F = 0, I = null, L = null, R, z = !1, B = A ? h.get(A) : void 0, V = B?.() ?? 0;
126
+ function E(t) {
127
+ let { endpoint: n, file: r, chunkSize: i = p, metadata: s, headers: h = {}, getToken: _, getPrincipal: v, trustedOrigins: C, withCredentials: w = !1, csrf: E, key: D = y(n, r), storage: O = b(), retry: k, onProgress: A, onStateChange: j } = t, M = v ?? u(_)?.current, N = "idle", P = 0, F = null, I = null, L, R = !1, z = O ? g.get(O) : void 0, B = z?.() ?? 0;
128
+ function V() {
129
+ if (M) return d("p", M());
130
+ if (_) return d("t", _());
131
+ }
128
132
  function H() {
129
- if (C && l("p", C()) !== R) throw new p("principal");
130
- if (B && B() !== V) throw new p("cleared");
133
+ if (M && d("p", M()) !== L) throw new m("principal");
134
+ if (z && z() !== B) throw new m("cleared");
131
135
  }
132
136
  let U = null, W = null, G = 0;
133
137
  function K(e) {
134
- P !== e && (P = e, N?.(e));
138
+ N !== e && (N = e, j?.(e));
135
139
  }
136
140
  function q(e) {
137
- M?.({
141
+ A?.({
138
142
  loaded: e,
139
143
  total: r.size,
140
144
  fraction: r.size === 0 ? 1 : e / r.size,
@@ -142,30 +146,30 @@ function D(t) {
142
146
  });
143
147
  }
144
148
  function J(e, t) {
145
- let r = {
146
- ...g,
147
- "Tus-Resumable": d
148
- }, i = _?.();
149
- return i && !("Authorization" in r) && (a(e, n, w) ? r.Authorization = `Bearer ${i}` : o(e, n)), Object.assign(r, s({
149
+ let r = a(e, n, C), i = {
150
+ ...r ? h : {},
151
+ "Tus-Resumable": f
152
+ }, s = _?.();
153
+ return s && !("Authorization" in h) && (r ? i.Authorization = `Bearer ${s}` : o(e, n)), Object.assign(i, c({
150
154
  method: t,
151
155
  url: e,
152
156
  reference: n,
153
- csrf: O,
154
- trustedOrigins: w,
155
- headers: g
156
- })), r;
157
+ csrf: E,
158
+ trustedOrigins: C,
159
+ headers: h
160
+ })), i;
157
161
  }
158
162
  function Y(e) {
159
163
  W = e;
160
164
  }
161
165
  async function X() {
162
- A && I && L && (H(), await A.set(k, {
163
- url: I,
164
- offset: F,
166
+ O && F && I && (H(), L = V(), await O.set(D, {
167
+ url: F,
168
+ offset: P,
165
169
  size: r.size,
166
- idempotencyKey: L,
170
+ idempotencyKey: I,
167
171
  updatedAt: Date.now(),
168
- ...R === void 0 ? {} : { owner: R }
172
+ ...L === void 0 ? {} : { owner: L }
169
173
  }));
170
174
  }
171
175
  async function Z(t) {
@@ -173,7 +177,7 @@ function D(t) {
173
177
  method: "HEAD",
174
178
  url: t,
175
179
  headers: J(t, "HEAD"),
176
- withCredentials: D,
180
+ withCredentials: w,
177
181
  register: Y
178
182
  });
179
183
  if (n.status === 404 || n.status === 410) throw new e({
@@ -184,44 +188,46 @@ function D(t) {
184
188
  if (r === null) throw T(n, "HEAD sem Upload-Offset.");
185
189
  return r;
186
190
  }
187
- async function te() {
188
- let e = C ? l("p", C()) : void 0;
189
- z && e !== R && (L = null), R = e, z = !0, V = B?.() ?? 0;
190
- let t = A ? await A.get(k) : null;
191
- if (t && R !== void 0 && t.owner !== R && (await A?.delete(k), t = null), t && t.size === r.size && (L = t.idempotencyKey, t.url)) try {
192
- return F = await Z(t.url), I = t.url, t.url;
191
+ async function ie() {
192
+ let e = V();
193
+ R && M && e !== L && (I = null);
194
+ let t = R && !M ? F : null;
195
+ L = e, R = !0, B = z?.() ?? 0;
196
+ let i = O ? await O.get(D) : null, a = i !== null && t !== null && i.url === t;
197
+ if (i && L !== void 0 && i.owner !== L && !a && (await O?.delete(D), i = null), i && i.size === r.size && (I = i.idempotencyKey, i.url)) try {
198
+ return P = await Z(i.url), F = i.url, i.url;
193
199
  } catch {
194
- F = 0;
200
+ P = 0;
195
201
  }
196
- K("creating"), L ??= u(), I = null, F = 0, A && await A.set(k, {
202
+ K("creating"), I ??= ee(), F = null, P = 0, O && await O.set(D, {
197
203
  url: "",
198
204
  offset: 0,
199
205
  size: r.size,
200
- idempotencyKey: L,
206
+ idempotencyKey: I,
201
207
  updatedAt: Date.now(),
202
- ...R === void 0 ? {} : { owner: R }
208
+ ...L === void 0 ? {} : { owner: L }
203
209
  });
204
- let i = {
210
+ let o = {
205
211
  ...J(n, "POST"),
206
212
  "Upload-Length": String(r.size),
207
- "Idempotency-Key": L
208
- }, a = v(m);
209
- a && (i["Upload-Metadata"] = a);
210
- let o = await x({
213
+ "Idempotency-Key": I
214
+ }, c = te(s);
215
+ c && (o["Upload-Metadata"] = c);
216
+ let l = await x({
211
217
  method: "POST",
212
218
  url: n,
213
- headers: i,
214
- withCredentials: D,
219
+ headers: o,
220
+ withCredentials: w,
215
221
  register: Y
216
222
  });
217
- if (o.status !== 201) throw T(o, "Criação do upload recusada.");
218
- let s = o.header("Location");
219
- if (!s) throw T(o, "Criação do upload sem cabeçalho Location.");
220
- return I = E(s), await X(), I;
223
+ if (l.status !== 201) throw T(l, "Criação do upload recusada.");
224
+ let u = l.header("Location");
225
+ if (!u) throw T(l, "Criação do upload sem cabeçalho Location.");
226
+ return F = re(u, n), await X(), F;
221
227
  }
222
- async function ne(e, t) {
223
- if (H(), t.needed && (F = await Z(e), t.needed = !1, q(F), await X(), F >= r.size)) return;
224
- let n = Math.min(F + i, r.size), a = F, o = await x({
228
+ async function ae(e, t) {
229
+ if (H(), t.needed && (P = await Z(e), t.needed = !1, q(P), await X(), P >= r.size)) return;
230
+ let n = Math.min(P + i, r.size), a = P, o = await x({
225
231
  method: "PATCH",
226
232
  url: e,
227
233
  headers: {
@@ -230,36 +236,36 @@ function D(t) {
230
236
  "Upload-Offset": String(a)
231
237
  },
232
238
  body: r.slice(a, n),
233
- withCredentials: D,
239
+ withCredentials: w,
234
240
  onProgress: (e) => q(Math.min(a + e, r.size)),
235
241
  register: Y
236
242
  });
237
243
  if (o.status === 409 || o.status === 412) throw t.needed = !0, T(o, "Offset divergente — o servidor já tinha esses bytes.");
238
244
  if (o.status !== 204 && o.status !== 200) throw T(o, "Chunk recusado pelo servidor.");
239
- F = S(o) ?? n, q(F), await X();
245
+ P = S(o) ?? n, q(P), await X();
240
246
  }
241
- async function re() {
247
+ async function oe() {
242
248
  U = null;
243
- let e = await te();
244
- G = F, K("uploading"), q(F);
249
+ let e = await ie();
250
+ G = P, K("uploading"), q(P);
245
251
  let t = { needed: !1 };
246
- for (; F < r.size && !U;) await c(() => ne(e, t), {
252
+ for (; P < r.size && !U;) await l(() => ae(e, t), {
247
253
  retries: 5,
248
- ...j,
254
+ ...k,
249
255
  shouldRetry: (e, n) => {
250
- if (U || e instanceof p || e instanceof DOMException && e.name === "AbortError") return !1;
251
- let r = j?.shouldRetry?.(e, n) ?? ee(e);
256
+ if (U || e instanceof m || e instanceof DOMException && e.name === "AbortError") return !1;
257
+ let r = k?.shouldRetry?.(e, n) ?? ne(e);
252
258
  return r && (t.needed = !0), r;
253
259
  }
254
260
  });
255
- return U === "pause" ? (K("paused"), null) : U === "abort" ? (K("aborted"), null) : (K("done"), A && await A.delete(k), {
261
+ return U === "pause" ? (K("paused"), null) : U === "abort" ? (K("aborted"), null) : (K("done"), O && await O.delete(D), {
256
262
  url: e,
257
263
  size: r.size
258
264
  });
259
265
  }
260
266
  async function Q() {
261
267
  try {
262
- return await re();
268
+ return await oe();
263
269
  } catch (e) {
264
270
  if (U !== null || e instanceof DOMException && e.name === "AbortError") return K(U === "abort" ? "aborted" : "paused"), null;
265
271
  throw K("error"), e;
@@ -275,27 +281,27 @@ function D(t) {
275
281
  resume: Q,
276
282
  pause: () => $("pause"),
277
283
  abort: async ({ discard: e = !1 } = {}) => {
278
- $("abort"), K("aborted"), e && (I && await x({
284
+ $("abort"), K("aborted"), e && (F && await x({
279
285
  method: "DELETE",
280
- url: I,
281
- headers: J(I, "DELETE"),
282
- withCredentials: D,
286
+ url: F,
287
+ headers: J(F, "DELETE"),
288
+ withCredentials: w,
283
289
  register: () => void 0
284
- }).catch(() => void 0), A && await A.delete(k));
290
+ }).catch(() => void 0), O && await O.delete(D));
285
291
  },
286
292
  get state() {
287
- return P;
293
+ return N;
288
294
  },
289
295
  get offset() {
290
- return F;
296
+ return P;
291
297
  },
292
298
  get url() {
293
- return I;
299
+ return F;
294
300
  },
295
- key: k
301
+ key: D
296
302
  };
297
303
  }
298
304
  //#endregion
299
- export { f as DEFAULT_CHUNK_SIZE, p as ResumableUploadSupersededError, d as TUS_VERSION, b as createLocalUploadStorage, D as createResumableUpload, y as uploadFingerprint };
305
+ export { p as DEFAULT_CHUNK_SIZE, m as ResumableUploadSupersededError, f as TUS_VERSION, b as createLocalUploadStorage, E as createResumableUpload, y as uploadFingerprint };
300
306
 
301
307
  //# sourceMappingURL=resumable-upload.js.map