tempest-react-sdk 0.75.0 → 0.77.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 (147) hide show
  1. package/README.md +4 -2
  2. package/bin/create-tempest-app.e2e.test.mjs +112 -0
  3. package/bin/create-tempest-app.mjs +69 -28
  4. package/bin/lib/component/generate.mjs +191 -0
  5. package/bin/lib/component/generate.test.mjs +336 -0
  6. package/bin/lib/openapi/escape.mjs +210 -0
  7. package/bin/lib/openapi/generate.hostile.test.mjs +592 -0
  8. package/bin/lib/openapi/generate.mjs +93 -17
  9. package/bin/lib/openapi/schema-to-zod.mjs +41 -4
  10. package/bin/tempest.mjs +184 -3
  11. package/dist/auth/create-tempest-auth.cjs +1 -1
  12. package/dist/auth/create-tempest-auth.cjs.map +1 -1
  13. package/dist/auth/create-tempest-auth.js +127 -55
  14. package/dist/auth/create-tempest-auth.js.map +1 -1
  15. package/dist/auth/refresh-queue.cjs +1 -1
  16. package/dist/auth/refresh-queue.cjs.map +1 -1
  17. package/dist/auth/refresh-queue.js +13 -6
  18. package/dist/auth/refresh-queue.js.map +1 -1
  19. package/dist/br/pix.cjs +1 -1
  20. package/dist/br/pix.cjs.map +1 -1
  21. package/dist/br/pix.js +72 -62
  22. package/dist/br/pix.js.map +1 -1
  23. package/dist/br.d.ts +12 -4
  24. package/dist/components/Chat/ChatAttachments.cjs +1 -1
  25. package/dist/components/Chat/ChatAttachments.cjs.map +1 -1
  26. package/dist/components/Chat/ChatAttachments.js +46 -38
  27. package/dist/components/Chat/ChatAttachments.js.map +1 -1
  28. package/dist/components/Markdown/markdown-parse.cjs +7 -5
  29. package/dist/components/Markdown/markdown-parse.cjs.map +1 -1
  30. package/dist/components/Markdown/markdown-parse.js +151 -87
  31. package/dist/components/Markdown/markdown-parse.js.map +1 -1
  32. package/dist/components/Toast/Toast.module.cjs +1 -1
  33. package/dist/components/Toast/Toast.module.cjs.map +1 -1
  34. package/dist/components/Toast/Toast.module.js +7 -3
  35. package/dist/components/Toast/Toast.module.js.map +1 -1
  36. package/dist/components/Toast/ToastProvider.cjs +1 -1
  37. package/dist/components/Toast/ToastProvider.cjs.map +1 -1
  38. package/dist/components/Toast/ToastProvider.js +77 -51
  39. package/dist/components/Toast/ToastProvider.js.map +1 -1
  40. package/dist/data/create-data-provider.cjs +1 -1
  41. package/dist/data/create-data-provider.cjs.map +1 -1
  42. package/dist/data/create-data-provider.js +32 -21
  43. package/dist/data/create-data-provider.js.map +1 -1
  44. package/dist/http/api-client.cjs +1 -1
  45. package/dist/http/api-client.cjs.map +1 -1
  46. package/dist/http/api-client.js +81 -73
  47. package/dist/http/api-client.js.map +1 -1
  48. package/dist/http/errors.cjs +1 -1
  49. package/dist/http/errors.cjs.map +1 -1
  50. package/dist/http/errors.js +39 -35
  51. package/dist/http/errors.js.map +1 -1
  52. package/dist/neural.cjs +2 -0
  53. package/dist/neural.cjs.map +1 -0
  54. package/dist/neural.d.ts +110 -0
  55. package/dist/neural.js +48 -0
  56. package/dist/neural.js.map +1 -0
  57. package/dist/oauth/callback.cjs +2 -0
  58. package/dist/oauth/callback.cjs.map +1 -0
  59. package/dist/oauth/callback.js +42 -0
  60. package/dist/oauth/callback.js.map +1 -0
  61. package/dist/oauth/use-oauth-callback.cjs +1 -1
  62. package/dist/oauth/use-oauth-callback.cjs.map +1 -1
  63. package/dist/oauth/use-oauth-callback.js +13 -20
  64. package/dist/oauth/use-oauth-callback.js.map +1 -1
  65. package/dist/push/use-push-subscription.cjs +1 -1
  66. package/dist/push/use-push-subscription.cjs.map +1 -1
  67. package/dist/push/use-push-subscription.js +42 -42
  68. package/dist/push/use-push-subscription.js.map +1 -1
  69. package/dist/push/web-push-client.cjs +1 -1
  70. package/dist/push/web-push-client.cjs.map +1 -1
  71. package/dist/push/web-push-client.js +23 -3
  72. package/dist/push/web-push-client.js.map +1 -1
  73. package/dist/query/offline-persistence.cjs +1 -1
  74. package/dist/query/offline-persistence.cjs.map +1 -1
  75. package/dist/query/offline-persistence.js +68 -23
  76. package/dist/query/offline-persistence.js.map +1 -1
  77. package/dist/styles/component/Toast.css +6 -1
  78. package/dist/styles/feedback.css +6 -1
  79. package/dist/styles.css +1 -1
  80. package/dist/sw/background-sync.cjs +1 -1
  81. package/dist/sw/background-sync.cjs.map +1 -1
  82. package/dist/sw/background-sync.js +271 -60
  83. package/dist/sw/background-sync.js.map +1 -1
  84. package/dist/sw/cache-inspect.cjs.map +1 -1
  85. package/dist/sw/cache-inspect.js.map +1 -1
  86. package/dist/sw/cache.cjs +1 -1
  87. package/dist/sw/cache.cjs.map +1 -1
  88. package/dist/sw/cache.js +91 -64
  89. package/dist/sw/cache.js.map +1 -1
  90. package/dist/sw/credential-headers.cjs +2 -0
  91. package/dist/sw/credential-headers.cjs.map +1 -0
  92. package/dist/sw/credential-headers.js +17 -0
  93. package/dist/sw/credential-headers.js.map +1 -0
  94. package/dist/sw/session-data.cjs +2 -0
  95. package/dist/sw/session-data.cjs.map +1 -0
  96. package/dist/sw/session-data.js +17 -0
  97. package/dist/sw/session-data.js.map +1 -0
  98. package/dist/sw.cjs +1 -1
  99. package/dist/sw.d.ts +271 -23
  100. package/dist/sw.js +7 -5
  101. package/dist/telemetry/app-error-owner.cjs +2 -0
  102. package/dist/telemetry/app-error-owner.cjs.map +1 -0
  103. package/dist/telemetry/app-error-owner.js +18 -0
  104. package/dist/telemetry/app-error-owner.js.map +1 -0
  105. package/dist/telemetry/app-error-queue.cjs +1 -1
  106. package/dist/telemetry/app-error-queue.cjs.map +1 -1
  107. package/dist/telemetry/app-error-queue.js +19 -14
  108. package/dist/telemetry/app-error-queue.js.map +1 -1
  109. package/dist/telemetry/app-error-reporter.cjs +1 -1
  110. package/dist/telemetry/app-error-reporter.cjs.map +1 -1
  111. package/dist/telemetry/app-error-reporter.js +75 -34
  112. package/dist/telemetry/app-error-reporter.js.map +1 -1
  113. package/dist/telemetry/app-error-transport.cjs +1 -1
  114. package/dist/telemetry/app-error-transport.cjs.map +1 -1
  115. package/dist/telemetry/app-error-transport.js +16 -3
  116. package/dist/telemetry/app-error-transport.js.map +1 -1
  117. package/dist/tempest-react-sdk.cjs +1 -1
  118. package/dist/tempest-react-sdk.d.ts +979 -62
  119. package/dist/tempest-react-sdk.js +160 -156
  120. package/dist/utils/csv.cjs +3 -3
  121. package/dist/utils/csv.cjs.map +1 -1
  122. package/dist/utils/csv.js +16 -13
  123. package/dist/utils/csv.js.map +1 -1
  124. package/dist/utils/safe-url.cjs +2 -0
  125. package/dist/utils/safe-url.cjs.map +1 -0
  126. package/dist/utils/safe-url.js +39 -0
  127. package/dist/utils/safe-url.js.map +1 -0
  128. package/dist/vite/tempest-csp.cjs +2 -2
  129. package/dist/vite/tempest-csp.cjs.map +1 -1
  130. package/dist/vite/tempest-csp.js +118 -63
  131. package/dist/vite/tempest-csp.js.map +1 -1
  132. package/dist/vite.d.ts +21 -5
  133. package/dist/webrtc/peer-link.cjs +1 -1
  134. package/dist/webrtc/peer-link.cjs.map +1 -1
  135. package/dist/webrtc/peer-link.js +2 -10
  136. package/dist/webrtc/peer-link.js.map +1 -1
  137. package/dist/webrtc/peer-mesh.cjs +1 -1
  138. package/dist/webrtc/peer-mesh.cjs.map +1 -1
  139. package/dist/webrtc/peer-mesh.js +110 -72
  140. package/dist/webrtc/peer-mesh.js.map +1 -1
  141. package/package.json +11 -1
  142. package/template-pwa/src/pwa.tsx +22 -0
  143. package/template-pwa/src/sw.ts +27 -14
  144. package/dist/components/Markdown/markdown-url.cjs +0 -2
  145. package/dist/components/Markdown/markdown-url.cjs.map +0 -1
  146. package/dist/components/Markdown/markdown-url.js +0 -28
  147. package/dist/components/Markdown/markdown-url.js.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"api-client.js","names":[],"sources":["../../src/http/api-client.ts"],"sourcesContent":["/**\n * @tempest-limits function-lines — createApiClient is over the limit and every line\n * is a request-lifecycle concern the client cannot delegate: base URL joining, the\n * auth header, the 401 refresh-and-replay, the opt-in retry wrapper and the response\n * parsing that turns a failure into a typed error.\n */\nimport { randomId } from \"../utils\";\nimport { buildApiUrl } from \"./build-url\";\nimport { isTrustedCredentialTarget, reportSuppressedCredential } from \"./credential-scope\";\nimport { csrfHeaders } from \"./csrf\";\nimport { decodeByContentType } from \"./decode-response\";\nimport type { ResponseDecoder } from \"./decode-response\";\nimport { buildApiError, TempestApiError, isRetriableStatus } from \"./errors\";\nimport { retry as retryWithBackoff } from \"./retry\";\nimport type { RetryOptions } from \"./retry\";\nimport { withTimeout } from \"./timeout\";\nimport type { ApiClient, ApiClientConfig, RequestOptions } from \"./types\";\n\n/**\n * Methods the built-in retry policy will replay.\n *\n * `PUT` and `DELETE` are idempotent on paper but stay out: a backend that logs,\n * bills, or fires a webhook per call still sees two, so replaying them is a\n * decision the caller makes through `shouldRetry`, not a default.\n */\nconst IDEMPOTENT_METHODS: ReadonlySet<string> = new Set([\"GET\", \"HEAD\", \"OPTIONS\"]);\n\n/**\n * Sub-500 statuses worth a second attempt: a network failure (status `0`), a\n * request timeout, a too-early replay, and a rate limit — which usually carries\n * the `Retry-After` the backoff already honours.\n */\n\n/**\n * The built-in retry policy, used when `retry` is `true` or is options carrying\n * no `shouldRetry` of their own.\n *\n * Conservative on purpose. Replaying a write can duplicate it, and replaying a\n * `400` or a `403` cannot fix a bad payload or a permission the caller does not\n * have — it only spends the user's time before showing the same error.\n *\n * @param error - Whatever the attempt threw.\n * @param method - The upper-cased HTTP method of the request.\n * @returns Whether the client should try again.\n */\nfunction isRetriableFailure(error: unknown, method: string): boolean {\n if (!IDEMPOTENT_METHODS.has(method)) return false;\n if (!(error instanceof TempestApiError)) return false;\n return isRetriableStatus(error.status);\n}\n\n/**\n * Normalize the `retry` config into options, or `null` when retrying is off.\n *\n * @param config - The `retry` field as the caller wrote it.\n * @returns Retry options to use, or `null` to run a single attempt.\n */\nfunction resolveRetry(config: boolean | RetryOptions | undefined): RetryOptions | null {\n if (!config) return null;\n return config === true ? {} : config;\n}\n\n/** Default milliseconds before a request is abandoned. */\nconst DEFAULT_TIMEOUT = 15_000;\n\n/** Default milliseconds before a `FormData` request is abandoned. */\nconst DEFAULT_UPLOAD_TIMEOUT = 300_000;\n\nfunction isFormData(body: unknown): body is FormData {\n return typeof FormData !== \"undefined\" && body instanceof FormData;\n}\n\n/**\n * Milliseconds since a `performance.now()` reading, rounded.\n *\n * `performance.now()` rather than `Date.now()` because this measures a\n * duration: the wall clock can step sideways mid-request (an NTP correction, a\n * VM resuming, the user changing the clock) and turn a 40 ms call into a\n * negative number. The monotonic clock cannot.\n *\n * @param startedAt - The reading taken before the work started.\n * @returns Whole milliseconds elapsed.\n */\nfunction elapsedMs(startedAt: number): number {\n return Math.round(performance.now() - startedAt);\n}\n\nasync function parseError(response: Response, sentRequestId?: string): Promise<TempestApiError> {\n let body: unknown;\n try {\n body = await response.clone().json();\n } catch {\n try {\n body = await response.text();\n } catch {\n body = null;\n }\n }\n return new TempestApiError(\n buildApiError(response.status, body, response.headers, sentRequestId),\n );\n}\n\n/**\n * Create a typed HTTP client backed by `fetch`.\n *\n * Handles JSON serialization, query params, bearer auth via `getToken`, uploads\n * via `FormData`, and throws a typed `ApiError` on any non-2xx response.\n *\n * **Expired sessions.** A `401` with `refresh` configured awaits the refresh and\n * replays the request once. `onUnauthorized` fires whenever that path ends\n * unauthorized anyway — the refresh threw, or the replay came back `401` — which\n * is the signal to clear the session. Without `refresh`, the first `401` calls\n * it directly.\n *\n * **Binary bodies** have their own methods — `blob()` and `arrayBuffer()` — which\n * run the same pipeline and skip the parse. `request()` no longer decodes an\n * unknown `Content-Type` as text either: it returns a `Blob` and says so once in\n * a development build, because reading `image/jpeg` as UTF-8 destroyed the bytes\n * on the way in.\n *\n * **The bearer token is scoped to `baseURL`'s origin** since 0.66.0. A path may\n * be an absolute URL, which overrides the base entirely, so without a scope the\n * destination of a credentialed request could come from a value read off the\n * network. A request to another origin still goes out; it goes without the\n * header, and a development build says so once. Declare the exceptions in\n * {@link ApiClientConfig.trustedOrigins}.\n *\n * **CSRF** is off unless you set `csrf`. With it, every unsafe request (anything\n * but `GET`/`HEAD`/`OPTIONS`/`TRACE`) echoes the `csrf_token` cookie in an\n * `X-CSRF-Token` header — the double-submit contract of `tempest-fastapi-sdk`'s\n * `CSRFMiddleware` — scoped to the same origins as the bearer token and sent on\n * `skipAuth` requests too. See {@link ApiClientConfig.csrf}.\n *\n * **Retries** are off unless you set `retry`. See {@link ApiClientConfig.retry}\n * for the built-in policy; it never replays a write. A single call overrides it\n * with {@link RequestOptions.retry}, and opts out of auth entirely with\n * {@link RequestOptions.skipAuth}.\n *\n * **Logging** is off unless you pass a `logger`. With one, every finished attempt\n * writes a line — `debug` under 400, `warn` from 400 up, plus a `warn` when\n * `onUnauthorized` fires — carrying `requestId`, `status` and elapsed `ms`, and\n * never a body, header or query string. The level and the destination belong to\n * the logger, not to a boolean here.\n *\n * @example\n * const api = createApiClient({\n * baseURL: import.meta.env.VITE_API_URL,\n * getToken: () => useAuthStore.getState().token,\n * refresh,\n * onUnauthorized: () => useAuthStore.getState().logout(),\n * logger: createLogger({ level: import.meta.env.DEV ? \"debug\" : \"warn\" }).child(\"http\"),\n * retry: true,\n * });\n *\n * @param config - Base URL plus the optional auth, retry and fetch hooks.\n * @returns A client with `request`/`get`/`post`/`put`/`patch`/`delete`/`blob`/\n * `arrayBuffer`/`upload`.\n */\nexport function createApiClient(config: ApiClientConfig): ApiClient {\n const fetcher = config.fetcher ?? globalThis.fetch.bind(globalThis);\n\n /**\n * The `Authorization` header for a request, or nothing.\n *\n * Takes the resolved URL rather than reading `config.baseURL`, because an\n * absolute path overrides the base entirely (see `buildApiUrl`) and the\n * credential is scoped to an origin, not to a client.\n *\n * @param url - The absolute URL the request is going to.\n * @param skipAuth - Whether the caller opted this request out of auth.\n * @returns The header, or an empty object.\n */\n function authHeaders(url: string, skipAuth: boolean): Record<string, string> {\n if (skipAuth) return {};\n const token = config.getToken?.();\n if (!token) return {};\n if (!isTrustedCredentialTarget(url, config.baseURL, config.trustedOrigins)) {\n reportSuppressedCredential(url, config.baseURL);\n return {};\n }\n return { Authorization: `Bearer ${token}` };\n }\n\n async function rawRequest(\n path: string,\n options: RequestOptions,\n requestId: string | undefined,\n skipAuth: boolean,\n ): Promise<Response> {\n const { body, params, headers, signal, timeout, ...rest } = options;\n const isForm = isFormData(body);\n const configured = isForm ? config.uploadTimeout : config.timeout;\n const fallback = isForm ? DEFAULT_UPLOAD_TIMEOUT : DEFAULT_TIMEOUT;\n const limit =\n timeout !== undefined ? timeout : configured !== undefined ? configured : fallback;\n\n const url = buildApiUrl(config.baseURL, path, { prefix: config.prefix, params });\n\n const callerHeaders = headers as Record<string, string> | undefined;\n const finalHeaders: Record<string, string> = {\n ...(isForm ? {} : { \"Content-Type\": \"application/json\" }),\n ...(requestId ? { \"X-Request-ID\": requestId } : {}),\n ...config.headers,\n ...authHeaders(url, skipAuth),\n ...csrfHeaders({\n method: rest.method ?? \"GET\",\n url,\n reference: config.baseURL,\n csrf: config.csrf,\n trustedOrigins: config.trustedOrigins,\n headers: { ...config.headers, ...callerHeaders },\n }),\n ...callerHeaders,\n };\n\n const timed = withTimeout(signal, limit);\n const init: RequestInit = {\n ...rest,\n signal: timed.signal,\n headers: finalHeaders,\n credentials: config.withCredentials ? \"include\" : rest.credentials,\n body:\n body === undefined || body === null\n ? undefined\n : isForm\n ? (body as FormData)\n : JSON.stringify(body),\n };\n\n try {\n return await fetcher(url, init);\n } catch (cause) {\n if (timed.timedOut()) {\n throw new TempestApiError({\n status: 0,\n detail: `A requisição excedeu ${limit}ms e foi abandonada.`,\n });\n }\n throw cause;\n } finally {\n timed.dispose();\n }\n }\n\n async function send(\n path: string,\n options: RequestOptions,\n requestId: string,\n method: string,\n skipAuth: boolean,\n ): Promise<Response> {\n const log = config.logger;\n if (!log) return rawRequest(path, options, requestId, skipAuth);\n\n const startedAt = performance.now();\n try {\n const response = await rawRequest(path, options, requestId, skipAuth);\n const entry = { requestId, status: response.status, ms: elapsedMs(startedAt) };\n const line = `${method} ${path} → ${response.status}`;\n if (response.status >= 400) log.warn(line, entry);\n else log.debug(line, entry);\n return response;\n } catch (error) {\n log.warn(`${method} ${path} → no response`, {\n requestId,\n ms: elapsedMs(startedAt),\n error,\n });\n throw error;\n }\n }\n\n async function notifyUnauthorized(response: Response, requestId: string): Promise<void> {\n if (!config.onUnauthorized) return;\n config.logger?.warn(`unauthorized — calling onUnauthorized`, {\n requestId,\n status: response.status,\n });\n try {\n await config.onUnauthorized(response);\n } catch (error) {\n config.logger?.warn(`onUnauthorized threw — keeping the original response error`, {\n requestId,\n status: response.status,\n error,\n });\n }\n }\n\n async function attempt<T>(\n path: string,\n options: RequestOptions,\n decode: ResponseDecoder<T>,\n ): Promise<T> {\n const { skipAuth = false, skipAuthRetry = false, ...init } = options;\n const requestId = config.requestId ? config.requestId() : randomId();\n const method = (init.method ?? \"GET\").toUpperCase();\n let response = await send(path, init, requestId, method, skipAuth);\n\n if (response.status === 401 && !skipAuth && !skipAuthRetry) {\n if (config.refresh) {\n try {\n await config.refresh();\n response = await send(path, init, requestId, method, skipAuth);\n } catch {\n await notifyUnauthorized(response, requestId);\n throw await parseError(response, requestId);\n }\n if (response.status === 401) {\n await notifyUnauthorized(response, requestId);\n }\n } else {\n await notifyUnauthorized(response, requestId);\n }\n }\n\n if (!response.ok) {\n throw await parseError(response, requestId);\n }\n\n return decode(response);\n }\n\n async function run<T>(\n path: string,\n options: RequestOptions,\n decode: ResponseDecoder<T>,\n ): Promise<T> {\n const { retry: perRequest, ...rest } = options;\n const retryOptions = resolveRetry(perRequest !== undefined ? perRequest : config.retry);\n if (!retryOptions) return attempt<T>(path, rest, decode);\n\n const method = (rest.method ?? \"GET\").toUpperCase();\n return retryWithBackoff(() => attempt<T>(path, rest, decode), {\n ...retryOptions,\n shouldRetry:\n retryOptions.shouldRetry ?? ((error: unknown) => isRetriableFailure(error, method)),\n });\n }\n\n async function request<T>(path: string, options: RequestOptions = {}): Promise<T> {\n return run<T>(path, options, decodeByContentType);\n }\n\n async function upload<T>(\n path: string,\n formData: FormData,\n method: \"POST\" | \"PUT\" | \"PATCH\" = \"POST\",\n options?: Omit<RequestOptions, \"body\" | \"method\">,\n ): Promise<T> {\n return request<T>(path, { ...options, method, body: formData });\n }\n\n return {\n request,\n get: <T>(path: string, options?: RequestOptions) =>\n request<T>(path, { ...options, method: \"GET\" }),\n post: <T>(path: string, options?: RequestOptions) =>\n request<T>(path, { ...options, method: \"POST\" }),\n put: <T>(path: string, options?: RequestOptions) =>\n request<T>(path, { ...options, method: \"PUT\" }),\n patch: <T>(path: string, options?: RequestOptions) =>\n request<T>(path, { ...options, method: \"PATCH\" }),\n delete: <T>(path: string, options?: RequestOptions) =>\n request<T>(path, { ...options, method: \"DELETE\" }),\n blob: (path: string, options?: RequestOptions) =>\n run<Blob>(path, { ...options }, (response) => response.blob()),\n arrayBuffer: (path: string, options?: RequestOptions) =>\n run<ArrayBuffer>(path, { ...options }, (response) => response.arrayBuffer()),\n upload,\n };\n}\n"],"mappings":";;;;;;;;;AAyBA,IAAM,oBAA0C,IAAI,IAAI;CAAC;CAAO;CAAQ;AAAS,CAAC;AAoBlF,SAAS,EAAmB,GAAgB,GAAyB;CAGjE,OAFI,CAAC,EAAmB,IAAI,CAAM,KAC9B,EAAE,aAAiB,KAAyB,KACzC,EAAkB,EAAM,MAAM;AACzC;AAQA,SAAS,EAAa,GAAiE;CAEnF,OADK,IACE,MAAW,KAAO,CAAC,IAAI,IADV;AAExB;AAGA,IAAM,IAAkB,MAGlB,IAAyB;AAE/B,SAAS,EAAW,GAAiC;CACjD,OAAO,OAAO,WAAa,OAAe,aAAgB;AAC9D;AAaA,SAAS,EAAU,GAA2B;CAC1C,OAAO,KAAK,MAAM,YAAY,IAAI,IAAI,CAAS;AACnD;AAEA,eAAe,EAAW,GAAoB,GAAkD;CAC5F,IAAI;CACJ,IAAI;EACA,IAAO,MAAM,EAAS,MAAM,CAAC,CAAC,KAAK;CACvC,QAAQ;EACJ,IAAI;G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AAE,GAAG;GAAS,QAAQ;EAAM,CAAC;EAClD,OAAU,GAAc,MACpB,EAAW,GAAM;GAAE,GAAG;GAAS,QAAQ;EAAO,CAAC;EACnD,MAAS,GAAc,MACnB,EAAW,GAAM;GAAE,GAAG;GAAS,QAAQ;EAAM,CAAC;EAClD,QAAW,GAAc,MACrB,EAAW,GAAM;GAAE,GAAG;GAAS,QAAQ;EAAQ,CAAC;EACpD,SAAY,GAAc,MACtB,EAAW,GAAM;GAAE,GAAG;GAAS,QAAQ;EAAS,CAAC;EACrD,OAAO,GAAc,MACjB,EAAU,GAAM,EAAE,GAAG,EAAQ,IAAI,MAAa,EAAS,KAAK,CAAC;EACjE,cAAc,GAAc,MACxB,EAAiB,GAAM,EAAE,GAAG,EAAQ,IAAI,MAAa,EAAS,YAAY,CAAC;EAC/E;CACJ;AACJ"}
1
+ {"version":3,"file":"api-client.js","names":[],"sources":["../../src/http/api-client.ts"],"sourcesContent":["/**\n * @tempest-limits function-lines — createApiClient is over the limit and every line\n * is a request-lifecycle concern the client cannot delegate: base URL joining, the\n * auth header, the 401 refresh-and-replay, the opt-in retry wrapper and the response\n * parsing that turns a failure into a typed error.\n */\nimport { randomId } from \"../utils\";\nimport { buildApiUrl } from \"./build-url\";\nimport { isTrustedCredentialTarget, reportSuppressedCredential } from \"./credential-scope\";\nimport { csrfHeaders } from \"./csrf\";\nimport { decodeByContentType } from \"./decode-response\";\nimport type { ResponseDecoder } from \"./decode-response\";\nimport {\n buildApiError,\n SessionSupersededError,\n TempestApiError,\n isRetriableStatus,\n} from \"./errors\";\nimport { retry as retryWithBackoff } from \"./retry\";\nimport type { RetryOptions } from \"./retry\";\nimport { withTimeout } from \"./timeout\";\nimport type { ApiClient, ApiClientConfig, RequestAuthContext, RequestOptions } from \"./types\";\n\n/**\n * Methods the built-in retry policy will replay.\n *\n * `PUT` and `DELETE` are idempotent on paper but stay out: a backend that logs,\n * bills, or fires a webhook per call still sees two, so replaying them is a\n * decision the caller makes through `shouldRetry`, not a default.\n */\nconst IDEMPOTENT_METHODS: ReadonlySet<string> = new Set([\"GET\", \"HEAD\", \"OPTIONS\"]);\n\n/**\n * Sub-500 statuses worth a second attempt: a network failure (status `0`), a\n * request timeout, a too-early replay, and a rate limit — which usually carries\n * the `Retry-After` the backoff already honours.\n */\n\n/**\n * The built-in retry policy, used when `retry` is `true` or is options carrying\n * no `shouldRetry` of their own.\n *\n * Conservative on purpose. Replaying a write can duplicate it, and replaying a\n * `400` or a `403` cannot fix a bad payload or a permission the caller does not\n * have — it only spends the user's time before showing the same error.\n *\n * @param error - Whatever the attempt threw.\n * @param method - The upper-cased HTTP method of the request.\n * @returns Whether the client should try again.\n */\nfunction isRetriableFailure(error: unknown, method: string): boolean {\n if (!IDEMPOTENT_METHODS.has(method)) return false;\n if (!(error instanceof TempestApiError)) return false;\n return isRetriableStatus(error.status);\n}\n\n/**\n * Normalize the `retry` config into options, or `null` when retrying is off.\n *\n * @param config - The `retry` field as the caller wrote it.\n * @returns Retry options to use, or `null` to run a single attempt.\n */\nfunction resolveRetry(config: boolean | RetryOptions | undefined): RetryOptions | null {\n if (!config) return null;\n return config === true ? {} : config;\n}\n\n/** Default milliseconds before a request is abandoned. */\nconst DEFAULT_TIMEOUT = 15_000;\n\n/** Default milliseconds before a `FormData` request is abandoned. */\nconst DEFAULT_UPLOAD_TIMEOUT = 300_000;\n\nfunction isFormData(body: unknown): body is FormData {\n return typeof FormData !== \"undefined\" && body instanceof FormData;\n}\n\n/**\n * Milliseconds since a `performance.now()` reading, rounded.\n *\n * `performance.now()` rather than `Date.now()` because this measures a\n * duration: the wall clock can step sideways mid-request (an NTP correction, a\n * VM resuming, the user changing the clock) and turn a 40 ms call into a\n * negative number. The monotonic clock cannot.\n *\n * @param startedAt - The reading taken before the work started.\n * @returns Whole milliseconds elapsed.\n */\nfunction elapsedMs(startedAt: number): number {\n return Math.round(performance.now() - startedAt);\n}\n\nasync function parseError(response: Response, sentRequestId?: string): Promise<TempestApiError> {\n let body: unknown;\n try {\n body = await response.clone().json();\n } catch {\n try {\n body = await response.text();\n } catch {\n body = null;\n }\n }\n return new TempestApiError(\n buildApiError(response.status, body, response.headers, sentRequestId),\n );\n}\n\n/**\n * Create a typed HTTP client backed by `fetch`.\n *\n * Handles JSON serialization, query params, bearer auth via `getToken`, uploads\n * via `FormData`, and throws a typed `ApiError` on any non-2xx response.\n *\n * **Expired sessions.** A `401` with `refresh` configured awaits the refresh and\n * replays the request once. `onUnauthorized` fires whenever that path ends\n * unauthorized anyway — the refresh threw, or the replay came back `401` — which\n * is the signal to clear the session. Without `refresh`, the first `401` calls\n * it directly.\n *\n * **Binary bodies** have their own methods — `blob()` and `arrayBuffer()` — which\n * run the same pipeline and skip the parse. `request()` no longer decodes an\n * unknown `Content-Type` as text either: it returns a `Blob` and says so once in\n * a development build, because reading `image/jpeg` as UTF-8 destroyed the bytes\n * on the way in.\n *\n * **The bearer token is scoped to `baseURL`'s origin** since 0.66.0. A path may\n * be an absolute URL, which overrides the base entirely, so without a scope the\n * destination of a credentialed request could come from a value read off the\n * network. A request to another origin still goes out; it goes without the\n * header, and a development build says so once. Declare the exceptions in\n * {@link ApiClientConfig.trustedOrigins}.\n *\n * **CSRF** is off unless you set `csrf`. With it, every unsafe request (anything\n * but `GET`/`HEAD`/`OPTIONS`/`TRACE`) echoes the `csrf_token` cookie in an\n * `X-CSRF-Token` header — the double-submit contract of `tempest-fastapi-sdk`'s\n * `CSRFMiddleware` — scoped to the same origins as the bearer token and sent on\n * `skipAuth` requests too. See {@link ApiClientConfig.csrf}.\n *\n * **Retries** are off unless you set `retry`. See {@link ApiClientConfig.retry}\n * for the built-in policy; it never replays a write. A single call overrides it\n * with {@link RequestOptions.retry}, and opts out of auth entirely with\n * {@link RequestOptions.skipAuth}.\n *\n * **Logging** is off unless you pass a `logger`. With one, every finished attempt\n * writes a line — `debug` under 400, `warn` from 400 up, plus a `warn` when\n * `onUnauthorized` fires — carrying `requestId`, `status` and elapsed `ms`, and\n * never a body, header or query string. The level and the destination belong to\n * the logger, not to a boolean here.\n *\n * @example\n * const api = createApiClient({\n * baseURL: import.meta.env.VITE_API_URL,\n * getToken: () => useAuthStore.getState().token,\n * refresh,\n * onUnauthorized: () => useAuthStore.getState().logout(),\n * logger: createLogger({ level: import.meta.env.DEV ? \"debug\" : \"warn\" }).child(\"http\"),\n * retry: true,\n * });\n *\n * @param config - Base URL plus the optional auth, retry and fetch hooks.\n * @returns A client with `request`/`get`/`post`/`put`/`patch`/`delete`/`blob`/\n * `arrayBuffer`/`upload`.\n */\nexport function createApiClient(config: ApiClientConfig): ApiClient {\n const fetcher = config.fetcher ?? globalThis.fetch.bind(globalThis);\n\n /**\n * The `Authorization` header for a request, or nothing.\n *\n * Takes the resolved URL rather than reading `config.baseURL`, because an\n * absolute path overrides the base entirely (see `buildApiUrl`) and the\n * credential is scoped to an origin, not to a client.\n *\n * @param url - The absolute URL the request is going to.\n * @param skipAuth - Whether the caller opted this request out of auth.\n * @returns The header, or an empty object.\n */\n function authHeaders(url: string, skipAuth: boolean): Record<string, string> {\n if (skipAuth) return {};\n const token = config.getToken?.();\n if (!token) return {};\n if (!isTrustedCredentialTarget(url, config.baseURL, config.trustedOrigins)) {\n reportSuppressedCredential(url, config.baseURL);\n return {};\n }\n return { Authorization: `Bearer ${token}` };\n }\n\n async function rawRequest(\n path: string,\n options: RequestOptions,\n requestId: string | undefined,\n skipAuth: boolean,\n ): Promise<Response> {\n const { body, params, headers, signal, timeout, ...rest } = options;\n const isForm = isFormData(body);\n const configured = isForm ? config.uploadTimeout : config.timeout;\n const fallback = isForm ? DEFAULT_UPLOAD_TIMEOUT : DEFAULT_TIMEOUT;\n const limit =\n timeout !== undefined ? timeout : configured !== undefined ? configured : fallback;\n\n const url = buildApiUrl(config.baseURL, path, { prefix: config.prefix, params });\n\n const callerHeaders = headers as Record<string, string> | undefined;\n const finalHeaders: Record<string, string> = {\n ...(isForm ? {} : { \"Content-Type\": \"application/json\" }),\n ...(requestId ? { \"X-Request-ID\": requestId } : {}),\n ...config.headers,\n ...authHeaders(url, skipAuth),\n ...csrfHeaders({\n method: rest.method ?? \"GET\",\n url,\n reference: config.baseURL,\n csrf: config.csrf,\n trustedOrigins: config.trustedOrigins,\n headers: { ...config.headers, ...callerHeaders },\n }),\n ...callerHeaders,\n };\n\n const timed = withTimeout(signal, limit);\n const init: RequestInit = {\n ...rest,\n signal: timed.signal,\n headers: finalHeaders,\n credentials: config.withCredentials ? \"include\" : rest.credentials,\n body:\n body === undefined || body === null\n ? undefined\n : isForm\n ? (body as FormData)\n : JSON.stringify(body),\n };\n\n try {\n return await fetcher(url, init);\n } catch (cause) {\n if (timed.timedOut()) {\n throw new TempestApiError({\n status: 0,\n detail: `A requisição excedeu ${limit}ms e foi abandonada.`,\n });\n }\n throw cause;\n } finally {\n timed.dispose();\n }\n }\n\n async function send(\n path: string,\n options: RequestOptions,\n requestId: string,\n method: string,\n skipAuth: boolean,\n ): Promise<Response> {\n const log = config.logger;\n if (!log) return rawRequest(path, options, requestId, skipAuth);\n\n const startedAt = performance.now();\n try {\n const response = await rawRequest(path, options, requestId, skipAuth);\n const entry = { requestId, status: response.status, ms: elapsedMs(startedAt) };\n const line = `${method} ${path} → ${response.status}`;\n if (response.status >= 400) log.warn(line, entry);\n else log.debug(line, entry);\n return response;\n } catch (error) {\n log.warn(`${method} ${path} → no response`, {\n requestId,\n ms: elapsedMs(startedAt),\n error,\n });\n throw error;\n }\n }\n\n /**\n * Call `onUnauthorized`, keeping the request's own error unless the hook\n * says the attempt belongs to an ended session.\n *\n * @param response - The `401` that ended the attempt.\n * @param requestId - Correlation id for the log.\n * @param context - The credential and session the attempt left with.\n * @throws {SessionSupersededError} When `onUnauthorized` threw it.\n */\n async function notifyUnauthorized(\n response: Response,\n requestId: string,\n context: RequestAuthContext,\n ): Promise<void> {\n if (!config.onUnauthorized) return;\n config.logger?.warn(`unauthorized — calling onUnauthorized`, {\n requestId,\n status: response.status,\n });\n try {\n await config.onUnauthorized(response, context);\n } catch (error) {\n if (error instanceof SessionSupersededError) throw error;\n config.logger?.warn(`onUnauthorized threw — keeping the original response error`, {\n requestId,\n status: response.status,\n error,\n });\n }\n }\n\n /**\n * The credential and session an attempt leaves with, read just before it is\n * sent.\n *\n * @param skipAuth - Whether the attempt goes out without credentials.\n * @returns The context handed to `refresh` and `onUnauthorized`.\n */\n function authContext(skipAuth: boolean): RequestAuthContext {\n return {\n token: skipAuth ? null : (config.getToken?.() ?? null),\n epoch: config.getSessionEpoch?.() ?? null,\n };\n }\n\n async function attempt<T>(\n path: string,\n options: RequestOptions,\n decode: ResponseDecoder<T>,\n ): Promise<T> {\n const { skipAuth = false, skipAuthRetry = false, ...init } = options;\n const requestId = config.requestId ? config.requestId() : randomId();\n const method = (init.method ?? \"GET\").toUpperCase();\n const sent = authContext(skipAuth);\n let response = await send(path, init, requestId, method, skipAuth);\n\n if (response.status === 401 && !skipAuth && !skipAuthRetry) {\n if (config.refresh) {\n let replayed: RequestAuthContext;\n try {\n await config.refresh(sent);\n replayed = authContext(skipAuth);\n response = await send(path, init, requestId, method, skipAuth);\n } catch (error) {\n if (error instanceof SessionSupersededError) throw error;\n await notifyUnauthorized(response, requestId, sent);\n throw await parseError(response, requestId);\n }\n if (response.status === 401) {\n await notifyUnauthorized(response, requestId, replayed);\n }\n } else {\n await notifyUnauthorized(response, requestId, sent);\n }\n }\n\n if (!response.ok) {\n throw await parseError(response, requestId);\n }\n\n return decode(response);\n }\n\n async function run<T>(\n path: string,\n options: RequestOptions,\n decode: ResponseDecoder<T>,\n ): Promise<T> {\n const { retry: perRequest, ...rest } = options;\n const retryOptions = resolveRetry(perRequest !== undefined ? perRequest : config.retry);\n if (!retryOptions) return attempt<T>(path, rest, decode);\n\n const method = (rest.method ?? \"GET\").toUpperCase();\n return retryWithBackoff(() => attempt<T>(path, rest, decode), {\n ...retryOptions,\n shouldRetry:\n retryOptions.shouldRetry ?? ((error: unknown) => isRetriableFailure(error, method)),\n });\n }\n\n async function request<T>(path: string, options: RequestOptions = {}): Promise<T> {\n return run<T>(path, options, decodeByContentType);\n }\n\n async function upload<T>(\n path: string,\n formData: FormData,\n method: \"POST\" | \"PUT\" | \"PATCH\" = \"POST\",\n options?: Omit<RequestOptions, \"body\" | \"method\">,\n ): Promise<T> {\n return request<T>(path, { ...options, method, body: formData });\n }\n\n return {\n request,\n get: <T>(path: string, options?: RequestOptions) =>\n request<T>(path, { ...options, method: \"GET\" }),\n post: <T>(path: string, options?: RequestOptions) =>\n request<T>(path, { ...options, method: \"POST\" }),\n put: <T>(path: string, options?: RequestOptions) =>\n request<T>(path, { ...options, method: \"PUT\" }),\n patch: <T>(path: string, options?: RequestOptions) =>\n request<T>(path, { ...options, method: \"PATCH\" }),\n delete: <T>(path: string, options?: RequestOptions) =>\n request<T>(path, { ...options, method: \"DELETE\" }),\n blob: (path: string, options?: RequestOptions) =>\n run<Blob>(path, { ...options }, (response) => response.blob()),\n arrayBuffer: (path: string, options?: RequestOptions) =>\n run<ArrayBuffer>(path, { ...options }, (response) => response.arrayBuffer()),\n upload,\n };\n}\n"],"mappings":";;;;;;;;;AA8BA,IAAM,oBAA0C,IAAI,IAAI;CAAC;CAAO;CAAQ;AAAS,CAAC;AAoBlF,SAAS,EAAmB,GAAgB,GAAyB;CAGjE,OAFI,CAAC,EAAmB,IAAI,CAAM,KAC9B,EAAE,aAAiB,KAAyB,KACzC,EAAkB,EAAM,MAAM;AACzC;AAQA,SAAS,EAAa,GAAiE;CAEnF,OADK,IACE,MAAW,KAAO,CAAC,IAAI,IADV;AAExB;AAGA,IAAM,IAAkB,MAGlB,IAAyB;AAE/B,SAAS,EAAW,GAAiC;CACjD,OAAO,OAAO,WAAa,OAAe,aAAgB;AAC9D;AAaA,SAAS,EAAU,GAA2B;CAC1C,OAAO,KAAK,MAAM,YAAY,IAAI,IAAI,CAAS;AACnD;AAEA,eAAe,EAAW,GAAoB,GAAkD;CAC5F,IAAI;CACJ,IAAI;EACA,IAAO,MAAM,EAAS,MAAM,CA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I,EAAa,iBAAiB,MAAmB,EAAmB,GAAO,CAAM;EACzF,CAAC;CACL;CAEA,eAAe,EAAW,GAAc,IAA0B,CAAC,GAAe;EAC9E,OAAO,EAAO,GAAM,GAAS,CAAmB;CACpD;CAEA,eAAe,EACX,GACA,GACA,IAAmC,QACnC,GACU;EACV,OAAO,EAAW,GAAM;GAAE,GAAG;GAAS;GAAQ,MAAM;EAAS,CAAC;CAClE;CAEA,OAAO;EACH;EACA,MAAS,GAAc,MACnB,EAAW,GAAM;GAAE,GAAG;GAAS,QAAQ;EAAM,CAAC;EAClD,OAAU,GAAc,MACpB,EAAW,GAAM;GAAE,GAAG;GAAS,QAAQ;EAAO,CAAC;EACnD,MAAS,GAAc,MACnB,EAAW,GAAM;GAAE,GAAG;GAAS,QAAQ;EAAM,CAAC;EAClD,QAAW,GAAc,MACrB,EAAW,GAAM;GAAE,GAAG;GAAS,QAAQ;EAAQ,CAAC;EACpD,SAAY,GAAc,MACtB,EAAW,GAAM;GAAE,GAAG;GAAS,QAAQ;EAAS,CAAC;EACrD,OAAO,GAAc,MACjB,EAAU,GAAM,EAAE,GAAG,EAAQ,IAAI,MAAa,EAAS,KAAK,CAAC;EACjE,cAAc,GAAc,MACxB,EAAiB,GAAM,EAAE,GAAG,EAAQ,IAAI,MAAa,EAAS,YAAY,CAAC;EAC/E;CACJ;AACJ"}
@@ -1,2 +1,2 @@
1
- var e=class extends Error{status;detail;code;requestId;fields;body;constructor(e){super(e.detail),this.name=`TempestApiError`,this.status=e.status,this.detail=e.detail,this.code=e.code,this.requestId=e.requestId,this.fields=e.fields,this.body=e.body}};function t(e){return typeof e==`object`&&!!e&&typeof e.status==`number`&&typeof e.detail==`string`}var n=new Set([`body`,`query`,`path`,`header`,`cookie`]);function r(e){if(!Array.isArray(e))return;let t=e.filter(e=>typeof e==`string`||typeof e==`number`).filter((e,t)=>!(t===0&&n.has(String(e))));return t.length>0?t.join(`.`):void 0}var i=4;function a(e){if(!Array.isArray(e))return;let t={};for(let n of e){if(typeof n!=`object`||!n)continue;let e=n,i=r(e.loc);if(i===void 0||i in t)continue;let a=u(e.msg)??u(e.message);a!==void 0&&(t[i]=a)}return Object.keys(t).length>0?t:void 0}function o(e){return typeof e==`object`&&e&&!Array.isArray(e)?e:void 0}function s(e){if(e===null)return;let t=[o(e.detail)?.field,e.field,o(e.details)?.field];for(let e of t)if(typeof e==`string`&&e!==``)return e}function c(e,t){if(e===void 0||t===void 0)return e;let n=t.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`),r=e.replace(RegExp(`\\s+for field '${n}'(?:\\s+in\\s+'[^']*')?\\.?\\s*$`),``).trim();return r===``?e:r}function l(e,t){let n=a(e?.detail);if(n!==void 0)return n;let r=s(e);if(r!==void 0&&t!==void 0)return{[r]:t}}function u(e,t=0){if(e!=null){if(typeof e==`string`)return e===``?void 0:e;if(typeof e==`number`||typeof e==`boolean`)return String(e);if(!(t>=i)){if(Array.isArray(e)){let n=e.map(e=>{let n=u(e,t+1);if(n===void 0)return;let i=typeof e==`object`&&e?r(e.loc):void 0;return i===void 0?n:`${i}: ${n}`}).filter(e=>e!==void 0);return n.length>0?n.join(`; `):void 0}if(typeof e==`object`){let n=e;return u(n.msg,t+1)??u(n.message,t+1)??u(n.detail,t+1)}}}}var d=new Set([0,408,425,429]);function f(e){return d.has(e)||e>=500}function p(e){return`Erro ${e}`}function m(e,t,n,r){let i=typeof t==`object`&&t?t:null,a=c(u(i?.detail)??u(i?.message),s(i)),o=a??p(e),d=typeof i?.code==`string`?i.code:void 0,f=typeof i?.details==`object`&&i.details!==null?i.details:null;return{status:e,detail:o,code:d,requestId:(typeof f?.request_id==`string`?f.request_id:void 0)??n?.get(`X-Request-ID`)??r??void 0??void 0,retryAfter:h(n?.get(`Retry-After`)),fields:l(i,a),body:t}}function h(e){if(!e)return;let t=e.trim();if(/^\d+$/.test(t))return Number(t);let n=Date.parse(t);if(!Number.isNaN(n))return Math.max(0,Math.round((n-Date.now())/1e3))}exports.TempestApiError=e,exports.buildApiError=m,exports.isApiError=t,exports.isRetriableStatus=f,exports.parseRetryAfter=h,exports.syntheticDetail=p;
1
+ var e=class extends Error{status;detail;code;requestId;fields;body;constructor(e){super(e.detail),this.name=`TempestApiError`,this.status=e.status,this.detail=e.detail,this.code=e.code,this.requestId=e.requestId,this.fields=e.fields,this.body=e.body}},t=class extends Error{constructor(){super(`A sessão mudou antes de a operação terminar.`),this.name=`SessionSupersededError`}};function n(e){return typeof e==`object`&&!!e&&typeof e.status==`number`&&typeof e.detail==`string`}var r=new Set([`body`,`query`,`path`,`header`,`cookie`]);function i(e){if(!Array.isArray(e))return;let t=e.filter(e=>typeof e==`string`||typeof e==`number`).filter((e,t)=>!(t===0&&r.has(String(e))));return t.length>0?t.join(`.`):void 0}var a=4;function o(e){if(!Array.isArray(e))return;let t={};for(let n of e){if(typeof n!=`object`||!n)continue;let e=n,r=i(e.loc);if(r===void 0||r in t)continue;let a=d(e.msg)??d(e.message);a!==void 0&&(t[r]=a)}return Object.keys(t).length>0?t:void 0}function s(e){return typeof e==`object`&&e&&!Array.isArray(e)?e:void 0}function c(e){if(e===null)return;let t=[s(e.detail)?.field,e.field,s(e.details)?.field];for(let e of t)if(typeof e==`string`&&e!==``)return e}function l(e,t){if(e===void 0||t===void 0)return e;let n=t.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`),r=e.replace(RegExp(`\\s+for field '${n}'(?:\\s+in\\s+'[^']*')?\\.?\\s*$`),``).trim();return r===``?e:r}function u(e,t){let n=o(e?.detail);if(n!==void 0)return n;let r=c(e);if(r!==void 0&&t!==void 0)return{[r]:t}}function d(e,t=0){if(e!=null){if(typeof e==`string`)return e===``?void 0:e;if(typeof e==`number`||typeof e==`boolean`)return String(e);if(!(t>=a)){if(Array.isArray(e)){let n=e.map(e=>{let n=d(e,t+1);if(n===void 0)return;let r=typeof e==`object`&&e?i(e.loc):void 0;return r===void 0?n:`${r}: ${n}`}).filter(e=>e!==void 0);return n.length>0?n.join(`; `):void 0}if(typeof e==`object`){let n=e;return d(n.msg,t+1)??d(n.message,t+1)??d(n.detail,t+1)}}}}var f=new Set([0,408,425,429]);function p(e){return f.has(e)||e>=500}function m(e){return`Erro ${e}`}function h(e,t,n,r){let i=typeof t==`object`&&t?t:null,a=l(d(i?.detail)??d(i?.message),c(i)),o=a??m(e),s=typeof i?.code==`string`?i.code:void 0,f=typeof i?.details==`object`&&i.details!==null?i.details:null;return{status:e,detail:o,code:s,requestId:(typeof f?.request_id==`string`?f.request_id:void 0)??n?.get(`X-Request-ID`)??r??void 0??void 0,retryAfter:g(n?.get(`Retry-After`)),fields:u(i,a),body:t}}function g(e){if(!e)return;let t=e.trim();if(/^\d+$/.test(t))return Number(t);let n=Date.parse(t);if(!Number.isNaN(n))return Math.max(0,Math.round((n-Date.now())/1e3))}exports.SessionSupersededError=t,exports.TempestApiError=e,exports.buildApiError=h,exports.isApiError=n,exports.isRetriableStatus=p,exports.parseRetryAfter=g,exports.syntheticDetail=m;
2
2
  //# sourceMappingURL=errors.cjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"errors.cjs","names":[],"sources":["../../src/http/errors.ts"],"sourcesContent":["import type { ApiError } from \"./types\";\n\n/**\n * Error thrown by {@link createApiClient} / {@link uploadWithProgress} on a\n * non-2xx response. Mirrors the Tempest FastAPI SDK error envelope\n * (`{ detail, code, details.request_id }`) so callers get a typed `code` and a\n * `requestId` for log correlation, while still being a real `Error` (stack\n * trace, `instanceof Error`).\n *\n * @example\n * try {\n * await api.post(\"/users\", { body });\n * } catch (err) {\n * if (isApiError(err) && err.code === \"EMAIL_TAKEN\") {\n * showFieldError(\"email\", err.detail);\n * }\n * }\n */\nexport class TempestApiError extends Error implements ApiError {\n readonly status: number;\n readonly detail: string;\n readonly code?: string;\n readonly requestId?: string;\n readonly fields?: Record<string, string>;\n readonly body?: unknown;\n\n constructor(init: ApiError) {\n super(init.detail);\n this.name = \"TempestApiError\";\n this.status = init.status;\n this.detail = init.detail;\n this.code = init.code;\n this.requestId = init.requestId;\n this.fields = init.fields;\n this.body = init.body;\n }\n}\n\n/**\n * Type guard for the {@link ApiError} shape. Matches both {@link TempestApiError}\n * instances and plain objects carrying `status` + `detail`.\n *\n * @param error - The unknown value (typically a caught error).\n * @returns Whether `error` conforms to the `ApiError` contract.\n */\nexport function isApiError(error: unknown): error is ApiError {\n return (\n typeof error === \"object\" &&\n error !== null &&\n typeof (error as ApiError).status === \"number\" &&\n typeof (error as ApiError).detail === \"string\"\n );\n}\n\n/**\n * Location prefixes FastAPI puts at the head of a validation error's `loc`,\n * naming the part of the request rather than the field. Dropped from the\n * rendered path, so `[\"body\", \"email\"]` reads as `email`.\n */\nconst LOC_ROOTS: ReadonlySet<string> = new Set([\"body\", \"query\", \"path\", \"header\", \"cookie\"]);\n\n/**\n * Render a FastAPI validation error's `loc` tuple as a dotted field path.\n *\n * @param loc - The raw `loc` value from one validation error entry.\n * @returns The dotted path (`\"items.0.price\"`), or undefined when `loc` carries\n * nothing addressable.\n */\nfunction formatLoc(loc: unknown): string | undefined {\n if (!Array.isArray(loc)) return undefined;\n const parts = loc\n .filter(\n (part): part is string | number => typeof part === \"string\" || typeof part === \"number\",\n )\n .filter((part, index) => !(index === 0 && LOC_ROOTS.has(String(part))));\n return parts.length > 0 ? parts.join(\".\") : undefined;\n}\n\n/**\n * How deep {@link normalizeDetail} follows a nested `detail` before giving up.\n *\n * A real envelope needs two or three levels: the list, an entry, the entry's\n * own `detail`. The cap exists because the body is untrusted input arriving on\n * the error path — a response nesting `{\"detail\":{\"detail\":…}}` twenty thousand\n * deep (a 220 KB body) overflowed the stack, and a `RangeError` thrown while\n * *building* the error is worse than the error: the caller's `catch` stops\n * receiving a `TempestApiError`, so `isApiError` is false, `describeApiError`\n * has nothing to read and the `401` handling never runs.\n */\nconst MAX_DETAIL_DEPTH = 4;\n\n/**\n * Pull field-level messages out of a validation `detail` **list**.\n *\n * FastAPI's `422` body is `detail: [{ loc, msg, type }]`, which is exactly what\n * a form needs and exactly what the flattened `detail` string destroys. Only the\n * top level is read: a validation error names one field per entry, and following\n * nesting here would invent paths the backend never sent.\n *\n * This is one of two ways a body names a field — see {@link collectFields}, which\n * is the entry point and falls back to the singular keys when the list names\n * nothing addressable.\n *\n * @param raw - The `detail` value from the error body.\n * @returns Field path to message, or undefined when the body is not a\n * validation list (or carries no entry naming a field).\n */\nfunction collectListFields(raw: unknown): Record<string, string> | undefined {\n if (!Array.isArray(raw)) return undefined;\n\n const fields: Record<string, string> = {};\n for (const entry of raw) {\n if (typeof entry !== \"object\" || entry === null) continue;\n const record = entry as Record<string, unknown>;\n const field = formatLoc(record.loc);\n if (field === undefined || field in fields) continue;\n const message = normalizeDetail(record.msg) ?? normalizeDetail(record.message);\n if (message === undefined) continue;\n fields[field] = message;\n }\n\n return Object.keys(fields).length > 0 ? fields : undefined;\n}\n\n/**\n * Narrow a value to a plain object — a record, and not an array.\n *\n * Arrays are excluded because `typeof [] === \"object\"` while a list means\n * something else entirely here: FastAPI's `detail` list is read by\n * {@link collectListFields}, and reading `.field` off it would only ever be\n * undefined.\n *\n * @param value - The candidate value from the error body.\n * @returns The value as a record, or undefined when it is not a plain object.\n */\nfunction plainRecord(value: unknown): Record<string, unknown> | undefined {\n return typeof value === \"object\" && value !== null && !Array.isArray(value)\n ? (value as Record<string, unknown>)\n : undefined;\n}\n\n/**\n * Read the field a **singular** error envelope names.\n *\n * A backend built on `tempest-fastapi-sdk` never answers with FastAPI's `detail`\n * list once it owns the handler: it names the guilty field in a key beside the\n * message. Three shapes are seen in the wild, and they are read inner-out:\n *\n * 1. `detail.field` — the field sits in the same object as the message it\n * describes (`{ detail: { detail: \"Cidade não encontrada…\", field: \"city\" } }`),\n * so it is the least ambiguous claim about which message belongs to which input.\n * 2. `field` at the top level — a flattened `RequestValidationError`\n * (`{ detail: \"Value error, … for field 'phone' in 'body'\", field: \"phone\" }`)\n * makes the same claim one level out.\n * 3. `details.field` — `details` is the envelope's free-form context bag, not a\n * validation channel, and its `field` may be about something no input on screen\n * carries (an unknown sort column, say). It answers last for exactly that reason.\n *\n * `location` (`\"body -> phone\"`) is deliberately not parsed: it renders the same\n * path `field` already names, no observed envelope sends it without `field`, and\n * splitting an arrow-separated string would invent a path the backend never sent.\n *\n * @param body - The parsed error body, or null when it was not an object.\n * @returns The field name, or undefined when none of the three keys carried a\n * non-empty string — anything else is not usable as a key on `fields`.\n */\nfunction namedField(body: Record<string, unknown> | null): string | undefined {\n if (body === null) return undefined;\n const candidates: readonly unknown[] = [\n plainRecord(body.detail)?.field,\n body.field,\n plainRecord(body.details)?.field,\n ];\n for (const candidate of candidates) {\n if (typeof candidate === \"string\" && candidate !== \"\") return candidate;\n }\n return undefined;\n}\n\n/**\n * Drop the machine-readable tail a `tempest-fastapi-sdk` backend appends.\n *\n * That backend flattens a field error into\n * `\"CPF ou CNPJ inválido for field 'cpf_cnpj' in 'body'\"` — a finished sentence\n * in the app's language with an English clause glued to the end. The clause\n * carries nothing new: the same two values arrive as `field` and `location` on\n * the envelope, which is where `ApiError.fields` reads them from. Left in, it\n * reaches the user, and every consuming app grew its own regex to shave it off.\n *\n * The trim only fires when the field the tail names is the field the envelope\n * resolved to. That is what keeps it from deleting text it cannot account for:\n * a tail naming some other field is either a different envelope shape or a\n * sentence that genuinely reads that way, and both are left alone.\n *\n * @param message - The readable message, or undefined when the body had none.\n * @param field - The field name {@link namedField} resolved, if any.\n * @returns The message without the tail, or the message unchanged.\n */\nfunction trimFieldSuffix(\n message: string | undefined,\n field: string | undefined,\n): string | undefined {\n if (message === undefined || field === undefined) return message;\n const escaped = field.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n const trimmed = message\n .replace(new RegExp(`\\\\s+for field '${escaped}'(?:\\\\s+in\\\\s+'[^']*')?\\\\.?\\\\s*$`), \"\")\n .trim();\n return trimmed === \"\" ? message : trimmed;\n}\n\n/**\n * Index the body's field-level messages, whichever envelope carried them.\n *\n * The single entry point behind `ApiError.fields`, and it applies two rules the\n * tests pin:\n *\n * - FastAPI's `detail` list wins whenever it names at least one addressable\n * field. A plain FastAPI app still answers a schema-level `422` with that list\n * even on a `tempest-fastapi-sdk` backend, so it stays authoritative.\n * - A named field with no readable message produces nothing. The only string\n * left at that point is the synthetic `Erro <status>`, and `{ phone: \"Erro 422\" }`\n * on an input is noise rather than an error message.\n *\n * @param body - The parsed error body, or null when it was not an object.\n * @param message - The readable message the same body produced, before the\n * synthetic fallback — the string that also becomes `ApiError.detail`.\n * @returns Field name to message, or undefined when nothing named a field.\n */\nfunction collectFields(\n body: Record<string, unknown> | null,\n message: string | undefined,\n): Record<string, string> | undefined {\n const listed = collectListFields(body?.detail);\n if (listed !== undefined) return listed;\n const field = namedField(body);\n if (field === undefined || message === undefined) return undefined;\n return { [field]: message };\n}\n\n/**\n * Collapse a backend `detail` of any shape into a single readable line.\n *\n * FastAPI answers a `422` with `detail` as a **list** of\n * `{ loc, msg, type }` entries, not a string. Passing that through `String()`\n * yields `\"[object Object]\"` — an error message that tells the user nothing and\n * hides which field failed. Each entry becomes `\"<field>: <msg>\"` and the\n * entries are joined with `\"; \"`; a nested object is read through its\n * `msg`/`message`/`detail` string.\n *\n * @param raw - The `detail` (or `message`) value from the error body.\n * @param depth - Current nesting level. Past {@link MAX_DETAIL_DEPTH} the value\n * is treated as unreadable instead of followed further.\n * @returns The rendered message, or undefined when nothing readable is there —\n * letting the caller fall back to the synthetic `Erro <status>`.\n */\nfunction normalizeDetail(raw: unknown, depth: number = 0): string | undefined {\n if (raw === null || raw === undefined) return undefined;\n if (typeof raw === \"string\") return raw === \"\" ? undefined : raw;\n if (typeof raw === \"number\" || typeof raw === \"boolean\") return String(raw);\n if (depth >= MAX_DETAIL_DEPTH) return undefined;\n\n if (Array.isArray(raw)) {\n const lines = raw\n .map((entry) => {\n const message = normalizeDetail(entry, depth + 1);\n if (message === undefined) return undefined;\n const field =\n typeof entry === \"object\" && entry !== null\n ? formatLoc((entry as Record<string, unknown>).loc)\n : undefined;\n return field === undefined ? message : `${field}: ${message}`;\n })\n .filter((line): line is string => line !== undefined);\n return lines.length > 0 ? lines.join(\"; \") : undefined;\n }\n\n if (typeof raw === \"object\") {\n const entry = raw as Record<string, unknown>;\n return (\n normalizeDetail(entry.msg, depth + 1) ??\n normalizeDetail(entry.message, depth + 1) ??\n normalizeDetail(entry.detail, depth + 1)\n );\n }\n\n return undefined;\n}\n\n/**\n * Statuses worth a second attempt, as a set for the sub-500 cases.\n *\n * A network failure (status `0`), a request timeout, a too-early replay, and a\n * rate limit — which usually carries the `Retry-After` the backoff honours.\n * Everything else below 500 is the server refusing on purpose.\n */\nconst RETRIABLE_STATUSES: ReadonlySet<number> = new Set([0, 408, 425, 429]);\n\n/**\n * Whether an HTTP status describes a condition a replay can plausibly fix.\n *\n * The single owner of that decision. It used to be spelled out in three places —\n * the client's own policy, the react-query default and the bare `retry()` helper\n * — and they had already drifted: the query default was missing `425`, so the\n * same `425 Too Early` was replayed through `createApiClient({ retry: true })`\n * and not replayed through `useQuery`. Same app, same error, two behaviours, and\n * no test caught it because each file asserted against its own copy.\n *\n * Deliberately about the status and nothing else. Whether a *non*-API error is\n * worth replaying, and whether the request's method may be replayed at all, are\n * the caller's calls: {@link createApiClient} refuses a non-idempotent method,\n * while a bare `retry()` has no method to inspect.\n *\n * @example\n * await api.get(\"/report\", {\n * retry: { shouldRetry: (error) => isApiError(error) && isRetriableStatus(error.status) },\n * });\n *\n * @param status - The HTTP status, where `0` means the request never landed.\n * @returns Whether a retry is worth attempting.\n */\nexport function isRetriableStatus(status: number): boolean {\n return RETRIABLE_STATUSES.has(status) || status >= 500;\n}\n\n/**\n * Detail text synthesised when a response body carries none.\n *\n * Exported because {@link describeApiError} has to recognise it: a detail the\n * server never sent says strictly less than the caller's own fallback, so the\n * funnel drops it. Comparing against a copied literal would silently stop\n * matching the day this sentence is reworded — no type error, no failing test.\n *\n * @param status - The HTTP status of the error.\n * @returns The synthetic detail for that status.\n */\nexport function syntheticDetail(status: number): string {\n return `Erro ${status}`;\n}\n\n/**\n * Parse an error body + response into the Tempest {@link ApiError} envelope.\n *\n * Reads `detail`/`message`, the programmatic `code`, and the correlation id\n * from `details.request_id` (falling back to the `X-Request-ID` header, then\n * the id the client sent).\n *\n * A `422` from FastAPI carries `detail` as a list of `{ loc, msg, type }`\n * entries, so it is flattened to `\"<field>: <msg>; <field>: <msg>\"` instead of\n * being stringified into `\"[object Object]\"`, and the same entries are indexed\n * on `fields` (`{ email: \"Field required\" }`) for a form to consume without\n * parsing that line back apart. The untouched body stays on `body`.\n *\n * A backend that owns its handlers — every `tempest-fastapi-sdk` app — sends no\n * such list, and names the field in a key instead:\n *\n * ```json\n * { \"detail\": \"Value error, … for field 'phone' in 'body'\", \"field\": \"phone\" }\n * { \"detail\": { \"detail\": \"Cidade não encontrada…\", \"field\": \"city\" },\n * \"code\": \"VALIDATION_ERROR\", \"details\": { \"field\": \"city\" } }\n * ```\n *\n * Those are indexed too, keyed by the field the backend named and valued with the\n * same sentence that becomes `detail`. Precedence is the list first, then\n * `detail.field`, `field`, `details.field` — see {@link collectFields}.\n *\n * A flattened `detail` from the list is developer-facing: it carries the\n * backend's field paths and the validator's own wording. `describeApiError` knows\n * not to show it to a person when `fields` is set — which now also covers a\n * business error that named a field, whose `detail` was a finished sentence. That\n * sentence is not lost: it is on `fields`, attached to the input that failed.\n *\n * @param status - HTTP status code.\n * @param body - The parsed error body (object, string, or null).\n * @param headers - The response headers (for the `X-Request-ID` fallback).\n * @param sentRequestId - The id the client sent on the request, if any.\n * @returns A fully-populated `ApiError`.\n *\n * @tempest-limits param-count — the arguments are the response as it arrives\n * (`status`, `body`, `headers`) plus the id the request was sent with, and they are\n * passed at exactly three places, all of them a client's response path\n * (`createApiClient`, `uploadWithProgress`, `createResumableUpload`). Wrapping them\n * in an options object would name each argument twice at every call site to say\n * nothing new.\n */\nexport function buildApiError(\n status: number,\n body: unknown,\n headers?: Headers | { get(name: string): string | null },\n sentRequestId?: string,\n): ApiError {\n const obj =\n typeof body === \"object\" && body !== null ? (body as Record<string, unknown>) : null;\n const message = trimFieldSuffix(\n normalizeDetail(obj?.detail) ?? normalizeDetail(obj?.message),\n namedField(obj),\n );\n const detail = message ?? syntheticDetail(status);\n const code = typeof obj?.code === \"string\" ? obj.code : undefined;\n const details =\n typeof obj?.details === \"object\" && obj.details !== null\n ? (obj.details as Record<string, unknown>)\n : null;\n const requestId =\n (typeof details?.request_id === \"string\" ? details.request_id : undefined) ??\n headers?.get(\"X-Request-ID\") ??\n sentRequestId ??\n undefined;\n\n return {\n status,\n detail,\n code,\n requestId: requestId ?? undefined,\n retryAfter: parseRetryAfter(headers?.get(\"Retry-After\")),\n fields: collectFields(obj, message),\n body,\n };\n}\n\n/**\n * Parse a `Retry-After` header into seconds. Accepts a delta-seconds integer\n * (`\"120\"`) or an HTTP-date (`\"Wed, 21 Oct 2015 07:28:00 GMT\"`).\n *\n * @param value - The raw header value, or null.\n * @returns The delay in seconds (>= 0), or undefined when absent/unparseable.\n */\nexport function parseRetryAfter(value: string | null | undefined): number | undefined {\n if (!value) return undefined;\n const trimmed = value.trim();\n if (/^\\d+$/.test(trimmed)) return Number(trimmed);\n const when = Date.parse(trimmed);\n if (Number.isNaN(when)) return undefined;\n return Math.max(0, Math.round((when - Date.now()) / 1000));\n}\n"],"mappings":"AAkBA,IAAa,EAAb,cAAqC,KAA0B,CAC3D,OACA,OACA,KACA,UACA,OACA,KAEA,YAAY,EAAgB,CACxB,MAAM,EAAK,MAAM,EACjB,KAAK,KAAO,kBACZ,KAAK,OAAS,EAAK,OACnB,KAAK,OAAS,EAAK,OACnB,KAAK,KAAO,EAAK,KACjB,KAAK,UAAY,EAAK,UACtB,KAAK,OAAS,EAAK,OACnB,KAAK,KAAO,EAAK,IACrB,CACJ,EASA,SAAgB,EAAW,EAAmC,CAC1D,OACI,OAAO,GAAU,YACjB,GACA,OAAQ,EAAmB,QAAW,UACtC,OAAQ,EAAmB,QAAW,QAE9C,CAOA,IAAM,EAAiC,IAAI,IAAI,CAAC,OAA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gB,EAAkB,EAAyB,CACvD,OAAO,EAAmB,IAAI,CAAM,GAAK,GAAU,GACvD,CAaA,SAAgB,EAAgB,EAAwB,CACpD,MAAO,QAAQ,GACnB,CA+CA,SAAgB,EACZ,EACA,EACA,EACA,EACQ,CACR,IAAM,EACF,OAAO,GAAS,UAAY,EAAiB,EAAmC,KAC9E,EAAU,EACZ,EAAgB,GAAK,MAAM,GAAK,EAAgB,GAAK,OAAO,EAC5D,EAAW,CAAG,CAClB,EACM,EAAS,GAAW,EAAgB,CAAM,EAC1C,EAAO,OAAO,GAAK,MAAS,SAAW,EAAI,KAAO,IAAA,GAClD,EACF,OAAO,GAAK,SAAY,UAAY,EAAI,UAAY,KAC7C,EAAI,QACL,KAOV,MAAO,CACH,SACA,SACA,OACA,WATC,OAAO,GAAS,YAAe,SAAW,EAAQ,WAAa,IAAA,KAChE,GAAS,IAAI,cAAc,GAC3B,GACA,IAAA,IAMwB,IAAA,GACxB,WAAY,EAAgB,GAAS,IAAI,aAAa,CAAC,EACvD,OAAQ,EAAc,EAAK,CAAO,EAClC,MACJ,CACJ,CASA,SAAgB,EAAgB,EAAsD,CAClF,GAAI,CAAC,EAAO,OACZ,IAAM,EAAU,EAAM,KAAK,EAC3B,GAAI,QAAQ,KAAK,CAAO,EAAG,OAAO,OAAO,CAAO,EAChD,IAAM,EAAO,KAAK,MAAM,CAAO,EAC3B,WAAO,MAAM,CAAI,EACrB,OAAO,KAAK,IAAI,EAAG,KAAK,OAAO,EAAO,KAAK,IAAI,GAAK,GAAI,CAAC,CAC7D"}
1
+ {"version":3,"file":"errors.cjs","names":[],"sources":["../../src/http/errors.ts"],"sourcesContent":["import type { ApiError } from \"./types\";\n\n/**\n * Error thrown by {@link createApiClient} / {@link uploadWithProgress} on a\n * non-2xx response. Mirrors the Tempest FastAPI SDK error envelope\n * (`{ detail, code, details.request_id }`) so callers get a typed `code` and a\n * `requestId` for log correlation, while still being a real `Error` (stack\n * trace, `instanceof Error`).\n *\n * @example\n * try {\n * await api.post(\"/users\", { body });\n * } catch (err) {\n * if (isApiError(err) && err.code === \"EMAIL_TAKEN\") {\n * showFieldError(\"email\", err.detail);\n * }\n * }\n */\nexport class TempestApiError extends Error implements ApiError {\n readonly status: number;\n readonly detail: string;\n readonly code?: string;\n readonly requestId?: string;\n readonly fields?: Record<string, string>;\n readonly body?: unknown;\n\n constructor(init: ApiError) {\n super(init.detail);\n this.name = \"TempestApiError\";\n this.status = init.status;\n this.detail = init.detail;\n this.code = init.code;\n this.requestId = init.requestId;\n this.fields = init.fields;\n this.body = init.body;\n }\n}\n\n/**\n * Thrown when the session that started an operation is no longer the current\n * one by the time it settles: a `refresh` hook (rethrown by\n * {@link createApiClient}), or a `createTempestAuth` `login()` whose session\n * was replaced while it waited on the previous session's teardown.\n *\n * A refresh is a network round trip, and the session can end or change hands\n * during it: the user signs out, or signs out and another account signs in. The\n * tokens that refresh brings back belong to the session that ended, so they are\n * discarded instead of installed, and the request that was waiting on them is\n * not replayed — replaying it would send it as whoever is signed in now.\n *\n * This is deliberately not an unauthorized outcome. The client does **not** call\n * `onUnauthorized` for it: that callback ends the session, and the current\n * session — possibly a different account that just signed in — did nothing\n * wrong. Treat it like an aborted request: drop the result, show nothing.\n *\n * @example\n * try {\n * await api.get(\"/api/orders\");\n * } catch (err) {\n * if (err instanceof SessionSupersededError) return;\n * throw err;\n * }\n */\nexport class SessionSupersededError extends Error {\n constructor() {\n super(\"A sessão mudou antes de a operação terminar.\");\n this.name = \"SessionSupersededError\";\n }\n}\n\n/**\n * Type guard for the {@link ApiError} shape. Matches both {@link TempestApiError}\n * instances and plain objects carrying `status` + `detail`.\n *\n * @param error - The unknown value (typically a caught error).\n * @returns Whether `error` conforms to the `ApiError` contract.\n */\nexport function isApiError(error: unknown): error is ApiError {\n return (\n typeof error === \"object\" &&\n error !== null &&\n typeof (error as ApiError).status === \"number\" &&\n typeof (error as ApiError).detail === \"string\"\n );\n}\n\n/**\n * Location prefixes FastAPI puts at the head of a validation error's `loc`,\n * naming the part of the request rather than the field. Dropped from the\n * rendered path, so `[\"body\", \"email\"]` reads as `email`.\n */\nconst LOC_ROOTS: ReadonlySet<string> = new Set([\"body\", \"query\", \"path\", \"header\", \"cookie\"]);\n\n/**\n * Render a FastAPI validation error's `loc` tuple as a dotted field path.\n *\n * @param loc - The raw `loc` value from one validation error entry.\n * @returns The dotted path (`\"items.0.price\"`), or undefined when `loc` carries\n * nothing addressable.\n */\nfunction formatLoc(loc: unknown): string | undefined {\n if (!Array.isArray(loc)) return undefined;\n const parts = loc\n .filter(\n (part): part is string | number => typeof part === \"string\" || typeof part === \"number\",\n )\n .filter((part, index) => !(index === 0 && LOC_ROOTS.has(String(part))));\n return parts.length > 0 ? parts.join(\".\") : undefined;\n}\n\n/**\n * How deep {@link normalizeDetail} follows a nested `detail` before giving up.\n *\n * A real envelope needs two or three levels: the list, an entry, the entry's\n * own `detail`. The cap exists because the body is untrusted input arriving on\n * the error path — a response nesting `{\"detail\":{\"detail\":…}}` twenty thousand\n * deep (a 220 KB body) overflowed the stack, and a `RangeError` thrown while\n * *building* the error is worse than the error: the caller's `catch` stops\n * receiving a `TempestApiError`, so `isApiError` is false, `describeApiError`\n * has nothing to read and the `401` handling never runs.\n */\nconst MAX_DETAIL_DEPTH = 4;\n\n/**\n * Pull field-level messages out of a validation `detail` **list**.\n *\n * FastAPI's `422` body is `detail: [{ loc, msg, type }]`, which is exactly what\n * a form needs and exactly what the flattened `detail` string destroys. Only the\n * top level is read: a validation error names one field per entry, and following\n * nesting here would invent paths the backend never sent.\n *\n * This is one of two ways a body names a field — see {@link collectFields}, which\n * is the entry point and falls back to the singular keys when the list names\n * nothing addressable.\n *\n * @param raw - The `detail` value from the error body.\n * @returns Field path to message, or undefined when the body is not a\n * validation list (or carries no entry naming a field).\n */\nfunction collectListFields(raw: unknown): Record<string, string> | undefined {\n if (!Array.isArray(raw)) return undefined;\n\n const fields: Record<string, string> = {};\n for (const entry of raw) {\n if (typeof entry !== \"object\" || entry === null) continue;\n const record = entry as Record<string, unknown>;\n const field = formatLoc(record.loc);\n if (field === undefined || field in fields) continue;\n const message = normalizeDetail(record.msg) ?? normalizeDetail(record.message);\n if (message === undefined) continue;\n fields[field] = message;\n }\n\n return Object.keys(fields).length > 0 ? fields : undefined;\n}\n\n/**\n * Narrow a value to a plain object — a record, and not an array.\n *\n * Arrays are excluded because `typeof [] === \"object\"` while a list means\n * something else entirely here: FastAPI's `detail` list is read by\n * {@link collectListFields}, and reading `.field` off it would only ever be\n * undefined.\n *\n * @param value - The candidate value from the error body.\n * @returns The value as a record, or undefined when it is not a plain object.\n */\nfunction plainRecord(value: unknown): Record<string, unknown> | undefined {\n return typeof value === \"object\" && value !== null && !Array.isArray(value)\n ? (value as Record<string, unknown>)\n : undefined;\n}\n\n/**\n * Read the field a **singular** error envelope names.\n *\n * A backend built on `tempest-fastapi-sdk` never answers with FastAPI's `detail`\n * list once it owns the handler: it names the guilty field in a key beside the\n * message. Three shapes are seen in the wild, and they are read inner-out:\n *\n * 1. `detail.field` — the field sits in the same object as the message it\n * describes (`{ detail: { detail: \"Cidade não encontrada…\", field: \"city\" } }`),\n * so it is the least ambiguous claim about which message belongs to which input.\n * 2. `field` at the top level — a flattened `RequestValidationError`\n * (`{ detail: \"Value error, … for field 'phone' in 'body'\", field: \"phone\" }`)\n * makes the same claim one level out.\n * 3. `details.field` — `details` is the envelope's free-form context bag, not a\n * validation channel, and its `field` may be about something no input on screen\n * carries (an unknown sort column, say). It answers last for exactly that reason.\n *\n * `location` (`\"body -> phone\"`) is deliberately not parsed: it renders the same\n * path `field` already names, no observed envelope sends it without `field`, and\n * splitting an arrow-separated string would invent a path the backend never sent.\n *\n * @param body - The parsed error body, or null when it was not an object.\n * @returns The field name, or undefined when none of the three keys carried a\n * non-empty string — anything else is not usable as a key on `fields`.\n */\nfunction namedField(body: Record<string, unknown> | null): string | undefined {\n if (body === null) return undefined;\n const candidates: readonly unknown[] = [\n plainRecord(body.detail)?.field,\n body.field,\n plainRecord(body.details)?.field,\n ];\n for (const candidate of candidates) {\n if (typeof candidate === \"string\" && candidate !== \"\") return candidate;\n }\n return undefined;\n}\n\n/**\n * Drop the machine-readable tail a `tempest-fastapi-sdk` backend appends.\n *\n * That backend flattens a field error into\n * `\"CPF ou CNPJ inválido for field 'cpf_cnpj' in 'body'\"` — a finished sentence\n * in the app's language with an English clause glued to the end. The clause\n * carries nothing new: the same two values arrive as `field` and `location` on\n * the envelope, which is where `ApiError.fields` reads them from. Left in, it\n * reaches the user, and every consuming app grew its own regex to shave it off.\n *\n * The trim only fires when the field the tail names is the field the envelope\n * resolved to. That is what keeps it from deleting text it cannot account for:\n * a tail naming some other field is either a different envelope shape or a\n * sentence that genuinely reads that way, and both are left alone.\n *\n * @param message - The readable message, or undefined when the body had none.\n * @param field - The field name {@link namedField} resolved, if any.\n * @returns The message without the tail, or the message unchanged.\n */\nfunction trimFieldSuffix(\n message: string | undefined,\n field: string | undefined,\n): string | undefined {\n if (message === undefined || field === undefined) return message;\n const escaped = field.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n const trimmed = message\n .replace(new RegExp(`\\\\s+for field '${escaped}'(?:\\\\s+in\\\\s+'[^']*')?\\\\.?\\\\s*$`), \"\")\n .trim();\n return trimmed === \"\" ? message : trimmed;\n}\n\n/**\n * Index the body's field-level messages, whichever envelope carried them.\n *\n * The single entry point behind `ApiError.fields`, and it applies two rules the\n * tests pin:\n *\n * - FastAPI's `detail` list wins whenever it names at least one addressable\n * field. A plain FastAPI app still answers a schema-level `422` with that list\n * even on a `tempest-fastapi-sdk` backend, so it stays authoritative.\n * - A named field with no readable message produces nothing. The only string\n * left at that point is the synthetic `Erro <status>`, and `{ phone: \"Erro 422\" }`\n * on an input is noise rather than an error message.\n *\n * @param body - The parsed error body, or null when it was not an object.\n * @param message - The readable message the same body produced, before the\n * synthetic fallback — the string that also becomes `ApiError.detail`.\n * @returns Field name to message, or undefined when nothing named a field.\n */\nfunction collectFields(\n body: Record<string, unknown> | null,\n message: string | undefined,\n): Record<string, string> | undefined {\n const listed = collectListFields(body?.detail);\n if (listed !== undefined) return listed;\n const field = namedField(body);\n if (field === undefined || message === undefined) return undefined;\n return { [field]: message };\n}\n\n/**\n * Collapse a backend `detail` of any shape into a single readable line.\n *\n * FastAPI answers a `422` with `detail` as a **list** of\n * `{ loc, msg, type }` entries, not a string. Passing that through `String()`\n * yields `\"[object Object]\"` — an error message that tells the user nothing and\n * hides which field failed. Each entry becomes `\"<field>: <msg>\"` and the\n * entries are joined with `\"; \"`; a nested object is read through its\n * `msg`/`message`/`detail` string.\n *\n * @param raw - The `detail` (or `message`) value from the error body.\n * @param depth - Current nesting level. Past {@link MAX_DETAIL_DEPTH} the value\n * is treated as unreadable instead of followed further.\n * @returns The rendered message, or undefined when nothing readable is there —\n * letting the caller fall back to the synthetic `Erro <status>`.\n */\nfunction normalizeDetail(raw: unknown, depth: number = 0): string | undefined {\n if (raw === null || raw === undefined) return undefined;\n if (typeof raw === \"string\") return raw === \"\" ? undefined : raw;\n if (typeof raw === \"number\" || typeof raw === \"boolean\") return String(raw);\n if (depth >= MAX_DETAIL_DEPTH) return undefined;\n\n if (Array.isArray(raw)) {\n const lines = raw\n .map((entry) => {\n const message = normalizeDetail(entry, depth + 1);\n if (message === undefined) return undefined;\n const field =\n typeof entry === \"object\" && entry !== null\n ? formatLoc((entry as Record<string, unknown>).loc)\n : undefined;\n return field === undefined ? message : `${field}: ${message}`;\n })\n .filter((line): line is string => line !== undefined);\n return lines.length > 0 ? lines.join(\"; \") : undefined;\n }\n\n if (typeof raw === \"object\") {\n const entry = raw as Record<string, unknown>;\n return (\n normalizeDetail(entry.msg, depth + 1) ??\n normalizeDetail(entry.message, depth + 1) ??\n normalizeDetail(entry.detail, depth + 1)\n );\n }\n\n return undefined;\n}\n\n/**\n * Statuses worth a second attempt, as a set for the sub-500 cases.\n *\n * A network failure (status `0`), a request timeout, a too-early replay, and a\n * rate limit — which usually carries the `Retry-After` the backoff honours.\n * Everything else below 500 is the server refusing on purpose.\n */\nconst RETRIABLE_STATUSES: ReadonlySet<number> = new Set([0, 408, 425, 429]);\n\n/**\n * Whether an HTTP status describes a condition a replay can plausibly fix.\n *\n * The single owner of that decision. It used to be spelled out in three places —\n * the client's own policy, the react-query default and the bare `retry()` helper\n * — and they had already drifted: the query default was missing `425`, so the\n * same `425 Too Early` was replayed through `createApiClient({ retry: true })`\n * and not replayed through `useQuery`. Same app, same error, two behaviours, and\n * no test caught it because each file asserted against its own copy.\n *\n * Deliberately about the status and nothing else. Whether a *non*-API error is\n * worth replaying, and whether the request's method may be replayed at all, are\n * the caller's calls: {@link createApiClient} refuses a non-idempotent method,\n * while a bare `retry()` has no method to inspect.\n *\n * @example\n * await api.get(\"/report\", {\n * retry: { shouldRetry: (error) => isApiError(error) && isRetriableStatus(error.status) },\n * });\n *\n * @param status - The HTTP status, where `0` means the request never landed.\n * @returns Whether a retry is worth attempting.\n */\nexport function isRetriableStatus(status: number): boolean {\n return RETRIABLE_STATUSES.has(status) || status >= 500;\n}\n\n/**\n * Detail text synthesised when a response body carries none.\n *\n * Exported because {@link describeApiError} has to recognise it: a detail the\n * server never sent says strictly less than the caller's own fallback, so the\n * funnel drops it. Comparing against a copied literal would silently stop\n * matching the day this sentence is reworded — no type error, no failing test.\n *\n * @param status - The HTTP status of the error.\n * @returns The synthetic detail for that status.\n */\nexport function syntheticDetail(status: number): string {\n return `Erro ${status}`;\n}\n\n/**\n * Parse an error body + response into the Tempest {@link ApiError} envelope.\n *\n * Reads `detail`/`message`, the programmatic `code`, and the correlation id\n * from `details.request_id` (falling back to the `X-Request-ID` header, then\n * the id the client sent).\n *\n * A `422` from FastAPI carries `detail` as a list of `{ loc, msg, type }`\n * entries, so it is flattened to `\"<field>: <msg>; <field>: <msg>\"` instead of\n * being stringified into `\"[object Object]\"`, and the same entries are indexed\n * on `fields` (`{ email: \"Field required\" }`) for a form to consume without\n * parsing that line back apart. The untouched body stays on `body`.\n *\n * A backend that owns its handlers — every `tempest-fastapi-sdk` app — sends no\n * such list, and names the field in a key instead:\n *\n * ```json\n * { \"detail\": \"Value error, … for field 'phone' in 'body'\", \"field\": \"phone\" }\n * { \"detail\": { \"detail\": \"Cidade não encontrada…\", \"field\": \"city\" },\n * \"code\": \"VALIDATION_ERROR\", \"details\": { \"field\": \"city\" } }\n * ```\n *\n * Those are indexed too, keyed by the field the backend named and valued with the\n * same sentence that becomes `detail`. Precedence is the list first, then\n * `detail.field`, `field`, `details.field` — see {@link collectFields}.\n *\n * A flattened `detail` from the list is developer-facing: it carries the\n * backend's field paths and the validator's own wording. `describeApiError` knows\n * not to show it to a person when `fields` is set — which now also covers a\n * business error that named a field, whose `detail` was a finished sentence. That\n * sentence is not lost: it is on `fields`, attached to the input that failed.\n *\n * @param status - HTTP status code.\n * @param body - The parsed error body (object, string, or null).\n * @param headers - The response headers (for the `X-Request-ID` fallback).\n * @param sentRequestId - The id the client sent on the request, if any.\n * @returns A fully-populated `ApiError`.\n *\n * @tempest-limits param-count — the arguments are the response as it arrives\n * (`status`, `body`, `headers`) plus the id the request was sent with, and they are\n * passed at exactly three places, all of them a client's response path\n * (`createApiClient`, `uploadWithProgress`, `createResumableUpload`). Wrapping them\n * in an options object would name each argument twice at every call site to say\n * nothing new.\n */\nexport function buildApiError(\n status: number,\n body: unknown,\n headers?: Headers | { get(name: string): string | null },\n sentRequestId?: string,\n): ApiError {\n const obj =\n typeof body === \"object\" && body !== null ? (body as Record<string, unknown>) : null;\n const message = trimFieldSuffix(\n normalizeDetail(obj?.detail) ?? normalizeDetail(obj?.message),\n namedField(obj),\n );\n const detail = message ?? syntheticDetail(status);\n const code = typeof obj?.code === \"string\" ? obj.code : undefined;\n const details =\n typeof obj?.details === \"object\" && obj.details !== null\n ? (obj.details as Record<string, unknown>)\n : null;\n const requestId =\n (typeof details?.request_id === \"string\" ? details.request_id : undefined) ??\n headers?.get(\"X-Request-ID\") ??\n sentRequestId ??\n undefined;\n\n return {\n status,\n detail,\n code,\n requestId: requestId ?? undefined,\n retryAfter: parseRetryAfter(headers?.get(\"Retry-After\")),\n fields: collectFields(obj, message),\n body,\n };\n}\n\n/**\n * Parse a `Retry-After` header into seconds. Accepts a delta-seconds integer\n * (`\"120\"`) or an HTTP-date (`\"Wed, 21 Oct 2015 07:28:00 GMT\"`).\n *\n * @param value - The raw header value, or null.\n * @returns The delay in seconds (>= 0), or undefined when absent/unparseable.\n */\nexport function parseRetryAfter(value: string | null | undefined): number | undefined {\n if (!value) return undefined;\n const trimmed = value.trim();\n if (/^\\d+$/.test(trimmed)) return Number(trimmed);\n const when = Date.parse(trimmed);\n if (Number.isNaN(when)) return undefined;\n return Math.max(0, Math.round((when - Date.now()) / 1000));\n}\n"],"mappings":"AAkBA,IAAa,EAAb,cAAqC,KAA0B,CAC3D,OACA,OACA,KACA,UACA,OACA,KAEA,YAAY,EAAgB,CACxB,MAAM,EAAK,MAAM,EACjB,KAAK,KAAO,kBACZ,KAAK,OAAS,EAAK,OACnB,KAAK,OAAS,EAAK,OACnB,KAAK,KAAO,EAAK,KACjB,KAAK,UAAY,EAAK,UACtB,KAAK,OAAS,EAAK,OACnB,KAAK,KAAO,EAAK,IACrB,CACJ,EA2Ba,EAAb,cAA4C,KAAM,CAC9C,aAAc,CACV,MAAM,8CAA8C,EACpD,KAAK,KAAO,wBAChB,CACJ,EASA,SAAgB,EAAW,EAAmC,CAC1D,OACI,OAAO,GAAU,YACjB,GACA,OAAQ,EAAmB,QAAW,UACtC,OAAQ,EAAmB,QAAW,QAE9C,CAOA,IAAM,EAAiC,IAAI,IAAI,CAAC,OAAQ,QAAS,OAAQ,SAAU,QAAQ,CAAC,EAS5F,SAAS,EAAU,EAAkC,CACjD,GAAI,CAAC,MAAM,QAAQ,CAAG,EAAG,OACzB,IAAM,EAAQ,EACT,OACI,GAAkC,OAAO,GAAS,UAAY,OAAO,GAAS,QACnF,CAAC,CACA,QAAQ,EAAM,IAAU,EAAE,IAAU,GAAK,EAAU,IAAI,OAAO,CA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,GAAK,EAAgB,GAAK,OAAO,EAC5D,EAAW,CAAG,CAClB,EACM,EAAS,GAAW,EAAgB,CAAM,EAC1C,EAAO,OAAO,GAAK,MAAS,SAAW,EAAI,KAAO,IAAA,GAClD,EACF,OAAO,GAAK,SAAY,UAAY,EAAI,UAAY,KAC7C,EAAI,QACL,KAOV,MAAO,CACH,SACA,SACA,OACA,WATC,OAAO,GAAS,YAAe,SAAW,EAAQ,WAAa,IAAA,KAChE,GAAS,IAAI,cAAc,GAC3B,GACA,IAAA,IAMwB,IAAA,GACxB,WAAY,EAAgB,GAAS,IAAI,aAAa,CAAC,EACvD,OAAQ,EAAc,EAAK,CAAO,EAClC,MACJ,CACJ,CASA,SAAgB,EAAgB,EAAsD,CAClF,GAAI,CAAC,EAAO,OACZ,IAAM,EAAU,EAAM,KAAK,EAC3B,GAAI,QAAQ,KAAK,CAAO,EAAG,OAAO,OAAO,CAAO,EAChD,IAAM,EAAO,KAAK,MAAM,CAAO,EAC3B,WAAO,MAAM,CAAI,EACrB,OAAO,KAAK,IAAI,EAAG,KAAK,OAAO,EAAO,KAAK,IAAI,GAAK,GAAI,CAAC,CAC7D"}
@@ -9,104 +9,108 @@ var e = class extends Error {
9
9
  constructor(e) {
10
10
  super(e.detail), this.name = "TempestApiError", this.status = e.status, this.detail = e.detail, this.code = e.code, this.requestId = e.requestId, this.fields = e.fields, this.body = e.body;
11
11
  }
12
+ }, t = class extends Error {
13
+ constructor() {
14
+ super("A sessão mudou antes de a operação terminar."), this.name = "SessionSupersededError";
15
+ }
12
16
  };
13
- function t(e) {
17
+ function n(e) {
14
18
  return typeof e == "object" && !!e && typeof e.status == "number" && typeof e.detail == "string";
15
19
  }
16
- var n = /* @__PURE__ */ new Set([
20
+ var r = /* @__PURE__ */ new Set([
17
21
  "body",
18
22
  "query",
19
23
  "path",
20
24
  "header",
21
25
  "cookie"
22
26
  ]);
23
- function r(e) {
27
+ function i(e) {
24
28
  if (!Array.isArray(e)) return;
25
- let t = e.filter((e) => typeof e == "string" || typeof e == "number").filter((e, t) => !(t === 0 && n.has(String(e))));
29
+ let t = e.filter((e) => typeof e == "string" || typeof e == "number").filter((e, t) => !(t === 0 && r.has(String(e))));
26
30
  return t.length > 0 ? t.join(".") : void 0;
27
31
  }
28
- var i = 4;
29
- function a(e) {
32
+ var a = 4;
33
+ function o(e) {
30
34
  if (!Array.isArray(e)) return;
31
35
  let t = {};
32
36
  for (let n of e) {
33
37
  if (typeof n != "object" || !n) continue;
34
- let e = n, i = r(e.loc);
35
- if (i === void 0 || i in t) continue;
36
- let a = u(e.msg) ?? u(e.message);
37
- a !== void 0 && (t[i] = a);
38
+ let e = n, r = i(e.loc);
39
+ if (r === void 0 || r in t) continue;
40
+ let a = d(e.msg) ?? d(e.message);
41
+ a !== void 0 && (t[r] = a);
38
42
  }
39
43
  return Object.keys(t).length > 0 ? t : void 0;
40
44
  }
41
- function o(e) {
45
+ function s(e) {
42
46
  return typeof e == "object" && e && !Array.isArray(e) ? e : void 0;
43
47
  }
44
- function s(e) {
48
+ function c(e) {
45
49
  if (e === null) return;
46
50
  let t = [
47
- o(e.detail)?.field,
51
+ s(e.detail)?.field,
48
52
  e.field,
49
- o(e.details)?.field
53
+ s(e.details)?.field
50
54
  ];
51
55
  for (let e of t) if (typeof e == "string" && e !== "") return e;
52
56
  }
53
- function c(e, t) {
57
+ function l(e, t) {
54
58
  if (e === void 0 || t === void 0) return e;
55
59
  let n = t.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"), r = e.replace(RegExp(`\\s+for field '${n}'(?:\\s+in\\s+'[^']*')?\\.?\\s*$`), "").trim();
56
60
  return r === "" ? e : r;
57
61
  }
58
- function l(e, t) {
59
- let n = a(e?.detail);
62
+ function u(e, t) {
63
+ let n = o(e?.detail);
60
64
  if (n !== void 0) return n;
61
- let r = s(e);
65
+ let r = c(e);
62
66
  if (r !== void 0 && t !== void 0) return { [r]: t };
63
67
  }
64
- function u(e, t = 0) {
68
+ function d(e, t = 0) {
65
69
  if (e != null) {
66
70
  if (typeof e == "string") return e === "" ? void 0 : e;
67
71
  if (typeof e == "number" || typeof e == "boolean") return String(e);
68
- if (!(t >= i)) {
72
+ if (!(t >= a)) {
69
73
  if (Array.isArray(e)) {
70
74
  let n = e.map((e) => {
71
- let n = u(e, t + 1);
75
+ let n = d(e, t + 1);
72
76
  if (n === void 0) return;
73
- let i = typeof e == "object" && e ? r(e.loc) : void 0;
74
- return i === void 0 ? n : `${i}: ${n}`;
77
+ let r = typeof e == "object" && e ? i(e.loc) : void 0;
78
+ return r === void 0 ? n : `${r}: ${n}`;
75
79
  }).filter((e) => e !== void 0);
76
80
  return n.length > 0 ? n.join("; ") : void 0;
77
81
  }
78
82
  if (typeof e == "object") {
79
83
  let n = e;
80
- return u(n.msg, t + 1) ?? u(n.message, t + 1) ?? u(n.detail, t + 1);
84
+ return d(n.msg, t + 1) ?? d(n.message, t + 1) ?? d(n.detail, t + 1);
81
85
  }
82
86
  }
83
87
  }
84
88
  }
85
- var d = /* @__PURE__ */ new Set([
89
+ var f = /* @__PURE__ */ new Set([
86
90
  0,
87
91
  408,
88
92
  425,
89
93
  429
90
94
  ]);
91
- function f(e) {
92
- return d.has(e) || e >= 500;
93
- }
94
95
  function p(e) {
96
+ return f.has(e) || e >= 500;
97
+ }
98
+ function m(e) {
95
99
  return `Erro ${e}`;
96
100
  }
97
- function m(e, t, n, r) {
98
- let i = typeof t == "object" && t ? t : null, a = c(u(i?.detail) ?? u(i?.message), s(i)), o = a ?? p(e), d = typeof i?.code == "string" ? i.code : void 0, f = typeof i?.details == "object" && i.details !== null ? i.details : null;
101
+ function h(e, t, n, r) {
102
+ let i = typeof t == "object" && t ? t : null, a = l(d(i?.detail) ?? d(i?.message), c(i)), o = a ?? m(e), s = typeof i?.code == "string" ? i.code : void 0, f = typeof i?.details == "object" && i.details !== null ? i.details : null;
99
103
  return {
100
104
  status: e,
101
105
  detail: o,
102
- code: d,
106
+ code: s,
103
107
  requestId: (typeof f?.request_id == "string" ? f.request_id : void 0) ?? n?.get("X-Request-ID") ?? r ?? void 0 ?? void 0,
104
- retryAfter: h(n?.get("Retry-After")),
105
- fields: l(i, a),
108
+ retryAfter: g(n?.get("Retry-After")),
109
+ fields: u(i, a),
106
110
  body: t
107
111
  };
108
112
  }
109
- function h(e) {
113
+ function g(e) {
110
114
  if (!e) return;
111
115
  let t = e.trim();
112
116
  if (/^\d+$/.test(t)) return Number(t);
@@ -114,6 +118,6 @@ function h(e) {
114
118
  if (!Number.isNaN(n)) return Math.max(0, Math.round((n - Date.now()) / 1e3));
115
119
  }
116
120
  //#endregion
117
- export { e as TempestApiError, m as buildApiError, t as isApiError, f as isRetriableStatus, h as parseRetryAfter, p as syntheticDetail };
121
+ export { t as SessionSupersededError, e as TempestApiError, h as buildApiError, n as isApiError, p as isRetriableStatus, g as parseRetryAfter, m as syntheticDetail };
118
122
 
119
123
  //# sourceMappingURL=errors.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"errors.js","names":[],"sources":["../../src/http/errors.ts"],"sourcesContent":["import type { ApiError } from \"./types\";\n\n/**\n * Error thrown by {@link createApiClient} / {@link uploadWithProgress} on a\n * non-2xx response. Mirrors the Tempest FastAPI SDK error envelope\n * (`{ detail, code, details.request_id }`) so callers get a typed `code` and a\n * `requestId` for log correlation, while still being a real `Error` (stack\n * trace, `instanceof Error`).\n *\n * @example\n * try {\n * await api.post(\"/users\", { body });\n * } catch (err) {\n * if (isApiError(err) && err.code === \"EMAIL_TAKEN\") {\n * showFieldError(\"email\", err.detail);\n * }\n * }\n */\nexport class TempestApiError extends Error implements ApiError {\n readonly status: number;\n readonly detail: string;\n readonly code?: string;\n readonly requestId?: string;\n readonly fields?: Record<string, string>;\n readonly body?: unknown;\n\n constructor(init: ApiError) {\n super(init.detail);\n this.name = \"TempestApiError\";\n this.status = init.status;\n this.detail = init.detail;\n this.code = init.code;\n this.requestId = init.requestId;\n this.fields = init.fields;\n this.body = init.body;\n }\n}\n\n/**\n * Type guard for the {@link ApiError} shape. Matches both {@link TempestApiError}\n * instances and plain objects carrying `status` + `detail`.\n *\n * @param error - The unknown value (typically a caught error).\n * @returns Whether `error` conforms to the `ApiError` contract.\n */\nexport function isApiError(error: unknown): error is ApiError {\n return (\n typeof error === \"object\" &&\n error !== null &&\n typeof (error as ApiError).status === \"number\" &&\n typeof (error as ApiError).detail === \"string\"\n );\n}\n\n/**\n * Location prefixes FastAPI puts at the head of a validation error's `loc`,\n * naming the part of the request rather than the field. Dropped from the\n * rendered path, so `[\"body\", \"email\"]` reads as `email`.\n */\nconst LOC_ROOTS: ReadonlySet<string> = new Set([\"body\", \"query\", \"path\", \"header\", \"cookie\"]);\n\n/**\n * Render a FastAPI validation error's `loc` tuple as a dotted field path.\n *\n * @param loc - The raw `loc` value from one validation error entry.\n * @returns The dotted path (`\"items.0.price\"`), or undefined when `loc` carries\n * nothing addressable.\n */\nfunction formatLoc(loc: unknown): string | undefined {\n if (!Array.isArray(loc)) return undefined;\n const parts = loc\n .filter(\n (part): part is string | number => typeof part === \"string\" || typeof part === \"number\",\n )\n .filter((part, index) => !(index === 0 && LOC_ROOTS.has(String(part))));\n return parts.length > 0 ? parts.join(\".\") : undefined;\n}\n\n/**\n * How deep {@link normalizeDetail} follows a nested `detail` before giving up.\n *\n * A real envelope needs two or three levels: the list, an entry, the entry's\n * own `detail`. The cap exists because the body is untrusted input arriving on\n * the error path — a response nesting `{\"detail\":{\"detail\":…}}` twenty thousand\n * deep (a 220 KB body) overflowed the stack, and a `RangeError` thrown while\n * *building* the error is worse than the error: the caller's `catch` stops\n * receiving a `TempestApiError`, so `isApiError` is false, `describeApiError`\n * has nothing to read and the `401` handling never runs.\n */\nconst MAX_DETAIL_DEPTH = 4;\n\n/**\n * Pull field-level messages out of a validation `detail` **list**.\n *\n * FastAPI's `422` body is `detail: [{ loc, msg, type }]`, which is exactly what\n * a form needs and exactly what the flattened `detail` string destroys. Only the\n * top level is read: a validation error names one field per entry, and following\n * nesting here would invent paths the backend never sent.\n *\n * This is one of two ways a body names a field — see {@link collectFields}, which\n * is the entry point and falls back to the singular keys when the list names\n * nothing addressable.\n *\n * @param raw - The `detail` value from the error body.\n * @returns Field path to message, or undefined when the body is not a\n * validation list (or carries no entry naming a field).\n */\nfunction collectListFields(raw: unknown): Record<string, string> | undefined {\n if (!Array.isArray(raw)) return undefined;\n\n const fields: Record<string, string> = {};\n for (const entry of raw) {\n if (typeof entry !== \"object\" || entry === null) continue;\n const record = entry as Record<string, unknown>;\n const field = formatLoc(record.loc);\n if (field === undefined || field in fields) continue;\n const message = normalizeDetail(record.msg) ?? normalizeDetail(record.message);\n if (message === undefined) continue;\n fields[field] = message;\n }\n\n return Object.keys(fields).length > 0 ? fields : undefined;\n}\n\n/**\n * Narrow a value to a plain object — a record, and not an array.\n *\n * Arrays are excluded because `typeof [] === \"object\"` while a list means\n * something else entirely here: FastAPI's `detail` list is read by\n * {@link collectListFields}, and reading `.field` off it would only ever be\n * undefined.\n *\n * @param value - The candidate value from the error body.\n * @returns The value as a record, or undefined when it is not a plain object.\n */\nfunction plainRecord(value: unknown): Record<string, unknown> | undefined {\n return typeof value === \"object\" && value !== null && !Array.isArray(value)\n ? (value as Record<string, unknown>)\n : undefined;\n}\n\n/**\n * Read the field a **singular** error envelope names.\n *\n * A backend built on `tempest-fastapi-sdk` never answers with FastAPI's `detail`\n * list once it owns the handler: it names the guilty field in a key beside the\n * message. Three shapes are seen in the wild, and they are read inner-out:\n *\n * 1. `detail.field` — the field sits in the same object as the message it\n * describes (`{ detail: { detail: \"Cidade não encontrada…\", field: \"city\" } }`),\n * so it is the least ambiguous claim about which message belongs to which input.\n * 2. `field` at the top level — a flattened `RequestValidationError`\n * (`{ detail: \"Value error, … for field 'phone' in 'body'\", field: \"phone\" }`)\n * makes the same claim one level out.\n * 3. `details.field` — `details` is the envelope's free-form context bag, not a\n * validation channel, and its `field` may be about something no input on screen\n * carries (an unknown sort column, say). It answers last for exactly that reason.\n *\n * `location` (`\"body -> phone\"`) is deliberately not parsed: it renders the same\n * path `field` already names, no observed envelope sends it without `field`, and\n * splitting an arrow-separated string would invent a path the backend never sent.\n *\n * @param body - The parsed error body, or null when it was not an object.\n * @returns The field name, or undefined when none of the three keys carried a\n * non-empty string — anything else is not usable as a key on `fields`.\n */\nfunction namedField(body: Record<string, unknown> | null): string | undefined {\n if (body === null) return undefined;\n const candidates: readonly unknown[] = [\n plainRecord(body.detail)?.field,\n body.field,\n plainRecord(body.details)?.field,\n ];\n for (const candidate of candidates) {\n if (typeof candidate === \"string\" && candidate !== \"\") return candidate;\n }\n return undefined;\n}\n\n/**\n * Drop the machine-readable tail a `tempest-fastapi-sdk` backend appends.\n *\n * That backend flattens a field error into\n * `\"CPF ou CNPJ inválido for field 'cpf_cnpj' in 'body'\"` — a finished sentence\n * in the app's language with an English clause glued to the end. The clause\n * carries nothing new: the same two values arrive as `field` and `location` on\n * the envelope, which is where `ApiError.fields` reads them from. Left in, it\n * reaches the user, and every consuming app grew its own regex to shave it off.\n *\n * The trim only fires when the field the tail names is the field the envelope\n * resolved to. That is what keeps it from deleting text it cannot account for:\n * a tail naming some other field is either a different envelope shape or a\n * sentence that genuinely reads that way, and both are left alone.\n *\n * @param message - The readable message, or undefined when the body had none.\n * @param field - The field name {@link namedField} resolved, if any.\n * @returns The message without the tail, or the message unchanged.\n */\nfunction trimFieldSuffix(\n message: string | undefined,\n field: string | undefined,\n): string | undefined {\n if (message === undefined || field === undefined) return message;\n const escaped = field.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n const trimmed = message\n .replace(new RegExp(`\\\\s+for field '${escaped}'(?:\\\\s+in\\\\s+'[^']*')?\\\\.?\\\\s*$`), \"\")\n .trim();\n return trimmed === \"\" ? message : trimmed;\n}\n\n/**\n * Index the body's field-level messages, whichever envelope carried them.\n *\n * The single entry point behind `ApiError.fields`, and it applies two rules the\n * tests pin:\n *\n * - FastAPI's `detail` list wins whenever it names at least one addressable\n * field. A plain FastAPI app still answers a schema-level `422` with that list\n * even on a `tempest-fastapi-sdk` backend, so it stays authoritative.\n * - A named field with no readable message produces nothing. The only string\n * left at that point is the synthetic `Erro <status>`, and `{ phone: \"Erro 422\" }`\n * on an input is noise rather than an error message.\n *\n * @param body - The parsed error body, or null when it was not an object.\n * @param message - The readable message the same body produced, before the\n * synthetic fallback — the string that also becomes `ApiError.detail`.\n * @returns Field name to message, or undefined when nothing named a field.\n */\nfunction collectFields(\n body: Record<string, unknown> | null,\n message: string | undefined,\n): Record<string, string> | undefined {\n const listed = collectListFields(body?.detail);\n if (listed !== undefined) return listed;\n const field = namedField(body);\n if (field === undefined || message === undefined) return undefined;\n return { [field]: message };\n}\n\n/**\n * Collapse a backend `detail` of any shape into a single readable line.\n *\n * FastAPI answers a `422` with `detail` as a **list** of\n * `{ loc, msg, type }` entries, not a string. Passing that through `String()`\n * yields `\"[object Object]\"` — an error message that tells the user nothing and\n * hides which field failed. Each entry becomes `\"<field>: <msg>\"` and the\n * entries are joined with `\"; \"`; a nested object is read through its\n * `msg`/`message`/`detail` string.\n *\n * @param raw - The `detail` (or `message`) value from the error body.\n * @param depth - Current nesting level. Past {@link MAX_DETAIL_DEPTH} the value\n * is treated as unreadable instead of followed further.\n * @returns The rendered message, or undefined when nothing readable is there —\n * letting the caller fall back to the synthetic `Erro <status>`.\n */\nfunction normalizeDetail(raw: unknown, depth: number = 0): string | undefined {\n if (raw === null || raw === undefined) return undefined;\n if (typeof raw === \"string\") return raw === \"\" ? undefined : raw;\n if (typeof raw === \"number\" || typeof raw === \"boolean\") return String(raw);\n if (depth >= MAX_DETAIL_DEPTH) return undefined;\n\n if (Array.isArray(raw)) {\n const lines = raw\n .map((entry) => {\n const message = normalizeDetail(entry, depth + 1);\n if (message === undefined) return undefined;\n const field =\n typeof entry === \"object\" && entry !== null\n ? formatLoc((entry as Record<string, unknown>).loc)\n : undefined;\n return field === undefined ? message : `${field}: ${message}`;\n })\n .filter((line): line is string => line !== undefined);\n return lines.length > 0 ? lines.join(\"; \") : undefined;\n }\n\n if (typeof raw === \"object\") {\n const entry = raw as Record<string, unknown>;\n return (\n normalizeDetail(entry.msg, depth + 1) ??\n normalizeDetail(entry.message, depth + 1) ??\n normalizeDetail(entry.detail, depth + 1)\n );\n }\n\n return undefined;\n}\n\n/**\n * Statuses worth a second attempt, as a set for the sub-500 cases.\n *\n * A network failure (status `0`), a request timeout, a too-early replay, and a\n * rate limit — which usually carries the `Retry-After` the backoff honours.\n * Everything else below 500 is the server refusing on purpose.\n */\nconst RETRIABLE_STATUSES: ReadonlySet<number> = new Set([0, 408, 425, 429]);\n\n/**\n * Whether an HTTP status describes a condition a replay can plausibly fix.\n *\n * The single owner of that decision. It used to be spelled out in three places —\n * the client's own policy, the react-query default and the bare `retry()` helper\n * — and they had already drifted: the query default was missing `425`, so the\n * same `425 Too Early` was replayed through `createApiClient({ retry: true })`\n * and not replayed through `useQuery`. Same app, same error, two behaviours, and\n * no test caught it because each file asserted against its own copy.\n *\n * Deliberately about the status and nothing else. Whether a *non*-API error is\n * worth replaying, and whether the request's method may be replayed at all, are\n * the caller's calls: {@link createApiClient} refuses a non-idempotent method,\n * while a bare `retry()` has no method to inspect.\n *\n * @example\n * await api.get(\"/report\", {\n * retry: { shouldRetry: (error) => isApiError(error) && isRetriableStatus(error.status) },\n * });\n *\n * @param status - The HTTP status, where `0` means the request never landed.\n * @returns Whether a retry is worth attempting.\n */\nexport function isRetriableStatus(status: number): boolean {\n return RETRIABLE_STATUSES.has(status) || status >= 500;\n}\n\n/**\n * Detail text synthesised when a response body carries none.\n *\n * Exported because {@link describeApiError} has to recognise it: a detail the\n * server never sent says strictly less than the caller's own fallback, so the\n * funnel drops it. Comparing against a copied literal would silently stop\n * matching the day this sentence is reworded — no type error, no failing test.\n *\n * @param status - The HTTP status of the error.\n * @returns The synthetic detail for that status.\n */\nexport function syntheticDetail(status: number): string {\n return `Erro ${status}`;\n}\n\n/**\n * Parse an error body + response into the Tempest {@link ApiError} envelope.\n *\n * Reads `detail`/`message`, the programmatic `code`, and the correlation id\n * from `details.request_id` (falling back to the `X-Request-ID` header, then\n * the id the client sent).\n *\n * A `422` from FastAPI carries `detail` as a list of `{ loc, msg, type }`\n * entries, so it is flattened to `\"<field>: <msg>; <field>: <msg>\"` instead of\n * being stringified into `\"[object Object]\"`, and the same entries are indexed\n * on `fields` (`{ email: \"Field required\" }`) for a form to consume without\n * parsing that line back apart. The untouched body stays on `body`.\n *\n * A backend that owns its handlers — every `tempest-fastapi-sdk` app — sends no\n * such list, and names the field in a key instead:\n *\n * ```json\n * { \"detail\": \"Value error, … for field 'phone' in 'body'\", \"field\": \"phone\" }\n * { \"detail\": { \"detail\": \"Cidade não encontrada…\", \"field\": \"city\" },\n * \"code\": \"VALIDATION_ERROR\", \"details\": { \"field\": \"city\" } }\n * ```\n *\n * Those are indexed too, keyed by the field the backend named and valued with the\n * same sentence that becomes `detail`. Precedence is the list first, then\n * `detail.field`, `field`, `details.field` — see {@link collectFields}.\n *\n * A flattened `detail` from the list is developer-facing: it carries the\n * backend's field paths and the validator's own wording. `describeApiError` knows\n * not to show it to a person when `fields` is set — which now also covers a\n * business error that named a field, whose `detail` was a finished sentence. That\n * sentence is not lost: it is on `fields`, attached to the input that failed.\n *\n * @param status - HTTP status code.\n * @param body - The parsed error body (object, string, or null).\n * @param headers - The response headers (for the `X-Request-ID` fallback).\n * @param sentRequestId - The id the client sent on the request, if any.\n * @returns A fully-populated `ApiError`.\n *\n * @tempest-limits param-count — the arguments are the response as it arrives\n * (`status`, `body`, `headers`) plus the id the request was sent with, and they are\n * passed at exactly three places, all of them a client's response path\n * (`createApiClient`, `uploadWithProgress`, `createResumableUpload`). Wrapping them\n * in an options object would name each argument twice at every call site to say\n * nothing new.\n */\nexport function buildApiError(\n status: number,\n body: unknown,\n headers?: Headers | { get(name: string): string | null },\n sentRequestId?: string,\n): ApiError {\n const obj =\n typeof body === \"object\" && body !== null ? (body as Record<string, unknown>) : null;\n const message = trimFieldSuffix(\n normalizeDetail(obj?.detail) ?? normalizeDetail(obj?.message),\n namedField(obj),\n );\n const detail = message ?? syntheticDetail(status);\n const code = typeof obj?.code === \"string\" ? obj.code : undefined;\n const details =\n typeof obj?.details === \"object\" && obj.details !== null\n ? (obj.details as Record<string, unknown>)\n : null;\n const requestId =\n (typeof details?.request_id === \"string\" ? details.request_id : undefined) ??\n headers?.get(\"X-Request-ID\") ??\n sentRequestId ??\n undefined;\n\n return {\n status,\n detail,\n code,\n requestId: requestId ?? undefined,\n retryAfter: parseRetryAfter(headers?.get(\"Retry-After\")),\n fields: collectFields(obj, message),\n body,\n };\n}\n\n/**\n * Parse a `Retry-After` header into seconds. Accepts a delta-seconds integer\n * (`\"120\"`) or an HTTP-date (`\"Wed, 21 Oct 2015 07:28:00 GMT\"`).\n *\n * @param value - The raw header value, or null.\n * @returns The delay in seconds (>= 0), or undefined when absent/unparseable.\n */\nexport function parseRetryAfter(value: string | null | undefined): number | undefined {\n if (!value) return undefined;\n const trimmed = value.trim();\n if (/^\\d+$/.test(trimmed)) return Number(trimmed);\n const when = Date.parse(trimmed);\n if (Number.isNaN(when)) return undefined;\n return Math.max(0, Math.round((when - Date.now()) / 1000));\n}\n"],"mappings":";AAkBA,IAAa,IAAb,cAAqC,MAA0B;CAC3D;CACA;CACA;CACA;CACA;CACA;CAEA,YAAY,GAAgB;EAQxB,AAPA,MAAM,EAAK,MAAM,GACjB,KAAK,OAAO,mBACZ,KAAK,SAAS,EAAK,QACnB,KAAK,SAAS,EAAK,QACnB,KAAK,OAAO,EAAK,MACjB,KAAK,YAAY,EAAK,WACtB,KAAK,SAAS,EAAK,QACnB,KAAK,OAAO,EAAK;CACrB;AACJ;AASA,SAAgB,EAAW,GAAmC;CAC1D,OACI,OAAO,KAAU,cACjB,KACA,OAAQ,EAAmB,UAAW,YACtC,OAAQ,EAAmB,UAAW;AAE9C;AAOA,IAAM,oBAAiC,IAAI,IAAI;CAAC;CAAQ;CAAS;CAAQ;CAAU;AAAQ,CAAC;AAS5F,SAAS,EAAU,GAAk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U;AACvD;AAaA,SAAgB,EAAgB,GAAwB;CACpD,OAAO,QAAQ;AACnB;AA+CA,SAAgB,EACZ,GACA,GACA,GACA,GACQ;CACR,IAAM,IACF,OAAO,KAAS,YAAY,IAAiB,IAAmC,MAC9E,IAAU,EACZ,EAAgB,GAAK,MAAM,KAAK,EAAgB,GAAK,OAAO,GAC5D,EAAW,CAAG,CAClB,GACM,IAAS,KAAW,EAAgB,CAAM,GAC1C,IAAO,OAAO,GAAK,QAAS,WAAW,EAAI,OAAO,KAAA,GAClD,IACF,OAAO,GAAK,WAAY,YAAY,EAAI,YAAY,OAC7C,EAAI,UACL;CAOV,OAAO;EACH;EACA;EACA;EACA,YATC,OAAO,GAAS,cAAe,WAAW,EAAQ,aAAa,KAAA,MAChE,GAAS,IAAI,cAAc,KAC3B,KACA,KAAA,KAMwB,KAAA;EACxB,YAAY,EAAgB,GAAS,IAAI,aAAa,CAAC;EACvD,QAAQ,EAAc,GAAK,CAAO;EAClC;CACJ;AACJ;AASA,SAAgB,EAAgB,GAAsD;CAClF,IAAI,CAAC,GAAO;CACZ,IAAM,IAAU,EAAM,KAAK;CAC3B,IAAI,QAAQ,KAAK,CAAO,GAAG,OAAO,OAAO,CAAO;CAChD,IAAM,IAAO,KAAK,MAAM,CAAO;CAC3B,YAAO,MAAM,CAAI,GACrB,OAAO,KAAK,IAAI,GAAG,KAAK,OAAO,IAAO,KAAK,IAAI,KAAK,GAAI,CAAC;AAC7D"}
1
+ {"version":3,"file":"errors.js","names":[],"sources":["../../src/http/errors.ts"],"sourcesContent":["import type { ApiError } from \"./types\";\n\n/**\n * Error thrown by {@link createApiClient} / {@link uploadWithProgress} on a\n * non-2xx response. Mirrors the Tempest FastAPI SDK error envelope\n * (`{ detail, code, details.request_id }`) so callers get a typed `code` and a\n * `requestId` for log correlation, while still being a real `Error` (stack\n * trace, `instanceof Error`).\n *\n * @example\n * try {\n * await api.post(\"/users\", { body });\n * } catch (err) {\n * if (isApiError(err) && err.code === \"EMAIL_TAKEN\") {\n * showFieldError(\"email\", err.detail);\n * }\n * }\n */\nexport class TempestApiError extends Error implements ApiError {\n readonly status: number;\n readonly detail: string;\n readonly code?: string;\n readonly requestId?: string;\n readonly fields?: Record<string, string>;\n readonly body?: unknown;\n\n constructor(init: ApiError) {\n super(init.detail);\n this.name = \"TempestApiError\";\n this.status = init.status;\n this.detail = init.detail;\n this.code = init.code;\n this.requestId = init.requestId;\n this.fields = init.fields;\n this.body = init.body;\n }\n}\n\n/**\n * Thrown when the session that started an operation is no longer the current\n * one by the time it settles: a `refresh` hook (rethrown by\n * {@link createApiClient}), or a `createTempestAuth` `login()` whose session\n * was replaced while it waited on the previous session's teardown.\n *\n * A refresh is a network round trip, and the session can end or change hands\n * during it: the user signs out, or signs out and another account signs in. The\n * tokens that refresh brings back belong to the session that ended, so they are\n * discarded instead of installed, and the request that was waiting on them is\n * not replayed — replaying it would send it as whoever is signed in now.\n *\n * This is deliberately not an unauthorized outcome. The client does **not** call\n * `onUnauthorized` for it: that callback ends the session, and the current\n * session — possibly a different account that just signed in — did nothing\n * wrong. Treat it like an aborted request: drop the result, show nothing.\n *\n * @example\n * try {\n * await api.get(\"/api/orders\");\n * } catch (err) {\n * if (err instanceof SessionSupersededError) return;\n * throw err;\n * }\n */\nexport class SessionSupersededError extends Error {\n constructor() {\n super(\"A sessão mudou antes de a operação terminar.\");\n this.name = \"SessionSupersededError\";\n }\n}\n\n/**\n * Type guard for the {@link ApiError} shape. Matches both {@link TempestApiError}\n * instances and plain objects carrying `status` + `detail`.\n *\n * @param error - The unknown value (typically a caught error).\n * @returns Whether `error` conforms to the `ApiError` contract.\n */\nexport function isApiError(error: unknown): error is ApiError {\n return (\n typeof error === \"object\" &&\n error !== null &&\n typeof (error as ApiError).status === \"number\" &&\n typeof (error as ApiError).detail === \"string\"\n );\n}\n\n/**\n * Location prefixes FastAPI puts at the head of a validation error's `loc`,\n * naming the part of the request rather than the field. Dropped from the\n * rendered path, so `[\"body\", \"email\"]` reads as `email`.\n */\nconst LOC_ROOTS: ReadonlySet<string> = new Set([\"body\", \"query\", \"path\", \"header\", \"cookie\"]);\n\n/**\n * Render a FastAPI validation error's `loc` tuple as a dotted field path.\n *\n * @param loc - The raw `loc` value from one validation error entry.\n * @returns The dotted path (`\"items.0.price\"`), or undefined when `loc` carries\n * nothing addressable.\n */\nfunction formatLoc(loc: unknown): string | undefined {\n if (!Array.isArray(loc)) return undefined;\n const parts = loc\n .filter(\n (part): part is string | number => typeof part === \"string\" || typeof part === \"number\",\n )\n .filter((part, index) => !(index === 0 && LOC_ROOTS.has(String(part))));\n return parts.length > 0 ? parts.join(\".\") : undefined;\n}\n\n/**\n * How deep {@link normalizeDetail} follows a nested `detail` before giving up.\n *\n * A real envelope needs two or three levels: the list, an entry, the entry's\n * own `detail`. The cap exists because the body is untrusted input arriving on\n * the error path — a response nesting `{\"detail\":{\"detail\":…}}` twenty thousand\n * deep (a 220 KB body) overflowed the stack, and a `RangeError` thrown while\n * *building* the error is worse than the error: the caller's `catch` stops\n * receiving a `TempestApiError`, so `isApiError` is false, `describeApiError`\n * has nothing to read and the `401` handling never runs.\n */\nconst MAX_DETAIL_DEPTH = 4;\n\n/**\n * Pull field-level messages out of a validation `detail` **list**.\n *\n * FastAPI's `422` body is `detail: [{ loc, msg, type }]`, which is exactly what\n * a form needs and exactly what the flattened `detail` string destroys. Only the\n * top level is read: a validation error names one field per entry, and following\n * nesting here would invent paths the backend never sent.\n *\n * This is one of two ways a body names a field — see {@link collectFields}, which\n * is the entry point and falls back to the singular keys when the list names\n * nothing addressable.\n *\n * @param raw - The `detail` value from the error body.\n * @returns Field path to message, or undefined when the body is not a\n * validation list (or carries no entry naming a field).\n */\nfunction collectListFields(raw: unknown): Record<string, string> | undefined {\n if (!Array.isArray(raw)) return undefined;\n\n const fields: Record<string, string> = {};\n for (const entry of raw) {\n if (typeof entry !== \"object\" || entry === null) continue;\n const record = entry as Record<string, unknown>;\n const field = formatLoc(record.loc);\n if (field === undefined || field in fields) continue;\n const message = normalizeDetail(record.msg) ?? normalizeDetail(record.message);\n if (message === undefined) continue;\n fields[field] = message;\n }\n\n return Object.keys(fields).length > 0 ? fields : undefined;\n}\n\n/**\n * Narrow a value to a plain object — a record, and not an array.\n *\n * Arrays are excluded because `typeof [] === \"object\"` while a list means\n * something else entirely here: FastAPI's `detail` list is read by\n * {@link collectListFields}, and reading `.field` off it would only ever be\n * undefined.\n *\n * @param value - The candidate value from the error body.\n * @returns The value as a record, or undefined when it is not a plain object.\n */\nfunction plainRecord(value: unknown): Record<string, unknown> | undefined {\n return typeof value === \"object\" && value !== null && !Array.isArray(value)\n ? (value as Record<string, unknown>)\n : undefined;\n}\n\n/**\n * Read the field a **singular** error envelope names.\n *\n * A backend built on `tempest-fastapi-sdk` never answers with FastAPI's `detail`\n * list once it owns the handler: it names the guilty field in a key beside the\n * message. Three shapes are seen in the wild, and they are read inner-out:\n *\n * 1. `detail.field` — the field sits in the same object as the message it\n * describes (`{ detail: { detail: \"Cidade não encontrada…\", field: \"city\" } }`),\n * so it is the least ambiguous claim about which message belongs to which input.\n * 2. `field` at the top level — a flattened `RequestValidationError`\n * (`{ detail: \"Value error, … for field 'phone' in 'body'\", field: \"phone\" }`)\n * makes the same claim one level out.\n * 3. `details.field` — `details` is the envelope's free-form context bag, not a\n * validation channel, and its `field` may be about something no input on screen\n * carries (an unknown sort column, say). It answers last for exactly that reason.\n *\n * `location` (`\"body -> phone\"`) is deliberately not parsed: it renders the same\n * path `field` already names, no observed envelope sends it without `field`, and\n * splitting an arrow-separated string would invent a path the backend never sent.\n *\n * @param body - The parsed error body, or null when it was not an object.\n * @returns The field name, or undefined when none of the three keys carried a\n * non-empty string — anything else is not usable as a key on `fields`.\n */\nfunction namedField(body: Record<string, unknown> | null): string | undefined {\n if (body === null) return undefined;\n const candidates: readonly unknown[] = [\n plainRecord(body.detail)?.field,\n body.field,\n plainRecord(body.details)?.field,\n ];\n for (const candidate of candidates) {\n if (typeof candidate === \"string\" && candidate !== \"\") return candidate;\n }\n return undefined;\n}\n\n/**\n * Drop the machine-readable tail a `tempest-fastapi-sdk` backend appends.\n *\n * That backend flattens a field error into\n * `\"CPF ou CNPJ inválido for field 'cpf_cnpj' in 'body'\"` — a finished sentence\n * in the app's language with an English clause glued to the end. The clause\n * carries nothing new: the same two values arrive as `field` and `location` on\n * the envelope, which is where `ApiError.fields` reads them from. Left in, it\n * reaches the user, and every consuming app grew its own regex to shave it off.\n *\n * The trim only fires when the field the tail names is the field the envelope\n * resolved to. That is what keeps it from deleting text it cannot account for:\n * a tail naming some other field is either a different envelope shape or a\n * sentence that genuinely reads that way, and both are left alone.\n *\n * @param message - The readable message, or undefined when the body had none.\n * @param field - The field name {@link namedField} resolved, if any.\n * @returns The message without the tail, or the message unchanged.\n */\nfunction trimFieldSuffix(\n message: string | undefined,\n field: string | undefined,\n): string | undefined {\n if (message === undefined || field === undefined) return message;\n const escaped = field.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n const trimmed = message\n .replace(new RegExp(`\\\\s+for field '${escaped}'(?:\\\\s+in\\\\s+'[^']*')?\\\\.?\\\\s*$`), \"\")\n .trim();\n return trimmed === \"\" ? message : trimmed;\n}\n\n/**\n * Index the body's field-level messages, whichever envelope carried them.\n *\n * The single entry point behind `ApiError.fields`, and it applies two rules the\n * tests pin:\n *\n * - FastAPI's `detail` list wins whenever it names at least one addressable\n * field. A plain FastAPI app still answers a schema-level `422` with that list\n * even on a `tempest-fastapi-sdk` backend, so it stays authoritative.\n * - A named field with no readable message produces nothing. The only string\n * left at that point is the synthetic `Erro <status>`, and `{ phone: \"Erro 422\" }`\n * on an input is noise rather than an error message.\n *\n * @param body - The parsed error body, or null when it was not an object.\n * @param message - The readable message the same body produced, before the\n * synthetic fallback — the string that also becomes `ApiError.detail`.\n * @returns Field name to message, or undefined when nothing named a field.\n */\nfunction collectFields(\n body: Record<string, unknown> | null,\n message: string | undefined,\n): Record<string, string> | undefined {\n const listed = collectListFields(body?.detail);\n if (listed !== undefined) return listed;\n const field = namedField(body);\n if (field === undefined || message === undefined) return undefined;\n return { [field]: message };\n}\n\n/**\n * Collapse a backend `detail` of any shape into a single readable line.\n *\n * FastAPI answers a `422` with `detail` as a **list** of\n * `{ loc, msg, type }` entries, not a string. Passing that through `String()`\n * yields `\"[object Object]\"` — an error message that tells the user nothing and\n * hides which field failed. Each entry becomes `\"<field>: <msg>\"` and the\n * entries are joined with `\"; \"`; a nested object is read through its\n * `msg`/`message`/`detail` string.\n *\n * @param raw - The `detail` (or `message`) value from the error body.\n * @param depth - Current nesting level. Past {@link MAX_DETAIL_DEPTH} the value\n * is treated as unreadable instead of followed further.\n * @returns The rendered message, or undefined when nothing readable is there —\n * letting the caller fall back to the synthetic `Erro <status>`.\n */\nfunction normalizeDetail(raw: unknown, depth: number = 0): string | undefined {\n if (raw === null || raw === undefined) return undefined;\n if (typeof raw === \"string\") return raw === \"\" ? undefined : raw;\n if (typeof raw === \"number\" || typeof raw === \"boolean\") return String(raw);\n if (depth >= MAX_DETAIL_DEPTH) return undefined;\n\n if (Array.isArray(raw)) {\n const lines = raw\n .map((entry) => {\n const message = normalizeDetail(entry, depth + 1);\n if (message === undefined) return undefined;\n const field =\n typeof entry === \"object\" && entry !== null\n ? formatLoc((entry as Record<string, unknown>).loc)\n : undefined;\n return field === undefined ? message : `${field}: ${message}`;\n })\n .filter((line): line is string => line !== undefined);\n return lines.length > 0 ? lines.join(\"; \") : undefined;\n }\n\n if (typeof raw === \"object\") {\n const entry = raw as Record<string, unknown>;\n return (\n normalizeDetail(entry.msg, depth + 1) ??\n normalizeDetail(entry.message, depth + 1) ??\n normalizeDetail(entry.detail, depth + 1)\n );\n }\n\n return undefined;\n}\n\n/**\n * Statuses worth a second attempt, as a set for the sub-500 cases.\n *\n * A network failure (status `0`), a request timeout, a too-early replay, and a\n * rate limit — which usually carries the `Retry-After` the backoff honours.\n * Everything else below 500 is the server refusing on purpose.\n */\nconst RETRIABLE_STATUSES: ReadonlySet<number> = new Set([0, 408, 425, 429]);\n\n/**\n * Whether an HTTP status describes a condition a replay can plausibly fix.\n *\n * The single owner of that decision. It used to be spelled out in three places —\n * the client's own policy, the react-query default and the bare `retry()` helper\n * — and they had already drifted: the query default was missing `425`, so the\n * same `425 Too Early` was replayed through `createApiClient({ retry: true })`\n * and not replayed through `useQuery`. Same app, same error, two behaviours, and\n * no test caught it because each file asserted against its own copy.\n *\n * Deliberately about the status and nothing else. Whether a *non*-API error is\n * worth replaying, and whether the request's method may be replayed at all, are\n * the caller's calls: {@link createApiClient} refuses a non-idempotent method,\n * while a bare `retry()` has no method to inspect.\n *\n * @example\n * await api.get(\"/report\", {\n * retry: { shouldRetry: (error) => isApiError(error) && isRetriableStatus(error.status) },\n * });\n *\n * @param status - The HTTP status, where `0` means the request never landed.\n * @returns Whether a retry is worth attempting.\n */\nexport function isRetriableStatus(status: number): boolean {\n return RETRIABLE_STATUSES.has(status) || status >= 500;\n}\n\n/**\n * Detail text synthesised when a response body carries none.\n *\n * Exported because {@link describeApiError} has to recognise it: a detail the\n * server never sent says strictly less than the caller's own fallback, so the\n * funnel drops it. Comparing against a copied literal would silently stop\n * matching the day this sentence is reworded — no type error, no failing test.\n *\n * @param status - The HTTP status of the error.\n * @returns The synthetic detail for that status.\n */\nexport function syntheticDetail(status: number): string {\n return `Erro ${status}`;\n}\n\n/**\n * Parse an error body + response into the Tempest {@link ApiError} envelope.\n *\n * Reads `detail`/`message`, the programmatic `code`, and the correlation id\n * from `details.request_id` (falling back to the `X-Request-ID` header, then\n * the id the client sent).\n *\n * A `422` from FastAPI carries `detail` as a list of `{ loc, msg, type }`\n * entries, so it is flattened to `\"<field>: <msg>; <field>: <msg>\"` instead of\n * being stringified into `\"[object Object]\"`, and the same entries are indexed\n * on `fields` (`{ email: \"Field required\" }`) for a form to consume without\n * parsing that line back apart. The untouched body stays on `body`.\n *\n * A backend that owns its handlers — every `tempest-fastapi-sdk` app — sends no\n * such list, and names the field in a key instead:\n *\n * ```json\n * { \"detail\": \"Value error, … for field 'phone' in 'body'\", \"field\": \"phone\" }\n * { \"detail\": { \"detail\": \"Cidade não encontrada…\", \"field\": \"city\" },\n * \"code\": \"VALIDATION_ERROR\", \"details\": { \"field\": \"city\" } }\n * ```\n *\n * Those are indexed too, keyed by the field the backend named and valued with the\n * same sentence that becomes `detail`. Precedence is the list first, then\n * `detail.field`, `field`, `details.field` — see {@link collectFields}.\n *\n * A flattened `detail` from the list is developer-facing: it carries the\n * backend's field paths and the validator's own wording. `describeApiError` knows\n * not to show it to a person when `fields` is set — which now also covers a\n * business error that named a field, whose `detail` was a finished sentence. That\n * sentence is not lost: it is on `fields`, attached to the input that failed.\n *\n * @param status - HTTP status code.\n * @param body - The parsed error body (object, string, or null).\n * @param headers - The response headers (for the `X-Request-ID` fallback).\n * @param sentRequestId - The id the client sent on the request, if any.\n * @returns A fully-populated `ApiError`.\n *\n * @tempest-limits param-count — the arguments are the response as it arrives\n * (`status`, `body`, `headers`) plus the id the request was sent with, and they are\n * passed at exactly three places, all of them a client's response path\n * (`createApiClient`, `uploadWithProgress`, `createResumableUpload`). Wrapping them\n * in an options object would name each argument twice at every call site to say\n * nothing new.\n */\nexport function buildApiError(\n status: number,\n body: unknown,\n headers?: Headers | { get(name: string): string | null },\n sentRequestId?: string,\n): ApiError {\n const obj =\n typeof body === \"object\" && body !== null ? (body as Record<string, unknown>) : null;\n const message = trimFieldSuffix(\n normalizeDetail(obj?.detail) ?? normalizeDetail(obj?.message),\n namedField(obj),\n );\n const detail = message ?? syntheticDetail(status);\n const code = typeof obj?.code === \"string\" ? obj.code : undefined;\n const details =\n typeof obj?.details === \"object\" && obj.details !== null\n ? (obj.details as Record<string, unknown>)\n : null;\n const requestId =\n (typeof details?.request_id === \"string\" ? details.request_id : undefined) ??\n headers?.get(\"X-Request-ID\") ??\n sentRequestId ??\n undefined;\n\n return {\n status,\n detail,\n code,\n requestId: requestId ?? undefined,\n retryAfter: parseRetryAfter(headers?.get(\"Retry-After\")),\n fields: collectFields(obj, message),\n body,\n };\n}\n\n/**\n * Parse a `Retry-After` header into seconds. Accepts a delta-seconds integer\n * (`\"120\"`) or an HTTP-date (`\"Wed, 21 Oct 2015 07:28:00 GMT\"`).\n *\n * @param value - The raw header value, or null.\n * @returns The delay in seconds (>= 0), or undefined when absent/unparseable.\n */\nexport function parseRetryAfter(value: string | null | undefined): number | undefined {\n if (!value) return undefined;\n const trimmed = value.trim();\n if (/^\\d+$/.test(trimmed)) return Number(trimmed);\n const when = Date.parse(trimmed);\n if (Number.isNaN(when)) return undefined;\n return Math.max(0, Math.round((when - Date.now()) / 1000));\n}\n"],"mappings":";AAkBA,IAAa,IAAb,cAAqC,MAA0B;CAC3D;CACA;CACA;CACA;CACA;CACA;CAEA,YAAY,GAAgB;EAQxB,AAPA,MAAM,EAAK,MAAM,GACjB,KAAK,OAAO,mBACZ,KAAK,SAAS,EAAK,QACnB,KAAK,SAAS,EAAK,QACnB,KAAK,OAAO,EAAK,MACjB,KAAK,YAAY,EAAK,WACtB,KAAK,SAAS,EAAK,QACnB,KAAK,OAAO,EAAK;CACrB;AACJ,GA2Ba,IAAb,cAA4C,MAAM;CAC9C,cAAc;EAEV,AADA,MAAM,8CAA8C,GACpD,KAAK,OAAO;CAChB;AACJ;AASA,SAAgB,EAAW,GAAmC;CAC1D,OACI,OAAO,KAAU,cACjB,KACA,OAAQ,EAAmB,UAAW,YACtC,OAAQ,EAAmB,UAAW;AAE9C;AAOA,IAAM,oBAAiC,IAAI,IAAI;CAAC;CAAQ;CAAS;CAAQ;CAAU;AAAQ,CAAC;AAS5F,SAAS,EAAU,GAAkC;CACjD,IAAI,CAAC,MAAM,QAAQ,CAAG,GAAG;CACzB,IAAM,IAAQ,EACT,QACI,MAAkC,OAAO,KAAS,YAAY,OAAO,KAAS,QACnF,CAAC,CACA,QAAQ,GAAM,MAAU,EAAE,MAAU,KAAK,EAAU,IAAI,OAAO,CAAI,CAAC,EAAE;CAC1E,OAAO,EAAM,SAAS,IAAI,E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AClB,GACM,IAAS,KAAW,EAAgB,CAAM,GAC1C,IAAO,OAAO,GAAK,QAAS,WAAW,EAAI,OAAO,KAAA,GAClD,IACF,OAAO,GAAK,WAAY,YAAY,EAAI,YAAY,OAC7C,EAAI,UACL;CAOV,OAAO;EACH;EACA;EACA;EACA,YATC,OAAO,GAAS,cAAe,WAAW,EAAQ,aAAa,KAAA,MAChE,GAAS,IAAI,cAAc,KAC3B,KACA,KAAA,KAMwB,KAAA;EACxB,YAAY,EAAgB,GAAS,IAAI,aAAa,CAAC;EACvD,QAAQ,EAAc,GAAK,CAAO;EAClC;CACJ;AACJ;AASA,SAAgB,EAAgB,GAAsD;CAClF,IAAI,CAAC,GAAO;CACZ,IAAM,IAAU,EAAM,KAAK;CAC3B,IAAI,QAAQ,KAAK,CAAO,GAAG,OAAO,OAAO,CAAO;CAChD,IAAM,IAAO,KAAK,MAAM,CAAO;CAC3B,YAAO,MAAM,CAAI,GACrB,OAAO,KAAK,IAAI,GAAG,KAAK,OAAO,IAAO,KAAK,IAAI,KAAK,GAAI,CAAC;AAC7D"}
@@ -0,0 +1,2 @@
1
+ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});let e=require("@sapphi-red/web-noise-suppressor");function t(){return typeof AudioWorkletNode<`u`&&typeof window<`u`&&window.isSecureContext}var n=null,r=new WeakMap;async function i(t,i){let a=r.get(t);return a||(a=t.audioWorklet.addModule(i.workletUrl).then(()=>void 0,e=>{throw r.delete(t),e}),r.set(t,a)),await a,n===null&&(n=(0,e.loadRnnoise)({url:i.wasmUrl,simdUrl:i.simdWasmUrl}).catch(e=>{throw n=null,e})),n}async function a(t,n,r,a){if(t.sampleRate!==48e3)return null;let o;try{o=await i(t,r)}catch{return null}let s;try{s=new e.RnnoiseWorkletNode(t,{maxChannels:a.maxChannels,wasmBinary:o})}catch{return null}let c=t.createMediaStreamSource(new MediaStream([n])),l=t.createMediaStreamDestination();c.connect(s),s.connect(l);let u=l.stream.getAudioTracks()[0];return u?(u.contentHint=n.contentHint,{track:u,release:()=>{c.disconnect(),s.disconnect(),l.disconnect(),s.destroy(),u.stop()}}):(c.disconnect(),s.disconnect(),l.disconnect(),s.destroy(),null)}exports.createNeuralSuppressor=a,exports.isNeuralSuppressionSupported=t,exports.prepareNeuralSuppressor=i;
2
+ //# sourceMappingURL=neural.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"neural.cjs","names":[],"sources":["../src/neural/index.ts"],"sourcesContent":["import { RnnoiseWorkletNode, loadRnnoise } from \"@sapphi-red/web-noise-suppressor\";\n\n/**\n * Where the suppressor's three pieces live, as URLs a bundler hands over.\n *\n * The `@sapphi-red/web-noise-suppressor` package ships the runnable assets next\n * to its code, but it cannot say where they are from inside a library: the\n * `?url` suffix that resolves a module to its served address is a bundler\n * feature, and every bundler answers it differently. So this subpath takes the\n * three resolved addresses as arguments and does the honest part — the graph,\n * the load-once semantics, the per-context registration — here.\n */\nexport interface NeuralSuppressorAssets {\n /**\n * The `AudioWorklet` processor module the model runs its DSP in\n * (`rnnoiseWorklet.js`).\n */\n workletUrl: string;\n /** The SIMD build of the model's wasm (`rnnoise_simd.wasm`). */\n simdWasmUrl: string;\n /** The baseline build, used where the engine lacks SIMD (`rnnoise.wasm`). */\n wasmUrl: string;\n}\n\n/**\n * Whether this browser can run a worklet-based noise suppressor.\n *\n * Answered from the two things the path needs that nothing but the platform can\n * supply: `AudioWorkletNode` runs custom DSP on the audio thread, and a secure\n * context is what the browser requires before letting a module near the\n * microphone graph. Everything else — the models, the wasm — ships with the\n * caller, so it cannot be missing. The context must also run at 48 kHz, which\n * is checked at build time rather than here because the caller owns how its\n * context was opened.\n *\n * Deliberately conservative: anything it cannot establish answers `false`, and\n * a `false` sends the caller back to the browser's own `noiseSuppression`\n * constraint, which is weaker but always there.\n *\n * @returns True when a neural suppressor can be built on top of a capture.\n */\nexport function isNeuralSuppressionSupported(): boolean {\n return (\n typeof AudioWorkletNode !== \"undefined\" &&\n typeof window !== \"undefined\" &&\n window.isSecureContext\n );\n}\n\n/**\n * The one wasm binary every suppressor shares, fetched once.\n *\n * `loadRnnoise` compiles the whole model, and the answer is identical for every\n * graph that opens afterwards — a mesh can build a suppressor per published\n * track and a settings dialog may build a second for its monitor within a\n * single frame. Held as the promise rather than the result so the first two\n * callers race into one fetch instead of two. Reset on failure, so the next\n * call retries instead of replaying a dead promise.\n */\nlet loadingBinary: Promise<ArrayBuffer> | null = null;\n\n/**\n * The contexts the worklet module has already been registered on, mapped to the\n * registration's own promise.\n *\n * `addModule` is per-context and throws on a name it already holds, so the\n * module records the moment a context is ready and skips the call next time.\n * The promise is what makes a fast caller that cannot wait — a mesh can open a\n * microphone and a preview within a single frame — race into one `addModule`\n * instead of two: had this been a set, the second caller would see the context\n * absent while the first was still awaiting and register the module twice.\n * Mapped to a promise rather than the module itself the way the wasm is,\n * because the registration belongs to one context while the wasm is shared,\n * and nothing here should keep a dead context alive — the value is dropped\n * with the context. On failure the entry is removed, so the next attempt\n * actually retries instead of replaying the broken registration.\n */\nconst readyContexts = new WeakMap<AudioContext, Promise<void>>();\n\n/**\n * The compiled model for this context, loading what is not ready yet.\n *\n * Idempotent across calls: the wasm fetch and the module registration both\n * happen exactly once. The wasm is shared by every suppressor, while the module\n * registration belongs to one context.\n *\n * @param context - The context the suppression graph will run in.\n * @param assets - The resolved asset addresses from {@link NeuralSuppressorAssets}.\n * @returns The compiled model binary, ready to hand to a worklet node.\n * @throws Whatever the fetch or the compile threw, for the caller to fall back on.\n */\nexport async function prepareNeuralSuppressor(\n context: AudioContext,\n assets: NeuralSuppressorAssets,\n): Promise<ArrayBuffer> {\n let ready = readyContexts.get(context);\n if (!ready) {\n ready = context.audioWorklet.addModule(assets.workletUrl).then(\n () => undefined,\n (error: unknown) => {\n readyContexts.delete(context);\n throw error;\n },\n );\n readyContexts.set(context, ready);\n }\n await ready;\n if (loadingBinary === null) {\n loadingBinary = loadRnnoise({ url: assets.wasmUrl, simdUrl: assets.simdWasmUrl }).catch(\n (error: unknown) => {\n loadingBinary = null;\n throw error;\n },\n );\n }\n return loadingBinary;\n}\n\n/**\n * A denoised track plus the graph that has to come down with it.\n *\n * `track` is not the captured one — it is the output of a `MediaStream`\n * destination the worklet feeds — so stopping the published track is not enough\n * to free the microphone. `release` closes the graph; the captured track behind\n * it belongs to the caller.\n */\nexport interface NeuralSuppressor {\n /** The track to publish in place of the captured one. */\n track: MediaStreamTrack;\n /** Tears the graph down. Does not stop the source track it was built from. */\n release(): void;\n}\n\n/**\n * Build a suppressor graph on top of a captured microphone track.\n *\n * The model runs on the audio thread through an `AudioWorkletNode` — a\n * recurrent network trained on speech that separates a voice from everything\n * that is not one: keyboards, fans, traffic, a room full of people. The\n * browser's `noiseSuppression` constraint answers the same question with a\n * stationary-noise gate that either lets a transient through or eats the voice\n * with it.\n *\n * Prefer {@link prepareNeuralSuppressor} before the capture opens: the fallback\n * to the browser's own suppression is a `getUserMedia` constraint, and a\n * constraint cannot be added to a capture that already exists. A caller that\n * did not preload still works — the load happens here, idempotently.\n *\n * The model assumes 48 kHz. A context opened at any other rate answers `null`\n * before anything is fetched, because feeding speech samples of the wrong rate\n * into a network trained on 48 kHz produces mush, not a voice.\n *\n * Failure is not fatal and is reported as `null` — whether the wasm would not\n * load or the worklet node could not be built: by the time this runs the caller\n * has already committed to the neural path, so the honest outcome is a call\n * without suppression rather than a microphone that will not open. {@link\n * prepareNeuralSuppressor}, which exists to be called *before* the capture,\n * still throws so the caller can pick a different fallback while one is\n * reachable.\n *\n * @param context - The shared context, prepared at 48 kHz.\n * @param source - The captured microphone track.\n * @param assets - The resolved asset addresses from {@link NeuralSuppressorAssets}.\n * @param options - `maxChannels` is the channel count of the capture; the model\n * is mono, and a stereo capture asks for two so a second channel is not lost.\n * @returns The denoised track and its teardown, or `null` when this context or\n * this graph cannot host the suppressor.\n */\nexport async function createNeuralSuppressor(\n context: AudioContext,\n source: MediaStreamTrack,\n assets: NeuralSuppressorAssets,\n options: { maxChannels: number },\n): Promise<NeuralSuppressor | null> {\n if (context.sampleRate !== 48_000) return null;\n\n let binary: ArrayBuffer;\n try {\n binary = await prepareNeuralSuppressor(context, assets);\n } catch {\n return null;\n }\n\n let node: RnnoiseWorkletNode;\n try {\n node = new RnnoiseWorkletNode(context, {\n maxChannels: options.maxChannels,\n wasmBinary: binary,\n });\n } catch {\n return null;\n }\n\n const input = context.createMediaStreamSource(new MediaStream([source]));\n const output = context.createMediaStreamDestination();\n input.connect(node);\n node.connect(output);\n\n const track = output.stream.getAudioTracks()[0];\n if (!track) {\n input.disconnect();\n node.disconnect();\n output.disconnect();\n node.destroy();\n return null;\n }\n track.contentHint = source.contentHint;\n\n return {\n track,\n release: () => {\n input.disconnect();\n node.disconnect();\n output.disconnect();\n node.destroy();\n track.stop();\n },\n };\n}\n"],"mappings":"qHAyCA,SAAgB,GAAwC,CACpD,OACI,OAAO,iBAAqB,KAC5B,OAAO,OAAW,KAClB,OAAO,eAEf,CAYA,IAAI,EAA6C,KAkB3C,EAAgB,IAAI,QAc1B,eAAsB,EAClB,EACA,EACoB,CACpB,IAAI,EAAQ,EAAc,IAAI,CAAO,EAoBrC,OAnBK,IACD,EAAQ,EAAQ,aAAa,UAAU,EAAO,UAAU,CAAC,CAAC,SAChD,IAAA,GACL,GAAmB,CAEhB,MADA,EAAc,OAAO,CAAO,EACtB,CACV,CACJ,EACA,EAAc,IAAI,EAAS,CAAK,GAEpC,MAAM,EACF,IAAkB,OAClB,GAAA,EAAgB,EAAA,YAAA,CAAY,CAAE,IAAK,EAAO,QAAS,QAAS,EAAO,WAAY,CAAC,CAAC,CAAC,MAC7E,GAAmB,CAEhB,KADA,GAAgB,KACV,CACV,CACJ,GAEG,CACX,CAoDA,eAAsB,EAClB,EACA,EACA,EACA,EACgC,CAChC,GAAI,EAAQ,aAAe,KAAQ,OAAO,KAE1C,IAAI,EACJ,GAAI,CACA,EAAS,MAAM,EAAwB,EAAS,CAAM,CAC1D,MAAQ,CACJ,OAAO,IACX,CAEA,IAAI,EACJ,GAA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