tempest-react-sdk 0.43.0 → 0.45.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.
- package/README.md +12 -5
- package/dist/app/AppProviders.cjs +1 -1
- package/dist/app/AppProviders.js +6 -6
- package/dist/audio/sfx-pool.cjs +2 -0
- package/dist/audio/sfx-pool.cjs.map +1 -0
- package/dist/audio/sfx-pool.js +62 -0
- package/dist/audio/sfx-pool.js.map +1 -0
- package/dist/audio/use-sfx-pool.cjs +2 -0
- package/dist/audio/use-sfx-pool.cjs.map +1 -0
- package/dist/audio/use-sfx-pool.js +18 -0
- package/dist/audio/use-sfx-pool.js.map +1 -0
- package/dist/auth/create-tempest-auth.cjs +1 -1
- package/dist/auth/create-tempest-auth.cjs.map +1 -1
- package/dist/auth/create-tempest-auth.js +47 -44
- package/dist/auth/create-tempest-auth.js.map +1 -1
- package/dist/auth/lazy-with-retry.cjs +1 -1
- package/dist/auth/lazy-with-retry.cjs.map +1 -1
- package/dist/auth/lazy-with-retry.js +8 -1
- package/dist/auth/lazy-with-retry.js.map +1 -1
- package/dist/components/AppBar/AppBar.cjs +1 -1
- package/dist/components/AppBar/AppBar.cjs.map +1 -1
- package/dist/components/AppBar/AppBar.js +27 -25
- package/dist/components/AppBar/AppBar.js.map +1 -1
- package/dist/components/AppBar/use-sticky-body-warning.cjs +2 -0
- package/dist/components/AppBar/use-sticky-body-warning.cjs.map +1 -0
- package/dist/components/AppBar/use-sticky-body-warning.js +16 -0
- package/dist/components/AppBar/use-sticky-body-warning.js.map +1 -0
- package/dist/components/BarList/BarList.cjs +2 -0
- package/dist/components/BarList/BarList.cjs.map +1 -0
- package/dist/components/BarList/BarList.js +42 -0
- package/dist/components/BarList/BarList.js.map +1 -0
- package/dist/components/BarList/BarList.module.cjs +2 -0
- package/dist/components/BarList/BarList.module.cjs.map +1 -0
- package/dist/components/BarList/BarList.module.js +15 -0
- package/dist/components/BarList/BarList.module.js.map +1 -0
- package/dist/components/BarList/bar-list-model.cjs +2 -0
- package/dist/components/BarList/bar-list-model.cjs.map +1 -0
- package/dist/components/BarList/bar-list-model.js +18 -0
- package/dist/components/BarList/bar-list-model.js.map +1 -0
- package/dist/components/DataTable/DataTable.cjs +1 -1
- package/dist/components/DataTable/DataTable.cjs.map +1 -1
- package/dist/components/DataTable/DataTable.js +141 -108
- package/dist/components/DataTable/DataTable.js.map +1 -1
- package/dist/components/DataTable/DataTable.module.cjs +1 -1
- package/dist/components/DataTable/DataTable.module.cjs.map +1 -1
- package/dist/components/DataTable/DataTable.module.js +13 -10
- package/dist/components/DataTable/DataTable.module.js.map +1 -1
- package/dist/components/DataTable/LoadingRows.cjs +2 -0
- package/dist/components/DataTable/LoadingRows.cjs.map +1 -0
- package/dist/components/DataTable/LoadingRows.js +18 -0
- package/dist/components/DataTable/LoadingRows.js.map +1 -0
- package/dist/components/DataTable/use-dev-warnings.cjs +2 -0
- package/dist/components/DataTable/use-dev-warnings.cjs.map +1 -0
- package/dist/components/DataTable/use-dev-warnings.js +17 -0
- package/dist/components/DataTable/use-dev-warnings.js.map +1 -0
- package/dist/components/FilterBar/filter-apply.cjs +2 -0
- package/dist/components/FilterBar/filter-apply.cjs.map +1 -0
- package/dist/components/FilterBar/filter-apply.js +76 -0
- package/dist/components/FilterBar/filter-apply.js.map +1 -0
- package/dist/components/FilterBar/filter-query.cjs +2 -0
- package/dist/components/FilterBar/filter-query.cjs.map +1 -0
- package/dist/components/FilterBar/filter-query.js +38 -0
- package/dist/components/FilterBar/filter-query.js.map +1 -0
- package/dist/hooks/use-countdown.cjs +2 -0
- package/dist/hooks/use-countdown.cjs.map +1 -0
- package/dist/hooks/use-countdown.js +18 -0
- package/dist/hooks/use-countdown.js.map +1 -0
- package/dist/hooks/use-latest-ref.cjs +2 -0
- package/dist/hooks/use-latest-ref.cjs.map +1 -0
- package/dist/hooks/use-latest-ref.js +10 -0
- package/dist/hooks/use-latest-ref.js.map +1 -0
- package/dist/hooks/use-typewriter.cjs +2 -0
- package/dist/hooks/use-typewriter.cjs.map +1 -0
- package/dist/hooks/use-typewriter.js +28 -0
- package/dist/hooks/use-typewriter.js.map +1 -0
- package/dist/http/api-client.cjs +1 -1
- package/dist/http/api-client.cjs.map +1 -1
- package/dist/http/api-client.js +42 -43
- package/dist/http/api-client.js.map +1 -1
- package/dist/http/build-url.cjs +2 -0
- package/dist/http/build-url.cjs.map +1 -0
- package/dist/http/build-url.js +26 -0
- package/dist/http/build-url.js.map +1 -0
- package/dist/http/describe-api-error.cjs +2 -0
- package/dist/http/describe-api-error.cjs.map +1 -0
- package/dist/http/describe-api-error.js +22 -0
- package/dist/http/describe-api-error.js.map +1 -0
- package/dist/http/use-describe-api-error.cjs +2 -0
- package/dist/http/use-describe-api-error.cjs.map +1 -0
- package/dist/http/use-describe-api-error.js +15 -0
- package/dist/http/use-describe-api-error.js.map +1 -0
- package/dist/i18n/I18nProvider.cjs +1 -1
- package/dist/i18n/I18nProvider.cjs.map +1 -1
- package/dist/i18n/I18nProvider.js +4 -1
- package/dist/i18n/I18nProvider.js.map +1 -1
- package/dist/query/QueryProvider.cjs +1 -1
- package/dist/query/QueryProvider.cjs.map +1 -1
- package/dist/query/QueryProvider.js +13 -12
- package/dist/query/QueryProvider.js.map +1 -1
- package/dist/query/retry-policy.cjs +2 -0
- package/dist/query/retry-policy.cjs.map +1 -0
- package/dist/query/retry-policy.js +10 -0
- package/dist/query/retry-policy.js.map +1 -0
- package/dist/styles.css +1 -1
- package/dist/tempest-react-sdk.cjs +1 -1
- package/dist/tempest-react-sdk.d.ts +867 -10
- package/dist/tempest-react-sdk.js +276 -261
- package/dist/utils/compressed-storage.cjs +2 -0
- package/dist/utils/compressed-storage.cjs.map +1 -0
- package/dist/utils/compressed-storage.js +52 -0
- package/dist/utils/compressed-storage.js.map +1 -0
- package/dist/utils/csv.cjs +4 -0
- package/dist/utils/csv.cjs.map +1 -0
- package/dist/utils/csv.js +25 -0
- package/dist/utils/csv.js.map +1 -0
- package/dist/utils/format.cjs +1 -1
- package/dist/utils/format.cjs.map +1 -1
- package/dist/utils/format.js +11 -4
- package/dist/utils/format.js.map +1 -1
- package/dist/utils/numbers.cjs +1 -1
- package/dist/utils/numbers.cjs.map +1 -1
- package/dist/utils/numbers.js +5 -2
- package/dist/utils/numbers.js.map +1 -1
- package/dist/vite/tempest-pwa-dev-sw.cjs +1 -1
- package/dist/vite/tempest-pwa-dev-sw.cjs.map +1 -1
- package/dist/vite/tempest-pwa-dev-sw.js +10 -5
- package/dist/vite/tempest-pwa-dev-sw.js.map +1 -1
- package/dist/vite/tempest-pwa-manifest.cjs +2 -2
- package/dist/vite/tempest-pwa-manifest.cjs.map +1 -1
- package/dist/vite/tempest-pwa-manifest.js +17 -13
- package/dist/vite/tempest-pwa-manifest.js.map +1 -1
- package/dist/vite.d.ts +19 -2
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -230,7 +230,7 @@ Every module is re-exported from the package root — `import { Button, useDebou
|
|
|
230
230
|
| ------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
231
231
|
| `components` | `Avatar`, `Badge`, `Breadcrumbs`, `Button`, `Card`, `Checkbox`, `ChipInput`, `ConfirmDialog`, `Container`, `DatePicker`, `Drawer`, `EmptyState`, `ErrorState`, `FileUpload`, `Form` (`FormSection`, `FormRow`, `FormActions`), `Grid`, `Input`, `InstallBanner`, `InstallButton`, `Modal`, `Pagination`, `Progress`, `Radio`, `RadioGroup`, `SearchBar`, `Select`, `Skeleton`, `Spinner`, `Stack`, `Stepper`, `Switch`, `Table`, `Tabs`, `Textarea`, `Toast` (`ToastProvider`, `useToast`), `Tooltip`, `VirtualList` |
|
|
232
232
|
| `hooks` | `useDebounce`, `usePagination`, `useClientFilter`, `useMediaQuery`, `useOnline`, `useDocumentVisibility`, `useIntersectionObserver`, `useResizeObserver`, `useClipboard`, `useKeyboardShortcut`, `useBeforeInstallPrompt`, `useIdle`, `useGeolocation`, `useScrollLock`, `useFocusTrap`, `useStableCallback`, `useAnnounce` (+ pure `announce`/`clearAnnouncer` — one shared live-region pair), `useDeepMemo`, `useObjectUrl`, `useLongPressHandlers` (spreadable long-press handlers + `wasLongPress()` guard), `useInstallPrompt` (install-method resolver with decline cooldown), `useServiceWorkerUpdate` (consent-based SW update flow), `useStorageEstimate` + `estimateStorage`/`requestPersistentStorage` (Storage API quota & persistence), PWA env helpers `isIOS`/`isAndroid`/`isAndroidWithoutPromptApi`/`isStandalone`/`buildOpenInChromeIntent`, type `BeforeInstallPromptEvent` |
|
|
233
|
-
| `http` | `createApiClient`, `parseResponse`, `uploadWithProgress`, `createResumableUpload` (tus 1.0.0: chunked + resumable, `pause`/`resume`/`abort`), `createLocalUploadStorage`, `uploadFingerprint`, `retry`, `generateIdempotencyKey`, `usePoll`, types: `ApiClient`, `ApiClientConfig`, `ApiError`, `RequestOptions`, `RetryOptions`, `UploadProgressEvent`, `UploadWithProgressOptions`, `UsePollOptions`, `UsePollResult`
|
|
233
|
+
| `http` | `createApiClient`, `buildApiUrl`, `parseResponse`, `uploadWithProgress`, `createResumableUpload` (tus 1.0.0: chunked + resumable, `pause`/`resume`/`abort`), `createLocalUploadStorage`, `uploadFingerprint`, `retry`, `generateIdempotencyKey`, `usePoll`, types: `ApiClient`, `ApiClientConfig`, `ApiError`, `BuildApiUrlOptions`, `RequestOptions`, `RetryOptions`, `UploadProgressEvent`, `UploadWithProgressOptions`, `UsePollOptions`, `UsePollResult` |
|
|
234
234
|
| `auth` _(peer: `zustand`)_ | `createAuthStore`, `AuthGuard`, `decodeJWT`, `isJWTExpired`, `lazyWithRetry`, `createRefreshQueue`, **passkeys/WebAuthn**: `createPasskeyClient`, `usePasskeyRegistration`, `usePasskeySignIn`, `usePasskeyCapabilities`, `isPasskeySupported`, `isPlatformAuthenticatorAvailable`, `isConditionalMediationAvailable`, `classifyPasskeyError`, `PasskeyError`, `base64UrlToBytes`, `bytesToBase64Url`, types: `AuthState`, `CreateAuthStoreOptions`, `AuthGuardProps`, `DecodedJWT`, `LazyWithRetryOptions` |
|
|
235
235
|
| `oauth` _(caller injects `@react-oauth/google`)_ | `GoogleSignIn` (normalises Google's credential/error payload), `useOAuthCallback` (runs the callback exchange once, StrictMode-proof), types: `GoogleSignInProps`, `OAuthCredential`, `OAuthError`, `UseOAuthCallbackOptions`, `UseOAuthCallbackResult` |
|
|
236
236
|
| `query` _(peer: `@tanstack/react-query`)_ | `QueryProvider`, `createQueryKeys`, `STALE_TIME`, `CACHE_TIME`, `REFETCH_TIME`, `usePaginatedQuery`, `useCursorQuery`, `useOfflineMutation` (optimistic offline mutation + cache rollback), `upsertById`/`removeById` (optimistic list-cache helpers), `persistQueryClientOffline` (IndexedDB cache persistence for offline reads) |
|
|
@@ -258,13 +258,13 @@ Every module is re-exported from the package root — `import { Button, useDebou
|
|
|
258
258
|
| `perf` | `createInferenceProfiler`, `readDeviceProfile`, `cachedResponseBytes`, `formatDurationMs`, types: `InferenceProfiler`, `InferenceReport`, `InferenceReportOptions`, `DeviceProfile`, `ProfiledModel`, `ProfiledModelSize` — custo de inferência on-device: cronômetro por etapa, perfil do dispositivo (cores/RAM/heap) e tamanho dos modelos em Cache Storage |
|
|
259
259
|
| `feature-flags` | `FeatureFlagsProvider`, `useFeatureFlag`, `useFlagValue`, `createInMemoryFlags`, `createGrowthBookFeatureFlagsAdapter`, `createLaunchDarklyFeatureFlagsAdapter`, types: `FeatureFlagsAdapter`, `FlagValue`, `GrowthBookLike`, `LDClientLike` |
|
|
260
260
|
| `share` | `share`, `isShareSupported`, `shareOrDownloadBlob` (Web Share file → download fallback), types: `SharePayload`, `ShareResult`, `ShareOrDownloadOptions` |
|
|
261
|
-
| `utils` | `cn`, format BR (`formatCurrency`, `formatDate`, `formatDateTime`, `formatPhone`, `formatCPF`, `formatPercent`), `storage`, strings (`slugify`, `truncate`, `capitalize`, `camelCase`, `kebabCase`, `pluralize`), numbers (`clamp`, `formatBytes`, `formatCompactNumber`), arrays (`groupBy`, `uniqueBy`, `chunk`, `range`), objects (`pick`, `omit`, `deepMerge`, `isEmpty`), guards (`isDefined`, `isString`, `isNumber`, `isPlainObject`, `assertNever`), functions (`debounce`, `throttle`, `once`, `memoizeOne`), promises (`sleep`, `withTimeout`), `randomId`, `relativeTime`, `writeXlsx` (generic single-sheet OOXML `.xlsx` writer → `Uint8Array`)
|
|
261
|
+
| `utils` | `cn`, format BR (`formatCurrency`, `formatDate`, `formatDateForInput`, `formatDateTime`, `formatPhone`, `formatCPF`, `formatPercent`), `storage`, strings (`slugify`, `truncate`, `capitalize`, `camelCase`, `kebabCase`, `pluralize`), numbers (`clamp`, `formatBytes`, `formatCompactNumber`, `percentOf`), arrays (`groupBy`, `uniqueBy`, `chunk`, `range`), objects (`pick`, `omit`, `deepMerge`, `isEmpty`), guards (`isDefined`, `isString`, `isNumber`, `isPlainObject`, `assertNever`), functions (`debounce`, `throttle`, `once`, `memoizeOne`), promises (`sleep`, `withTimeout`), `randomId`, `relativeTime`, `writeXlsx` (generic single-sheet OOXML `.xlsx` writer → `Uint8Array`), CSV (`toCsv`, `downloadCsv` — RFC 4180 escaping + BOM) |
|
|
262
262
|
| generic components | display (`CopyButton`, `RelativeTime`, `Money`, `TruncateText`, `VisuallyHidden`), headless (`Portal`, `ClickOutside`, `ConditionalWrapper`, `For`, `ErrorText`), media/content (`Image`, `DataList`, `DescriptionList`) |
|
|
263
263
|
| Module | Exports |
|
|
264
264
|
| ------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
|
|
265
265
|
| `components` | `Avatar`, `Badge`, `Breadcrumbs`, `Button`, `Card`, `Checkbox`, `ChipInput`, `ConfirmDialog`, `Container`, `DatePicker`, `Drawer`, `EmptyState`, `ErrorState`, `FileUpload`, `Form` (`FormSection`, `FormRow`, `FormActions`), `Grid`, `Input`, `InstallBanner`, `InstallButton`, `Modal`, `Pagination`, `Progress`, `Radio`, `RadioGroup`, `SearchBar`, `Select`, `Skeleton`, `Spinner`, `Stack`, `Stepper`, `Switch`, `Table`, `Tabs`, `Textarea`, `Toast` (`ToastProvider`, `useToast`), `Tooltip`, `VirtualList` |
|
|
266
266
|
| `hooks` | `useDebounce`, `usePagination`, `useClientFilter`, `useMediaQuery`, `useOnline`, `useDocumentVisibility`, `useIntersectionObserver`, `useResizeObserver`, `useClipboard`, `useKeyboardShortcut`, `useBeforeInstallPrompt`, `useIdle`, `useGeolocation`, `useScrollLock`, `useFocusTrap`, `useStableCallback`, `useDeepMemo`, `useObjectUrl`, `useLongPressHandlers` (spreadable long-press handlers + `wasLongPress()` guard), `useInstallPrompt` (install-method resolver with decline cooldown), `useServiceWorkerUpdate` (consent-based SW update flow), `useStorageEstimate` + `estimateStorage`/`requestPersistentStorage` (Storage API quota & persistence), PWA env helpers `isIOS`/`isAndroid`/`isAndroidWithoutPromptApi`/`isStandalone`/`buildOpenInChromeIntent`, type `BeforeInstallPromptEvent` |
|
|
267
|
-
| `http` | `createApiClient`, `parseResponse`, `uploadWithProgress`, `retry`, `generateIdempotencyKey`, `usePoll`, types: `ApiClient`, `ApiClientConfig`, `ApiError`, `RequestOptions`, `RetryOptions`, `UploadProgressEvent`, `UploadWithProgressOptions`, `UsePollOptions`, `UsePollResult`
|
|
267
|
+
| `http` | `createApiClient`, `buildApiUrl`, `parseResponse`, `uploadWithProgress`, `retry`, `generateIdempotencyKey`, `usePoll`, types: `ApiClient`, `ApiClientConfig`, `ApiError`, `BuildApiUrlOptions`, `RequestOptions`, `RetryOptions`, `UploadProgressEvent`, `UploadWithProgressOptions`, `UsePollOptions`, `UsePollResult` |
|
|
268
268
|
| `auth` _(peer: `zustand`)_ | `createAuthStore`, `AuthGuard`, `decodeJWT`, `isJWTExpired`, `lazyWithRetry`, `createRefreshQueue`, types: `AuthState`, `CreateAuthStoreOptions`, `AuthGuardProps`, `DecodedJWT`, `LazyWithRetryOptions` |
|
|
269
269
|
| `oauth` _(caller injects `@react-oauth/google`)_ | `GoogleSignIn` (normalises Google's credential/error payload), `useOAuthCallback` (runs the callback exchange once, StrictMode-proof), types: `GoogleSignInProps`, `OAuthCredential`, `OAuthError`, `UseOAuthCallbackOptions`, `UseOAuthCallbackResult` |
|
|
270
270
|
| `query` _(peer: `@tanstack/react-query`)_ | `QueryProvider`, `createQueryKeys`, `STALE_TIME`, `CACHE_TIME`, `REFETCH_TIME`, `usePaginatedQuery`, `useCursorQuery`, `useOfflineMutation` (optimistic offline mutation + cache rollback), `upsertById`/`removeById` (optimistic list-cache helpers), `persistQueryClientOffline` (IndexedDB cache persistence for offline reads) |
|
|
@@ -295,7 +295,7 @@ Every module is re-exported from the package root — `import { Button, useDebou
|
|
|
295
295
|
| `perf` | `createInferenceProfiler`, `readDeviceProfile`, `cachedResponseBytes`, `formatDurationMs`, types: `InferenceProfiler`, `InferenceReport`, `InferenceReportOptions`, `DeviceProfile`, `ProfiledModel`, `ProfiledModelSize` — custo de inferência on-device: cronômetro por etapa, perfil do dispositivo (cores/RAM/heap) e tamanho dos modelos em Cache Storage |
|
|
296
296
|
| `feature-flags` | `FeatureFlagsProvider`, `useFeatureFlag`, `useFlagValue`, `createInMemoryFlags`, `createGrowthBookFeatureFlagsAdapter`, `createLaunchDarklyFeatureFlagsAdapter`, types: `FeatureFlagsAdapter`, `FlagValue`, `GrowthBookLike`, `LDClientLike` |
|
|
297
297
|
| `share` | `share`, `isShareSupported`, `shareOrDownloadBlob` (Web Share file → download fallback), types: `SharePayload`, `ShareResult`, `ShareOrDownloadOptions` |
|
|
298
|
-
| `utils` | `cn`, format BR (`formatCurrency`, `formatDate`, `formatDateTime`, `formatPhone`, `formatCPF`, `formatPercent`), `storage`, strings (`slugify`, `truncate`, `capitalize`, `camelCase`, `kebabCase`, `pluralize`), numbers (`clamp`, `formatBytes`, `formatCompactNumber`), arrays (`groupBy`, `uniqueBy`, `chunk`, `range`), objects (`pick`, `omit`, `deepMerge`, `isEmpty`), guards (`isDefined`, `isString`, `isNumber`, `isPlainObject`, `assertNever`), functions (`debounce`, `throttle`, `once`, `memoizeOne`), promises (`sleep`, `withTimeout`), `randomId`, `relativeTime`, `writeXlsx` (generic single-sheet OOXML `.xlsx` writer → `Uint8Array`)
|
|
298
|
+
| `utils` | `cn`, format BR (`formatCurrency`, `formatDate`, `formatDateForInput`, `formatDateTime`, `formatPhone`, `formatCPF`, `formatPercent`), `storage`, strings (`slugify`, `truncate`, `capitalize`, `camelCase`, `kebabCase`, `pluralize`), numbers (`clamp`, `formatBytes`, `formatCompactNumber`, `percentOf`), arrays (`groupBy`, `uniqueBy`, `chunk`, `range`), objects (`pick`, `omit`, `deepMerge`, `isEmpty`), guards (`isDefined`, `isString`, `isNumber`, `isPlainObject`, `assertNever`), functions (`debounce`, `throttle`, `once`, `memoizeOne`), promises (`sleep`, `withTimeout`), `randomId`, `relativeTime`, `writeXlsx` (generic single-sheet OOXML `.xlsx` writer → `Uint8Array`), CSV (`toCsv`, `downloadCsv` — RFC 4180 escaping + BOM) |
|
|
299
299
|
| generic components | display (`CopyButton`, `RelativeTime`, `Money`, `TruncateText`, `VisuallyHidden`), headless (`Portal`, `ClickOutside`, `ConditionalWrapper`, `For`, `ErrorText`), media/content (`Image`, `DataList`, `DescriptionList`) |
|
|
300
300
|
|
|
301
301
|
Full per-module docs are published as a bilingual MkDocs site on GitHub Pages — **[Português (BR)](https://mauriciobenjamin700.github.io/tempest-react-sdk/)** / **[English (US)](https://mauriciobenjamin700.github.io/tempest-react-sdk/en/)** (one page per module + draw.io diagrams in [`docs/diagrams/`](./docs/diagrams)). The source markdown lives in [`docs/`](./docs) (PT-BR base files + `.en.md` translations).
|
|
@@ -581,18 +581,21 @@ import { useAuthStore } from "@/store/auth";
|
|
|
581
581
|
|
|
582
582
|
export const api = createApiClient({
|
|
583
583
|
baseURL: import.meta.env.VITE_API_URL,
|
|
584
|
+
prefix: "/api", // the root_path the service is mounted under
|
|
584
585
|
getToken: () => useAuthStore.getState().token,
|
|
585
586
|
onUnauthorized: () => useAuthStore.getState().logout(),
|
|
586
587
|
withCredentials: true,
|
|
587
588
|
defaultHeaders: { "X-App-Version": __APP_VERSION__ },
|
|
588
589
|
});
|
|
589
590
|
|
|
590
|
-
const user = await api.get<UserResponse>("/users/me");
|
|
591
|
+
const user = await api.get<UserResponse>("/users/me"); // → /api/users/me
|
|
591
592
|
await api.post("/orders", { body: { total: 100, items: [...] } });
|
|
592
593
|
```
|
|
593
594
|
|
|
594
595
|
Every method throws `ApiError` (`status`, `body`, `url`, `code`) on non-2xx responses. `onUnauthorized` is called automatically on 401, before the error is thrown — so you can refresh-and-retry or sign out as you choose.
|
|
595
596
|
|
|
597
|
+
`prefix` is the segment every request is nested under; writing it into `baseURL` (`https://api.example.com/api`) does the same thing, and a relative `baseURL` (`"/api"`) resolves against the current origin for dev-server proxies. The leading slash at the call site makes no difference, and the prefix is never applied twice. `buildApiUrl` exposes the same join for URLs built outside the client (an SSE `EventSource`, an `<img>`). See [HTTP → Base URL and prefix](https://mauriciobenjamin700.github.io/tempest-react-sdk/en/http/#base-url-and-prefix).
|
|
598
|
+
|
|
596
599
|
### Response parsing with zod recipe
|
|
597
600
|
|
|
598
601
|
The HTTP client returns untyped JSON (`unknown`). `parseResponse` validates against a zod schema and gives you a `ZodError`-aware failure message tied to the request.
|
|
@@ -1751,20 +1754,24 @@ import {
|
|
|
1751
1754
|
cn,
|
|
1752
1755
|
formatCurrency,
|
|
1753
1756
|
formatDate,
|
|
1757
|
+
formatDateForInput,
|
|
1754
1758
|
formatDateTime,
|
|
1755
1759
|
formatPhone,
|
|
1756
1760
|
formatCPF,
|
|
1757
1761
|
formatPercent,
|
|
1762
|
+
percentOf,
|
|
1758
1763
|
storage,
|
|
1759
1764
|
} from "tempest-react-sdk";
|
|
1760
1765
|
|
|
1761
1766
|
cn("btn", isPrimary && "btn-primary", { "btn-disabled": disabled });
|
|
1762
1767
|
formatCurrency(1234.5, "BRL"); // "R$ 1.234,50"
|
|
1763
1768
|
formatDate("2026-05-17"); // "17/05/2026"
|
|
1769
|
+
formatDateForInput("2026-05-17T14:30Z"); // "2026-05-17" — the value <input type="date"> accepts
|
|
1764
1770
|
formatDateTime("2026-05-17T14:30Z"); // "17/05/2026 11:30"
|
|
1765
1771
|
formatPhone("11998765432"); // "(11) 99876-5432"
|
|
1766
1772
|
formatCPF("12345678909"); // "123.456.789-09"
|
|
1767
1773
|
formatPercent(0.1234, 1); // "12,3%"
|
|
1774
|
+
percentOf(3, 4); // 75 — and percentOf(3, 0) is 0, not NaN
|
|
1768
1775
|
|
|
1769
1776
|
storage.set("draft", { title: "..." });
|
|
1770
1777
|
const draft = storage.get<Draft>("draft");
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
const e=require("../
|
|
1
|
+
const e=require("../i18n/I18nProvider.cjs"),t=require("../query/QueryProvider.cjs"),n=require("../theme/ThemeProvider.cjs"),r=require("../error-boundary/ErrorBoundary.cjs");let i=require("react/jsx-runtime");function a({children:a,query:o,theme:s,i18n:c,errorBoundary:l}){let u=a;return c&&(u=(0,i.jsx)(e.I18nProvider,{...c,children:u})),s!==!1&&(u=(0,i.jsx)(n.ThemeProvider,{...s||{},children:u})),o!==!1&&(u=(0,i.jsx)(t.QueryProvider,{...o||{},children:u})),l&&(u=(0,i.jsx)(r.ErrorBoundary,{...l,children:u})),(0,i.jsx)(i.Fragment,{children:u})}exports.AppProviders=a;
|
|
2
2
|
//# sourceMappingURL=AppProviders.cjs.map
|
package/dist/app/AppProviders.js
CHANGED
|
@@ -1,18 +1,18 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import {
|
|
3
|
-
import {
|
|
1
|
+
import { I18nProvider as e } from "../i18n/I18nProvider.js";
|
|
2
|
+
import { QueryProvider as t } from "../query/QueryProvider.js";
|
|
3
|
+
import { ThemeProvider as n } from "../theme/ThemeProvider.js";
|
|
4
4
|
import { ErrorBoundary as r } from "../error-boundary/ErrorBoundary.js";
|
|
5
5
|
import { Fragment as i, jsx as a } from "react/jsx-runtime";
|
|
6
6
|
//#region src/app/AppProviders.tsx
|
|
7
7
|
function o({ children: o, query: s, theme: c, i18n: l, errorBoundary: u }) {
|
|
8
8
|
let d = o;
|
|
9
|
-
return l && (d = /* @__PURE__ */ a(
|
|
9
|
+
return l && (d = /* @__PURE__ */ a(e, {
|
|
10
10
|
...l,
|
|
11
11
|
children: d
|
|
12
|
-
})), c !== !1 && (d = /* @__PURE__ */ a(
|
|
12
|
+
})), c !== !1 && (d = /* @__PURE__ */ a(n, {
|
|
13
13
|
...c || {},
|
|
14
14
|
children: d
|
|
15
|
-
})), s !== !1 && (d = /* @__PURE__ */ a(
|
|
15
|
+
})), s !== !1 && (d = /* @__PURE__ */ a(t, {
|
|
16
16
|
...s || {},
|
|
17
17
|
children: d
|
|
18
18
|
})), u && (d = /* @__PURE__ */ a(r, {
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
function e(e){return Number.isFinite(e)?Math.min(1,Math.max(0,e)):1}function t(t={}){let{baseUrl:n=``,voices:r=1,maxSources:i=48}=t,a=e(t.volume??1),o=Math.max(1,Math.floor(r)),s=new Map,c=new WeakMap;function l(e){return!n||/^(https?:)?\/\//.test(e)||e.startsWith(`data:`)?e:`${n.replace(/\/$/,``)}/${e.replace(/^\//,``)}`}function u(e){for(let t of e.elements)t.pause(),t.removeAttribute(`src`),t.load()}function d(e){if(typeof Audio>`u`)return null;let t=l(e),n=s.get(t);if(n)return s.delete(t),s.set(t,n),n;let r={elements:Array.from({length:o},()=>{let e=new Audio(t);return e.preload=`auto`,e}),next:0};if(s.set(t,r),s.size>i){let e=s.keys().next();if(!e.done&&e.value!==t){let t=s.get(e.value);t&&u(t),s.delete(e.value)}}return r}return{play(t,n={}){let r=d(t);if(!r)return;let i=r.elements[r.next];r.next=(r.next+1)%r.elements.length;let o=e(n.volume??1);c.set(i,o),i.pause(),i.currentTime=0,i.volume=e(o*a),i.play().catch(()=>{})},preload(e){for(let t of Array.isArray(e)?e:[e])d(t)?.elements.forEach(e=>e.load())},setVolume(t){a=e(t);for(let t of s.values())for(let n of t.elements)n.paused||(n.volume=e((c.get(n)??1)*a))},stop(e){let t=e?[s.get(l(e))]:[...s.values()];for(let e of t)if(e)for(let t of e.elements)t.pause(),t.currentTime=0},dispose(){for(let e of s.values())u(e);s.clear()}}}exports.createSfxPool=t;
|
|
2
|
+
//# sourceMappingURL=sfx-pool.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"sfx-pool.cjs","names":[],"sources":["../../src/audio/sfx-pool.ts"],"sourcesContent":["/** Options for {@link createSfxPool}. */\nexport interface SfxPoolOptions {\n /**\n * Master volume, `0`–`1`, multiplied into every per-play volume. Default\n * `1`. Wire it to the app's sound setting so one value governs the lot.\n */\n volume?: number;\n /**\n * Prefix applied to sources that are not absolute URLs — typically Vite's\n * `import.meta.env.BASE_URL`, so a build served from a subpath resolves.\n * Default `\"\"`.\n */\n baseUrl?: string;\n /**\n * Elements kept per source. `1` (the default) restarts the clip on every\n * play, which is what a menu blip wants. Raise it to let a sound overlap\n * itself — a hit landing while the previous one is still ringing.\n */\n voices?: number;\n /**\n * Maximum number of distinct sources held. When exceeded, the least\n * recently played source is released. Default `48`.\n */\n maxSources?: number;\n}\n\n/** Per-play overrides. */\nexport interface PlaySfxOptions {\n /** Volume for this play, `0`–`1`, multiplied by the pool's master. Default `1`. */\n volume?: number;\n}\n\n/** Imperative handle over a pool of short sound effects. */\nexport interface SfxPool {\n /** Play a clip, allocating and caching its element on first use. */\n play: (src: string, options?: PlaySfxOptions) => void;\n /** Fetch clips ahead of the first play, so it is not silent while the file downloads. */\n preload: (src: string | string[]) => void;\n /** Set the master volume, applying it to anything already sounding. */\n setVolume: (volume: number) => void;\n /** Stop one source, or every source when called with no argument. */\n stop: (src?: string) => void;\n /** Release every element. Call on unmount. */\n dispose: () => void;\n}\n\n/** Clamp to the range `HTMLMediaElement.volume` accepts, rejecting `NaN`. */\nfunction clampVolume(value: number): number {\n if (!Number.isFinite(value)) return 1;\n return Math.min(1, Math.max(0, value));\n}\n\n/**\n * A pool of preallocated `<audio>` elements for short sound effects.\n *\n * `new Audio(src)` on every play allocates an element and re-enters the network\n * stack for a file the browser already has, which is the wrong shape for a\n * sound that fires dozens of times a minute — a UI blip, a hit, a pickup. The\n * pool allocates once per source and replays.\n *\n * This is deliberately not {@link createAudioPlayer}: that handle tracks a\n * single \"current\" clip with loop, sink routing and lifecycle callbacks, which\n * is what background music needs. Effects are the opposite case — many\n * sources, all short, fire-and-forget, and the only thing that matters is that\n * firing one is cheap.\n *\n * A blocked `play()` is swallowed. Browsers reject playback until the user has\n * interacted with the page, and a sound effect is by definition not worth\n * interrupting anything over; call {@link SfxPool.preload} after the first\n * interaction if you want the pool warm.\n *\n * @param options - Master volume, base URL, voices per source and pool size.\n * @returns The pool handle.\n *\n * @example\n * const sfx = createSfxPool({ volume: 0.6, baseUrl: import.meta.env.BASE_URL });\n * sfx.preload([\"sfx/select.mp3\", \"sfx/back.mp3\"]);\n *\n * <button onClick={() => sfx.play(\"sfx/select.mp3\")}>Confirmar</button>\n */\nexport function createSfxPool(options: SfxPoolOptions = {}): SfxPool {\n const { baseUrl = \"\", voices = 1, maxSources = 48 } = options;\n\n let master = clampVolume(options.volume ?? 1);\n const voiceCount = Math.max(1, Math.floor(voices));\n\n /**\n * Insertion-ordered by last play, so evicting the first key drops the\n * least recently used source.\n */\n const sources = new Map<string, { elements: HTMLAudioElement[]; next: number }>();\n\n /**\n * Per-play gain of whatever each element last played at.\n *\n * `setVolume` has to rescale live playback by the same factor it was\n * started with; assigning the master directly would yank a clip that\n * started at half volume up to full.\n */\n const gains = new WeakMap<HTMLAudioElement, number>();\n\n function resolve(src: string): string {\n if (!baseUrl || /^(https?:)?\\/\\//.test(src) || src.startsWith(\"data:\")) return src;\n return `${baseUrl.replace(/\\/$/, \"\")}/${src.replace(/^\\//, \"\")}`;\n }\n\n function release(entry: { elements: HTMLAudioElement[] }): void {\n for (const element of entry.elements) {\n element.pause();\n element.removeAttribute(\"src\");\n element.load();\n }\n }\n\n function acquire(src: string): { elements: HTMLAudioElement[]; next: number } | null {\n if (typeof Audio === \"undefined\") return null;\n\n const url = resolve(src);\n const existing = sources.get(url);\n if (existing) {\n // Re-insert so the map order stays \"least recently played first\".\n sources.delete(url);\n sources.set(url, existing);\n return existing;\n }\n\n const entry = {\n elements: Array.from({ length: voiceCount }, () => {\n const element = new Audio(url);\n element.preload = \"auto\";\n return element;\n }),\n next: 0,\n };\n sources.set(url, entry);\n\n if (sources.size > maxSources) {\n const oldest = sources.keys().next();\n if (!oldest.done && oldest.value !== url) {\n const evicted = sources.get(oldest.value);\n if (evicted) release(evicted);\n sources.delete(oldest.value);\n }\n }\n\n return entry;\n }\n\n return {\n play(src, playOptions = {}) {\n const entry = acquire(src);\n if (!entry) return;\n\n const element = entry.elements[entry.next];\n entry.next = (entry.next + 1) % entry.elements.length;\n\n const gain = clampVolume(playOptions.volume ?? 1);\n gains.set(element, gain);\n\n element.pause();\n element.currentTime = 0;\n element.volume = clampVolume(gain * master);\n void element.play().catch(() => {});\n },\n\n preload(src) {\n for (const one of Array.isArray(src) ? src : [src]) {\n acquire(one)?.elements.forEach((element) => element.load());\n }\n },\n\n setVolume(volume) {\n master = clampVolume(volume);\n for (const entry of sources.values()) {\n for (const element of entry.elements) {\n if (element.paused) continue;\n element.volume = clampVolume((gains.get(element) ?? 1) * master);\n }\n }\n },\n\n stop(src) {\n const targets = src ? [sources.get(resolve(src))] : [...sources.values()];\n for (const entry of targets) {\n if (!entry) continue;\n for (const element of entry.elements) {\n element.pause();\n element.currentTime = 0;\n }\n }\n },\n\n dispose() {\n for (const entry of sources.values()) release(entry);\n sources.clear();\n },\n };\n}\n"],"mappings":"AA+CA,SAAS,EAAY,EAAuB,CAExC,OADK,OAAO,SAAS,CAAK,EACnB,KAAK,IAAI,EAAG,KAAK,IAAI,EAAG,CAAK,CAAC,EADD,CAExC,CA8BA,SAAgB,EAAc,EAA0B,CAAC,EAAY,CACjE,GAAM,CAAE,UAAU,GAAI,SAAS,EAAG,aAAa,IAAO,EAElD,EAAS,EAAY,EAAQ,QAAU,CAAC,EACtC,EAAa,KAAK,IAAI,EAAG,KAAK,MAAM,CAAM,CAAC,EAM3C,EAAU,IAAI,IASd,EAAQ,IAAI,QAElB,SAAS,EAAQ,EAAqB,CAElC,MADI,CAAC,GAAW,kBAAkB,KAAK,CAAG,GAAK,EAAI,WAAW,OAAO,EAAU,EACxE,GAAG,EAAQ,QAAQ,MAAO,EAAE,EAAE,GAAG,EAAI,QAAQ,MAAO,EAAE,GACjE,CAEA,SAAS,EAAQ,EAA+C,CAC5D,IAAK,IAAM,KAAW,EAAM,SACxB,EAAQ,MAAM,EACd,EAAQ,gBAAgB,KAAK,EAC7B,EAAQ,KAAK,CAErB,CAEA,SAAS,EAAQ,EAAoE,CACjF,GAAI,OAAO,MAAU,IAAa,OAAO,KAEzC,IAAM,EAAM,EAAQ,CAAG,EACjB,EAAW,EAAQ,IAAI,CAAG,EAChC,GAAI,EAIA,OAFA,EAAQ,OAAO,CAAG,EAClB,EAAQ,IAAI,EAAK,CAAQ,EAClB,EAGX,IAAM,EAAQ,CACV,SAAU,MAAM,KAAK,CAAE,OAAQ,CAAW,MAAS,CAC/C,IAAM,EAAU,IAAI,MAAM,CAAG,EAE7B,MADA,GAAQ,QAAU,OACX,CACX,CAAC,EACD,KAAM,CACV,EAGA,GAFA,EAAQ,IAAI,EAAK,CAAK,EAElB,EAAQ,KAAO,EAAY,CAC3B,IAAM,EAAS,EAAQ,KAAK,CAAC,CAAC,KAAK,EACnC,GAAI,CAAC,EAAO,MAAQ,EAAO,QAAU,EAAK,CACtC,IAAM,EAAU,EAAQ,IAAI,EAAO,KAAK,EACpC,GAAS,EAAQ,CAAO,EAC5B,EAAQ,OAAO,EAAO,KAAK,CAC/B,CACJ,CAEA,OAAO,CACX,CAEA,MAAO,CACH,KAAK,EAAK,EAAc,CAAC,EAAG,CACxB,IAAM,EAAQ,EAAQ,CAAG,EACzB,GAAI,CAAC,EAAO,OAEZ,IAAM,EAAU,EAAM,SAAS,EAAM,MACrC,EAAM,MAAQ,EAAM,KAAO,GAAK,EAAM,SAAS,OAE/C,IAAM,EAAO,EAAY,EAAY,QAAU,CAAC,EAChD,EAAM,IAAI,EAAS,CAAI,EAEvB,EAAQ,MAAM,EACd,EAAQ,YAAc,EACtB,EAAQ,OAAS,EAAY,EAAO,CAAM,EAC1C,EAAa,KAAK,CAAC,CAAC,UAAY,CAAC,CAAC,CACtC,EAEA,QAAQ,EAAK,CACT,IAAK,IAAM,KAAO,MAAM,QAAQ,CAAG,EAAI,EAAM,CAAC,CAAG,EAC7C,EAAQ,CAAG,CAAC,EAAE,SAAS,QAAS,GAAY,EAAQ,KAAK,CAAC,CAElE,EAEA,UAAU,EAAQ,CACd,EAAS,EAAY,CAAM,EAC3B,IAAK,IAAM,KAAS,EAAQ,OAAO,EAC/B,IAAK,IAAM,KAAW,EAAM,SACpB,EAAQ,SACZ,EAAQ,OAAS,GAAa,EAAM,IAAI,CAAO,GAAK,GAAK,CAAM,EAG3E,EAEA,KAAK,EAAK,CACN,IAAM,EAAU,EAAM,CAAC,EAAQ,IAAI,EAAQ,CAAG,CAAC,CAAC,EAAI,CAAC,GAAG,EAAQ,OAAO,CAAC,EACxE,IAAK,IAAM,KAAS,EACX,KACL,IAAK,IAAM,KAAW,EAAM,SACxB,EAAQ,MAAM,EACd,EAAQ,YAAc,CAGlC,EAEA,SAAU,CACN,IAAK,IAAM,KAAS,EAAQ,OAAO,EAAG,EAAQ,CAAK,EACnD,EAAQ,MAAM,CAClB,CACJ,CACJ"}
|
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
//#region src/audio/sfx-pool.ts
|
|
2
|
+
function e(e) {
|
|
3
|
+
return Number.isFinite(e) ? Math.min(1, Math.max(0, e)) : 1;
|
|
4
|
+
}
|
|
5
|
+
function t(t = {}) {
|
|
6
|
+
let { baseUrl: n = "", voices: r = 1, maxSources: i = 48 } = t, a = e(t.volume ?? 1), o = Math.max(1, Math.floor(r)), s = /* @__PURE__ */ new Map(), c = /* @__PURE__ */ new WeakMap();
|
|
7
|
+
function l(e) {
|
|
8
|
+
return !n || /^(https?:)?\/\//.test(e) || e.startsWith("data:") ? e : `${n.replace(/\/$/, "")}/${e.replace(/^\//, "")}`;
|
|
9
|
+
}
|
|
10
|
+
function u(e) {
|
|
11
|
+
for (let t of e.elements) t.pause(), t.removeAttribute("src"), t.load();
|
|
12
|
+
}
|
|
13
|
+
function d(e) {
|
|
14
|
+
if (typeof Audio > "u") return null;
|
|
15
|
+
let t = l(e), n = s.get(t);
|
|
16
|
+
if (n) return s.delete(t), s.set(t, n), n;
|
|
17
|
+
let r = {
|
|
18
|
+
elements: Array.from({ length: o }, () => {
|
|
19
|
+
let e = new Audio(t);
|
|
20
|
+
return e.preload = "auto", e;
|
|
21
|
+
}),
|
|
22
|
+
next: 0
|
|
23
|
+
};
|
|
24
|
+
if (s.set(t, r), s.size > i) {
|
|
25
|
+
let e = s.keys().next();
|
|
26
|
+
if (!e.done && e.value !== t) {
|
|
27
|
+
let t = s.get(e.value);
|
|
28
|
+
t && u(t), s.delete(e.value);
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
return r;
|
|
32
|
+
}
|
|
33
|
+
return {
|
|
34
|
+
play(t, n = {}) {
|
|
35
|
+
let r = d(t);
|
|
36
|
+
if (!r) return;
|
|
37
|
+
let i = r.elements[r.next];
|
|
38
|
+
r.next = (r.next + 1) % r.elements.length;
|
|
39
|
+
let o = e(n.volume ?? 1);
|
|
40
|
+
c.set(i, o), i.pause(), i.currentTime = 0, i.volume = e(o * a), i.play().catch(() => {});
|
|
41
|
+
},
|
|
42
|
+
preload(e) {
|
|
43
|
+
for (let t of Array.isArray(e) ? e : [e]) d(t)?.elements.forEach((e) => e.load());
|
|
44
|
+
},
|
|
45
|
+
setVolume(t) {
|
|
46
|
+
a = e(t);
|
|
47
|
+
for (let t of s.values()) for (let n of t.elements) n.paused || (n.volume = e((c.get(n) ?? 1) * a));
|
|
48
|
+
},
|
|
49
|
+
stop(e) {
|
|
50
|
+
let t = e ? [s.get(l(e))] : [...s.values()];
|
|
51
|
+
for (let e of t) if (e) for (let t of e.elements) t.pause(), t.currentTime = 0;
|
|
52
|
+
},
|
|
53
|
+
dispose() {
|
|
54
|
+
for (let e of s.values()) u(e);
|
|
55
|
+
s.clear();
|
|
56
|
+
}
|
|
57
|
+
};
|
|
58
|
+
}
|
|
59
|
+
//#endregion
|
|
60
|
+
export { t as createSfxPool };
|
|
61
|
+
|
|
62
|
+
//# sourceMappingURL=sfx-pool.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"sfx-pool.js","names":[],"sources":["../../src/audio/sfx-pool.ts"],"sourcesContent":["/** Options for {@link createSfxPool}. */\nexport interface SfxPoolOptions {\n /**\n * Master volume, `0`–`1`, multiplied into every per-play volume. Default\n * `1`. Wire it to the app's sound setting so one value governs the lot.\n */\n volume?: number;\n /**\n * Prefix applied to sources that are not absolute URLs — typically Vite's\n * `import.meta.env.BASE_URL`, so a build served from a subpath resolves.\n * Default `\"\"`.\n */\n baseUrl?: string;\n /**\n * Elements kept per source. `1` (the default) restarts the clip on every\n * play, which is what a menu blip wants. Raise it to let a sound overlap\n * itself — a hit landing while the previous one is still ringing.\n */\n voices?: number;\n /**\n * Maximum number of distinct sources held. When exceeded, the least\n * recently played source is released. Default `48`.\n */\n maxSources?: number;\n}\n\n/** Per-play overrides. */\nexport interface PlaySfxOptions {\n /** Volume for this play, `0`–`1`, multiplied by the pool's master. Default `1`. */\n volume?: number;\n}\n\n/** Imperative handle over a pool of short sound effects. */\nexport interface SfxPool {\n /** Play a clip, allocating and caching its element on first use. */\n play: (src: string, options?: PlaySfxOptions) => void;\n /** Fetch clips ahead of the first play, so it is not silent while the file downloads. */\n preload: (src: string | string[]) => void;\n /** Set the master volume, applying it to anything already sounding. */\n setVolume: (volume: number) => void;\n /** Stop one source, or every source when called with no argument. */\n stop: (src?: string) => void;\n /** Release every element. Call on unmount. */\n dispose: () => void;\n}\n\n/** Clamp to the range `HTMLMediaElement.volume` accepts, rejecting `NaN`. */\nfunction clampVolume(value: number): number {\n if (!Number.isFinite(value)) return 1;\n return Math.min(1, Math.max(0, value));\n}\n\n/**\n * A pool of preallocated `<audio>` elements for short sound effects.\n *\n * `new Audio(src)` on every play allocates an element and re-enters the network\n * stack for a file the browser already has, which is the wrong shape for a\n * sound that fires dozens of times a minute — a UI blip, a hit, a pickup. The\n * pool allocates once per source and replays.\n *\n * This is deliberately not {@link createAudioPlayer}: that handle tracks a\n * single \"current\" clip with loop, sink routing and lifecycle callbacks, which\n * is what background music needs. Effects are the opposite case — many\n * sources, all short, fire-and-forget, and the only thing that matters is that\n * firing one is cheap.\n *\n * A blocked `play()` is swallowed. Browsers reject playback until the user has\n * interacted with the page, and a sound effect is by definition not worth\n * interrupting anything over; call {@link SfxPool.preload} after the first\n * interaction if you want the pool warm.\n *\n * @param options - Master volume, base URL, voices per source and pool size.\n * @returns The pool handle.\n *\n * @example\n * const sfx = createSfxPool({ volume: 0.6, baseUrl: import.meta.env.BASE_URL });\n * sfx.preload([\"sfx/select.mp3\", \"sfx/back.mp3\"]);\n *\n * <button onClick={() => sfx.play(\"sfx/select.mp3\")}>Confirmar</button>\n */\nexport function createSfxPool(options: SfxPoolOptions = {}): SfxPool {\n const { baseUrl = \"\", voices = 1, maxSources = 48 } = options;\n\n let master = clampVolume(options.volume ?? 1);\n const voiceCount = Math.max(1, Math.floor(voices));\n\n /**\n * Insertion-ordered by last play, so evicting the first key drops the\n * least recently used source.\n */\n const sources = new Map<string, { elements: HTMLAudioElement[]; next: number }>();\n\n /**\n * Per-play gain of whatever each element last played at.\n *\n * `setVolume` has to rescale live playback by the same factor it was\n * started with; assigning the master directly would yank a clip that\n * started at half volume up to full.\n */\n const gains = new WeakMap<HTMLAudioElement, number>();\n\n function resolve(src: string): string {\n if (!baseUrl || /^(https?:)?\\/\\//.test(src) || src.startsWith(\"data:\")) return src;\n return `${baseUrl.replace(/\\/$/, \"\")}/${src.replace(/^\\//, \"\")}`;\n }\n\n function release(entry: { elements: HTMLAudioElement[] }): void {\n for (const element of entry.elements) {\n element.pause();\n element.removeAttribute(\"src\");\n element.load();\n }\n }\n\n function acquire(src: string): { elements: HTMLAudioElement[]; next: number } | null {\n if (typeof Audio === \"undefined\") return null;\n\n const url = resolve(src);\n const existing = sources.get(url);\n if (existing) {\n // Re-insert so the map order stays \"least recently played first\".\n sources.delete(url);\n sources.set(url, existing);\n return existing;\n }\n\n const entry = {\n elements: Array.from({ length: voiceCount }, () => {\n const element = new Audio(url);\n element.preload = \"auto\";\n return element;\n }),\n next: 0,\n };\n sources.set(url, entry);\n\n if (sources.size > maxSources) {\n const oldest = sources.keys().next();\n if (!oldest.done && oldest.value !== url) {\n const evicted = sources.get(oldest.value);\n if (evicted) release(evicted);\n sources.delete(oldest.value);\n }\n }\n\n return entry;\n }\n\n return {\n play(src, playOptions = {}) {\n const entry = acquire(src);\n if (!entry) return;\n\n const element = entry.elements[entry.next];\n entry.next = (entry.next + 1) % entry.elements.length;\n\n const gain = clampVolume(playOptions.volume ?? 1);\n gains.set(element, gain);\n\n element.pause();\n element.currentTime = 0;\n element.volume = clampVolume(gain * master);\n void element.play().catch(() => {});\n },\n\n preload(src) {\n for (const one of Array.isArray(src) ? src : [src]) {\n acquire(one)?.elements.forEach((element) => element.load());\n }\n },\n\n setVolume(volume) {\n master = clampVolume(volume);\n for (const entry of sources.values()) {\n for (const element of entry.elements) {\n if (element.paused) continue;\n element.volume = clampVolume((gains.get(element) ?? 1) * master);\n }\n }\n },\n\n stop(src) {\n const targets = src ? [sources.get(resolve(src))] : [...sources.values()];\n for (const entry of targets) {\n if (!entry) continue;\n for (const element of entry.elements) {\n element.pause();\n element.currentTime = 0;\n }\n }\n },\n\n dispose() {\n for (const entry of sources.values()) release(entry);\n sources.clear();\n },\n };\n}\n"],"mappings":";AA+CA,SAAS,EAAY,GAAuB;CAExC,OADK,OAAO,SAAS,CAAK,IACnB,KAAK,IAAI,GAAG,KAAK,IAAI,GAAG,CAAK,CAAC,IADD;AAExC;AA8BA,SAAgB,EAAc,IAA0B,CAAC,GAAY;CACjE,IAAM,EAAE,aAAU,IAAI,YAAS,GAAG,gBAAa,OAAO,GAElD,IAAS,EAAY,EAAQ,UAAU,CAAC,GACtC,IAAa,KAAK,IAAI,GAAG,KAAK,MAAM,CAAM,CAAC,GAM3C,oBAAU,IAAI,IAA4D,GAS1E,oBAAQ,IAAI,QAAkC;CAEpD,SAAS,EAAQ,GAAqB;EAElC,OADI,CAAC,KAAW,kBAAkB,KAAK,CAAG,KAAK,EAAI,WAAW,OAAO,IAAU,IACxE,GAAG,EAAQ,QAAQ,OAAO,EAAE,EAAE,GAAG,EAAI,QAAQ,OAAO,EAAE;CACjE;CAEA,SAAS,EAAQ,GAA+C;EAC5D,KAAK,IAAM,KAAW,EAAM,UAGxB,AAFA,EAAQ,MAAM,GACd,EAAQ,gBAAgB,KAAK,GAC7B,EAAQ,KAAK;CAErB;CAEA,SAAS,EAAQ,GAAoE;EACjF,IAAI,OAAO,QAAU,KAAa,OAAO;EAEzC,IAAM,IAAM,EAAQ,CAAG,GACjB,IAAW,EAAQ,IAAI,CAAG;EAChC,IAAI,GAIA,OAFA,EAAQ,OAAO,CAAG,GAClB,EAAQ,IAAI,GAAK,CAAQ,GAClB;EAGX,IAAM,IAAQ;GACV,UAAU,MAAM,KAAK,EAAE,QAAQ,EAAW,SAAS;IAC/C,IAAM,IAAU,IAAI,MAAM,CAAG;IAE7B,OADA,EAAQ,UAAU,QACX;GACX,CAAC;GACD,MAAM;EACV;EAGA,IAFA,EAAQ,IAAI,GAAK,CAAK,GAElB,EAAQ,OAAO,GAAY;GAC3B,IAAM,IAAS,EAAQ,KAAK,CAAC,CAAC,KAAK;GACnC,IAAI,CAAC,EAAO,QAAQ,EAAO,UAAU,GAAK;IACtC,IAAM,IAAU,EAAQ,IAAI,EAAO,KAAK;IAExC,AADI,KAAS,EAAQ,CAAO,GAC5B,EAAQ,OAAO,EAAO,KAAK;GAC/B;EACJ;EAEA,OAAO;CACX;CAEA,OAAO;EACH,KAAK,GAAK,IAAc,CAAC,GAAG;GACxB,IAAM,IAAQ,EAAQ,CAAG;GACzB,IAAI,CAAC,GAAO;GAEZ,IAAM,IAAU,EAAM,SAAS,EAAM;GACrC,EAAM,QAAQ,EAAM,OAAO,KAAK,EAAM,SAAS;GAE/C,IAAM,IAAO,EAAY,EAAY,UAAU,CAAC;GAMhD,AALA,EAAM,IAAI,GAAS,CAAI,GAEvB,EAAQ,MAAM,GACd,EAAQ,cAAc,GACtB,EAAQ,SAAS,EAAY,IAAO,CAAM,GAC1C,EAAa,KAAK,CAAC,CAAC,YAAY,CAAC,CAAC;EACtC;EAEA,QAAQ,GAAK;GACT,KAAK,IAAM,KAAO,MAAM,QAAQ,CAAG,IAAI,IAAM,CAAC,CAAG,GAC7C,EAAQ,CAAG,CAAC,EAAE,SAAS,SAAS,MAAY,EAAQ,KAAK,CAAC;EAElE;EAEA,UAAU,GAAQ;GACd,IAAS,EAAY,CAAM;GAC3B,KAAK,IAAM,KAAS,EAAQ,OAAO,GAC/B,KAAK,IAAM,KAAW,EAAM,UACpB,EAAQ,WACZ,EAAQ,SAAS,GAAa,EAAM,IAAI,CAAO,KAAK,KAAK,CAAM;EAG3E;EAEA,KAAK,GAAK;GACN,IAAM,IAAU,IAAM,CAAC,EAAQ,IAAI,EAAQ,CAAG,CAAC,CAAC,IAAI,CAAC,GAAG,EAAQ,OAAO,CAAC;GACxE,KAAK,IAAM,KAAS,GACX,OACL,KAAK,IAAM,KAAW,EAAM,UAExB,AADA,EAAQ,MAAM,GACd,EAAQ,cAAc;EAGlC;EAEA,UAAU;GACN,KAAK,IAAM,KAAS,EAAQ,OAAO,GAAG,EAAQ,CAAK;GACnD,EAAQ,MAAM;EAClB;CACJ;AACJ"}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
const e=require("./sfx-pool.cjs");let t=require("react");function n(n={}){let{volume:r=1,baseUrl:i,voices:a,maxSources:o}=n,[s]=(0,t.useState)(()=>e.createSfxPool({baseUrl:i,voices:a,maxSources:o,volume:r}));return(0,t.useEffect)(()=>{s.setVolume(r)},[s,r]),(0,t.useEffect)(()=>()=>s.dispose(),[s]),s}exports.useSfxPool=n;
|
|
2
|
+
//# sourceMappingURL=use-sfx-pool.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"use-sfx-pool.cjs","names":[],"sources":["../../src/audio/use-sfx-pool.ts"],"sourcesContent":["import { useEffect, useState } from \"react\";\nimport { createSfxPool, type SfxPool, type SfxPoolOptions } from \"./sfx-pool\";\n\n/**\n * Component-scoped {@link createSfxPool}, with the lifecycle wired up.\n *\n * The pool is created once — through a lazy `useState` initializer, so no\n * element is allocated on a render that gets discarded — and disposed on\n * unmount, so its elements do not outlive the screen that owns them.\n *\n * `volume` is tracked separately: changing it calls `setVolume` on the existing\n * pool rather than rebuilding it, which would throw away every clip the user\n * has already downloaded — exactly the cost the pool exists to avoid.\n * `baseUrl`, `voices` and `maxSources` are read once, at creation.\n *\n * @param options - Passed through to {@link createSfxPool}.\n * @returns A stable pool handle.\n *\n * @example\n * const sfx = useSfxPool({ volume: settings.sfxVolume / 100, baseUrl: import.meta.env.BASE_URL });\n *\n * useEffect(() => { sfx.preload([\"sfx/select.mp3\", \"sfx/back.mp3\"]); }, [sfx]);\n *\n * <button onClick={() => sfx.play(\"sfx/select.mp3\")}>Confirmar</button>\n */\nexport function useSfxPool(options: SfxPoolOptions = {}): SfxPool {\n const { volume = 1, baseUrl, voices, maxSources } = options;\n\n const [pool] = useState(() => createSfxPool({ baseUrl, voices, maxSources, volume }));\n\n useEffect(() => {\n pool.setVolume(volume);\n }, [pool, volume]);\n\n useEffect(() => () => pool.dispose(), [pool]);\n\n return pool;\n}\n"],"mappings":"yDAyBA,SAAgB,EAAW,EAA0B,CAAC,EAAY,CAC9D,GAAM,CAAE,SAAS,EAAG,UAAS,SAAQ,cAAe,EAE9C,CAAC,IAAA,EAAQ,EAAA,SAAA,KAAe,EAAA,cAAc,CAAE,UAAS,SAAQ,aAAY,QAAO,CAAC,CAAC,EAQpF,OANA,EAAA,EAAA,UAAA,KAAgB,CACZ,EAAK,UAAU,CAAM,CACzB,EAAG,CAAC,EAAM,CAAM,CAAC,GAEjB,EAAA,EAAA,UAAA,SAAsB,EAAK,QAAQ,EAAG,CAAC,CAAI,CAAC,EAErC,CACX"}
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
import { createSfxPool as e } from "./sfx-pool.js";
|
|
2
|
+
import { useEffect as t, useState as n } from "react";
|
|
3
|
+
//#region src/audio/use-sfx-pool.ts
|
|
4
|
+
function r(r = {}) {
|
|
5
|
+
let { volume: i = 1, baseUrl: a, voices: o, maxSources: s } = r, [c] = n(() => e({
|
|
6
|
+
baseUrl: a,
|
|
7
|
+
voices: o,
|
|
8
|
+
maxSources: s,
|
|
9
|
+
volume: i
|
|
10
|
+
}));
|
|
11
|
+
return t(() => {
|
|
12
|
+
c.setVolume(i);
|
|
13
|
+
}, [c, i]), t(() => () => c.dispose(), [c]), c;
|
|
14
|
+
}
|
|
15
|
+
//#endregion
|
|
16
|
+
export { r as useSfxPool };
|
|
17
|
+
|
|
18
|
+
//# sourceMappingURL=use-sfx-pool.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"use-sfx-pool.js","names":[],"sources":["../../src/audio/use-sfx-pool.ts"],"sourcesContent":["import { useEffect, useState } from \"react\";\nimport { createSfxPool, type SfxPool, type SfxPoolOptions } from \"./sfx-pool\";\n\n/**\n * Component-scoped {@link createSfxPool}, with the lifecycle wired up.\n *\n * The pool is created once — through a lazy `useState` initializer, so no\n * element is allocated on a render that gets discarded — and disposed on\n * unmount, so its elements do not outlive the screen that owns them.\n *\n * `volume` is tracked separately: changing it calls `setVolume` on the existing\n * pool rather than rebuilding it, which would throw away every clip the user\n * has already downloaded — exactly the cost the pool exists to avoid.\n * `baseUrl`, `voices` and `maxSources` are read once, at creation.\n *\n * @param options - Passed through to {@link createSfxPool}.\n * @returns A stable pool handle.\n *\n * @example\n * const sfx = useSfxPool({ volume: settings.sfxVolume / 100, baseUrl: import.meta.env.BASE_URL });\n *\n * useEffect(() => { sfx.preload([\"sfx/select.mp3\", \"sfx/back.mp3\"]); }, [sfx]);\n *\n * <button onClick={() => sfx.play(\"sfx/select.mp3\")}>Confirmar</button>\n */\nexport function useSfxPool(options: SfxPoolOptions = {}): SfxPool {\n const { volume = 1, baseUrl, voices, maxSources } = options;\n\n const [pool] = useState(() => createSfxPool({ baseUrl, voices, maxSources, volume }));\n\n useEffect(() => {\n pool.setVolume(volume);\n }, [pool, volume]);\n\n useEffect(() => () => pool.dispose(), [pool]);\n\n return pool;\n}\n"],"mappings":";;;AAyBA,SAAgB,EAAW,IAA0B,CAAC,GAAY;CAC9D,IAAM,EAAE,YAAS,GAAG,YAAS,WAAQ,kBAAe,GAE9C,CAAC,KAAQ,QAAe,EAAc;EAAE;EAAS;EAAQ;EAAY;CAAO,CAAC,CAAC;CAQpF,OANA,QAAgB;EACZ,EAAK,UAAU,CAAM;CACzB,GAAG,CAAC,GAAM,CAAM,CAAC,GAEjB,cAAsB,EAAK,QAAQ,GAAG,CAAC,CAAI,CAAC,GAErC;AACX"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
const e=require("../http/api-client.cjs"),t=require("./create-auth-store.cjs"),n=require("./refresh-queue.cjs");function r(e){let t=e??{};return{token:t.access_token,refreshToken:t.refresh_token}}function i(i){let{baseURL:a,loginPath:
|
|
1
|
+
const e=require("../http/api-client.cjs"),t=require("./create-auth-store.cjs"),n=require("./refresh-queue.cjs");function r(e){let t=e??{};return{token:t.access_token,refreshToken:t.refresh_token}}function i(i){let{baseURL:a,prefix:o,loginPath:s=`/api/auth/login`,refreshPath:c=`/api/auth/refresh`,mePath:l,storeName:u=`tempest-auth`,storage:d=`local`,withCredentials:f=!1,fetcher:p,parseTokens:m=r,parseUser:h,refreshBody:g=e=>e?{refresh_token:e}:void 0,retry:_,redirectTo:v}=i,y=t.createAuthStore({name:u,storage:d}),b=`${u}-refresh`;function x(){return typeof window>`u`?null:d===`session`?window.sessionStorage:window.localStorage}function S(){return x()?.getItem(b)??null}function C(e){let t=x();t&&(e?t.setItem(b,e):t.removeItem(b))}let w=()=>y.getState(),T=()=>w().token,E=e.createApiClient({baseURL:a,prefix:o,withCredentials:f,fetcher:p});async function D(){if(!l)return w().user;let t=T(),n=await e.createApiClient({baseURL:a,prefix:o,withCredentials:f,fetcher:p,getToken:()=>t}).get(l);return w().setUser(n),n}async function O(e){let t=await E.post(s,{body:e}),{token:n,refreshToken:r}=m(t);w().setToken(n),C(r??null);let i=h?.(t);return i==null?D():(w().setUser(i),i)}function k(){w().logout(),C(null)}function A(){k(),v&&typeof window<`u`&&window.location.assign(v)}let j=n.createRefreshQueue(async()=>{let e=await E.post(c,{body:g(S())}),{token:t,refreshToken:n}=m(e);w().setToken(t),n&&C(n)});return{useAuthStore:y,api:e.createApiClient({baseURL:a,prefix:o,withCredentials:f,fetcher:p,getToken:T,refresh:j,retry:_,onUnauthorized:()=>A()}),login:O,logout:k,refresh:j,getToken:T}}exports.createTempestAuth=i;
|
|
2
2
|
//# sourceMappingURL=create-tempest-auth.cjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"create-tempest-auth.cjs","names":[],"sources":["../../src/auth/create-tempest-auth.ts"],"sourcesContent":["import { createApiClient } from \"../http\";\nimport type { ApiClient, RetryOptions } from \"../http\";\nimport { createAuthStore } from \"./create-auth-store\";\nimport type { AuthState } from \"./create-auth-store\";\nimport { createRefreshQueue } from \"./refresh-queue\";\n\n/** The token envelope returned by a Tempest FastAPI SDK login/refresh route. */\nexport interface TempestTokenResponse {\n /** The bearer access token. */\n access_token: string;\n /** Token type — always `\"bearer\"` for the SDK. */\n token_type?: string;\n /** Optional refresh token (when the API returns it in the body, not a cookie). */\n refresh_token?: string;\n}\n\nexport interface CreateTempestAuthOptions<TUser> {\n /** Base URL of the API. Required. */\n baseURL: string;\n /** Login route (`POST`). Default: `\"/api/auth/login\"`. */\n loginPath?: string;\n /** Refresh route (`POST`). Default: `\"/api/auth/refresh\"`. */\n refreshPath?: string;\n /** Optional current-user route (`GET`) called after login/refresh. */\n mePath?: string;\n /** Persist key for the store. Default: `\"tempest-auth\"`. */\n storeName?: string;\n /** Storage backend. Default: `\"local\"`. */\n storage?: \"local\" | \"session\";\n /** Send cookies (needed when the refresh token lives in an httpOnly cookie). */\n withCredentials?: boolean;\n /** Custom fetch implementation (testing / SSR). Defaults to `globalThis.fetch`. */\n fetcher?: typeof fetch;\n /**\n * Extract tokens from a login/refresh response. Default reads\n * `access_token` + `refresh_token`.\n */\n parseTokens?: (data: unknown) => { token: string; refreshToken?: string };\n /** Pull the user out of the login response, when the API embeds it. */\n parseUser?: (data: unknown) => TUser | null;\n /**\n * Build the refresh request body. Default sends `{ refresh_token }` when a\n * refresh token is stored, else `undefined` (cookie-based refresh).\n */\n refreshBody?: (refreshToken: string | null) => unknown;\n /**\n * Retry policy for `api`, forwarded to {@link createApiClient}. Off by\n * default; `true` enables the conservative built-in policy, which never\n * replays a write.\n */\n retry?: boolean | RetryOptions;\n /**\n * Where to send the browser when the session ends — a hard navigation via\n * `window.location.assign`, after the store is cleared.\n *\n * **Prefer leaving this unset.** `logout()` already clears the store, so a\n * `<RouteGuard when={isAuthenticated} redirectTo=\"/login\">` wrapped around\n * the protected area navigates on its own, which keeps the SPA alive and the\n * router history intact. Reach for this only when the expiry can happen\n * outside any guarded subtree and a full reload is acceptable.\n */\n redirectTo?: string;\n}\n\nexport interface TempestAuth<TUser, TCredentials> {\n /** The persisted Zustand auth store hook (compatible with `<AuthGuard>`). */\n useAuthStore: ReturnType<typeof createAuthStore<TUser>>;\n /** A `createApiClient` wired with bearer auth + 401 → refresh → retry. */\n api: ApiClient;\n /** Authenticate, store the session, and resolve the user (or null). */\n login: (credentials: TCredentials) => Promise<TUser | null>;\n /** Clear the session (and the stored refresh token). */\n logout: () => void;\n /** Refresh the access token (deduplicated across concurrent callers). */\n refresh: () => Promise<void>;\n /** The current access token, or null. */\n getToken: () => string | null;\n}\n\nfunction defaultParseTokens(data: unknown): { token: string; refreshToken?: string } {\n const d = (data ?? {}) as TempestTokenResponse;\n return { token: d.access_token, refreshToken: d.refresh_token };\n}\n\n/**\n * Turn-key auth preset wiring `createAuthStore` + `createRefreshQueue` +\n * `createApiClient` to the Tempest FastAPI SDK auth contract: login returns\n * `{ access_token, token_type }`, requests carry `Authorization: Bearer`, and a\n * `401` triggers a single deduplicated refresh + replay.\n *\n * The session is cleared whenever that path ends unauthorized anyway — the\n * refresh threw, or the replay came back `401` — so a refresh token that the\n * backend has revoked cannot leave the app holding a dead session. With\n * `redirectTo` set, the browser also leaves the page; without it, clearing the\n * store is enough for a `<RouteGuard>` to navigate on its own.\n *\n * @example\n * const auth = createTempestAuth<User, { email: string; password: string }>({\n * baseURL: import.meta.env.VITE_API_URL,\n * mePath: \"/api/auth/me\",\n * });\n *\n * await auth.login({ email, password }); // stores session, returns the user\n * const orders = await auth.api.get(\"/api/orders\"); // sends the bearer token\n * auth.logout();\n *\n * @param options - The auth configuration.\n * @returns The store hook, a wired API client, and login/logout/refresh helpers.\n */\nexport function createTempestAuth<TUser, TCredentials = { email: string; password: string }>(\n options: CreateTempestAuthOptions<TUser>,\n): TempestAuth<TUser, TCredentials> {\n const {\n baseURL,\n loginPath = \"/api/auth/login\",\n refreshPath = \"/api/auth/refresh\",\n mePath,\n storeName = \"tempest-auth\",\n storage = \"local\",\n withCredentials = false,\n fetcher,\n parseTokens = defaultParseTokens,\n parseUser,\n refreshBody = (rt) => (rt ? { refresh_token: rt } : undefined),\n retry,\n redirectTo,\n } = options;\n\n const useAuthStore = createAuthStore<TUser>({ name: storeName, storage });\n const refreshKey = `${storeName}-refresh`;\n\n function storageImpl(): Storage | null {\n if (typeof window === \"undefined\") return null;\n return storage === \"session\" ? window.sessionStorage : window.localStorage;\n }\n function readRefreshToken(): string | null {\n return storageImpl()?.getItem(refreshKey) ?? null;\n }\n function writeRefreshToken(token: string | null): void {\n const s = storageImpl();\n if (!s) return;\n if (token) s.setItem(refreshKey, token);\n else s.removeItem(refreshKey);\n }\n\n const state = (): AuthState<TUser> => useAuthStore.getState();\n const getToken = (): string | null => state().token;\n\n // Bare client (no auth/refresh) used for the login + refresh calls themselves.\n const bareApi = createApiClient({ baseURL, withCredentials, fetcher });\n\n async function fetchUser(): Promise<TUser | null> {\n if (!mePath) return state().user;\n const token = getToken();\n const user = await createApiClient({\n baseURL,\n withCredentials,\n fetcher,\n getToken: () => token,\n }).get<TUser>(mePath);\n state().setUser(user);\n return user;\n }\n\n async function login(credentials: TCredentials): Promise<TUser | null> {\n const data = await bareApi.post<unknown>(loginPath, { body: credentials });\n const { token, refreshToken } = parseTokens(data);\n state().setToken(token);\n writeRefreshToken(refreshToken ?? null);\n const embedded = parseUser?.(data);\n if (embedded != null) {\n state().setUser(embedded);\n return embedded;\n }\n return fetchUser();\n }\n\n function logout(): void {\n state().logout();\n writeRefreshToken(null);\n }\n\n /**\n * Clear the session and, when `redirectTo` is set, leave the page.\n *\n * Separate from `logout` so an explicit sign-out stays a pure state change:\n * a caller that already navigates itself would otherwise get a second,\n * competing navigation.\n */\n function endSession(): void {\n logout();\n if (redirectTo && typeof window !== \"undefined\") {\n window.location.assign(redirectTo);\n }\n }\n\n const refresh = createRefreshQueue(async () => {\n const data = await bareApi.post<unknown>(refreshPath, {\n body: refreshBody(readRefreshToken()),\n });\n const { token, refreshToken } = parseTokens(data);\n state().setToken(token);\n if (refreshToken) writeRefreshToken(refreshToken);\n });\n\n const api = createApiClient({\n baseURL,\n withCredentials,\n fetcher,\n getToken,\n refresh,\n retry,\n onUnauthorized: () => endSession(),\n });\n\n return { useAuthStore, api, login, logout, refresh, getToken };\n}\n"],"mappings":"gHA+EA,SAAS,EAAmB,EAAyD,CACjF,IAAM,EAAK,GAAQ,CAAC,EACpB,MAAO,CAAE,MAAO,EAAE,aAAc,aAAc,EAAE,aAAc,CAClE,CA2BA,SAAgB,EACZ,EACgC,CAChC,GAAM,CACF,UACA,YAAY,kBACZ,cAAc,oBACd,SACA,YAAY,eACZ,UAAU,QACV,kBAAkB,GAClB,UACA,cAAc,EACd,YACA,cAAe,GAAQ,EAAK,CAAE,cAAe,CAAG,EAAI,IAAA,GACpD,QACA,cACA,EAEE,EAAe,EAAA,gBAAuB,CAAE,KAAM,EAAW,SAAQ,CAAC,EAClE,EAAa,GAAG,EAAU,UAEhC,SAAS,GAA8B,CAEnC,OADI,OAAO,OAAW,IAAoB,KACnC,IAAY,UAAY,OAAO,eAAiB,OAAO,YAClE,CACA,SAAS,GAAkC,CACvC,OAAO,EAAY,CAAC,EAAE,QAAQ,CAAU,GAAK,IACjD,CACA,SAAS,EAAkB,EAA4B,CACnD,IAAM,EAAI,EAAY,EACjB,IACD,EAAO,EAAE,QAAQ,EAAY,CAAK,EACjC,EAAE,WAAW,CAAU,EAChC,CAEA,IAAM,MAAgC,EAAa,SAAS,EACtD,MAAgC,EAAM,CAAC,CAAC,MAGxC,EAAU,EAAA,gBAAgB,CAAE,UAAS,kBAAiB,SAAQ,CAAC,EAErE,eAAe,GAAmC,CAC9C,GAAI,CAAC,EAAQ,OAAO,EAAM,CAAC,CAAC,KAC5B,IAAM,EAAQ,EAAS,EACjB,EAAO,MAAM,EAAA,gBAAgB,CAC/B,UACA,kBACA,UACA,aAAgB,CACpB,CAAC,CAAC,CAAC,IAAW,CAAM,EAEpB,OADA,EAAM,CAAC,CAAC,QAAQ,CAAI,EACb,CACX,CAEA,eAAe,EAAM,EAAkD,CACnE,IAAM,EAAO,MAAM,EAAQ,KAAc,EAAW,CAAE,KAAM,CAAY,CAAC,EACnE,CAAE,QAAO,gBAAiB,EAAY,CAAI,EAChD,EAAM,CAAC,CAAC,SAAS,CAAK,EACtB,EAAkB,GAAgB,IAAI,EACtC,IAAM,EAAW,IAAY,CAAI,EAKjC,OAJI,GAAY,KAIT,EAAU,GAHb,EAAM,CAAC,CAAC,QAAQ,CAAQ,EACjB,EAGf,CAEA,SAAS,GAAe,CACpB,EAAM,CAAC,CAAC,OAAO,EACf,EAAkB,IAAI,CAC1B,CASA,SAAS,GAAmB,CACxB,EAAO,EACH,GAAc,OAAO,OAAW,KAChC,OAAO,SAAS,OAAO,CAAU,CAEzC,CAEA,IAAM,EAAU,EAAA,mBAAmB,SAAY,CAC3C,IAAM,EAAO,MAAM,EAAQ,KAAc,EAAa,CAClD,KAAM,EAAY,EAAiB,CAAC,CACxC,CAAC,EACK,CAAE,QAAO,gBAAiB,EAAY,CAAI,EAChD,EAAM,CAAC,CAAC,SAAS,CAAK,EAClB,GAAc,EAAkB,CAAY,CACpD,CAAC,EAYD,MAAO,CAAE,eAAc,IAVX,EAAA,gBAAgB,CACxB,UACA,kBACA,UACA,WACA,UACA,QACA,mBAAsB,EAAW,CACrC,CAEuB,EAAK,QAAO,SAAQ,UAAS,UAAS,CACjE"}
|
|
1
|
+
{"version":3,"file":"create-tempest-auth.cjs","names":[],"sources":["../../src/auth/create-tempest-auth.ts"],"sourcesContent":["import { createApiClient } from \"../http\";\nimport type { ApiClient, RetryOptions } from \"../http\";\nimport { createAuthStore } from \"./create-auth-store\";\nimport type { AuthState } from \"./create-auth-store\";\nimport { createRefreshQueue } from \"./refresh-queue\";\n\n/** The token envelope returned by a Tempest FastAPI SDK login/refresh route. */\nexport interface TempestTokenResponse {\n /** The bearer access token. */\n access_token: string;\n /** Token type — always `\"bearer\"` for the SDK. */\n token_type?: string;\n /** Optional refresh token (when the API returns it in the body, not a cookie). */\n refresh_token?: string;\n}\n\nexport interface CreateTempestAuthOptions<TUser> {\n /** Base URL of the API. Required. */\n baseURL: string;\n /**\n * Path segment the API is mounted under, such as `\"/api\"`, forwarded to\n * every client this preset builds — see the `prefix` option of\n * `createApiClient`.\n *\n * Safe to combine with the default paths below: the prefix is applied at\n * most once, so `\"/api/auth/login\"` under a `\"/api\"` prefix stays\n * `\"/api/auth/login\"`.\n */\n prefix?: string;\n /** Login route (`POST`). Default: `\"/api/auth/login\"`. */\n loginPath?: string;\n /** Refresh route (`POST`). Default: `\"/api/auth/refresh\"`. */\n refreshPath?: string;\n /** Optional current-user route (`GET`) called after login/refresh. */\n mePath?: string;\n /** Persist key for the store. Default: `\"tempest-auth\"`. */\n storeName?: string;\n /** Storage backend. Default: `\"local\"`. */\n storage?: \"local\" | \"session\";\n /** Send cookies (needed when the refresh token lives in an httpOnly cookie). */\n withCredentials?: boolean;\n /** Custom fetch implementation (testing / SSR). Defaults to `globalThis.fetch`. */\n fetcher?: typeof fetch;\n /**\n * Extract tokens from a login/refresh response. Default reads\n * `access_token` + `refresh_token`.\n */\n parseTokens?: (data: unknown) => { token: string; refreshToken?: string };\n /** Pull the user out of the login response, when the API embeds it. */\n parseUser?: (data: unknown) => TUser | null;\n /**\n * Build the refresh request body. Default sends `{ refresh_token }` when a\n * refresh token is stored, else `undefined` (cookie-based refresh).\n */\n refreshBody?: (refreshToken: string | null) => unknown;\n /**\n * Retry policy for `api`, forwarded to {@link createApiClient}. Off by\n * default; `true` enables the conservative built-in policy, which never\n * replays a write.\n */\n retry?: boolean | RetryOptions;\n /**\n * Where to send the browser when the session ends — a hard navigation via\n * `window.location.assign`, after the store is cleared.\n *\n * **Prefer leaving this unset.** `logout()` already clears the store, so a\n * `<RouteGuard when={isAuthenticated} redirectTo=\"/login\">` wrapped around\n * the protected area navigates on its own, which keeps the SPA alive and the\n * router history intact. Reach for this only when the expiry can happen\n * outside any guarded subtree and a full reload is acceptable.\n */\n redirectTo?: string;\n}\n\nexport interface TempestAuth<TUser, TCredentials> {\n /** The persisted Zustand auth store hook (compatible with `<AuthGuard>`). */\n useAuthStore: ReturnType<typeof createAuthStore<TUser>>;\n /** A `createApiClient` wired with bearer auth + 401 → refresh → retry. */\n api: ApiClient;\n /** Authenticate, store the session, and resolve the user (or null). */\n login: (credentials: TCredentials) => Promise<TUser | null>;\n /** Clear the session (and the stored refresh token). */\n logout: () => void;\n /** Refresh the access token (deduplicated across concurrent callers). */\n refresh: () => Promise<void>;\n /** The current access token, or null. */\n getToken: () => string | null;\n}\n\nfunction defaultParseTokens(data: unknown): { token: string; refreshToken?: string } {\n const d = (data ?? {}) as TempestTokenResponse;\n return { token: d.access_token, refreshToken: d.refresh_token };\n}\n\n/**\n * Turn-key auth preset wiring `createAuthStore` + `createRefreshQueue` +\n * `createApiClient` to the Tempest FastAPI SDK auth contract: login returns\n * `{ access_token, token_type }`, requests carry `Authorization: Bearer`, and a\n * `401` triggers a single deduplicated refresh + replay.\n *\n * The session is cleared whenever that path ends unauthorized anyway — the\n * refresh threw, or the replay came back `401` — so a refresh token that the\n * backend has revoked cannot leave the app holding a dead session. With\n * `redirectTo` set, the browser also leaves the page; without it, clearing the\n * store is enough for a `<RouteGuard>` to navigate on its own.\n *\n * @example\n * const auth = createTempestAuth<User, { email: string; password: string }>({\n * baseURL: import.meta.env.VITE_API_URL,\n * mePath: \"/api/auth/me\",\n * });\n *\n * await auth.login({ email, password }); // stores session, returns the user\n * const orders = await auth.api.get(\"/api/orders\"); // sends the bearer token\n * auth.logout();\n *\n * @param options - The auth configuration.\n * @returns The store hook, a wired API client, and login/logout/refresh helpers.\n */\nexport function createTempestAuth<TUser, TCredentials = { email: string; password: string }>(\n options: CreateTempestAuthOptions<TUser>,\n): TempestAuth<TUser, TCredentials> {\n const {\n baseURL,\n prefix,\n loginPath = \"/api/auth/login\",\n refreshPath = \"/api/auth/refresh\",\n mePath,\n storeName = \"tempest-auth\",\n storage = \"local\",\n withCredentials = false,\n fetcher,\n parseTokens = defaultParseTokens,\n parseUser,\n refreshBody = (rt) => (rt ? { refresh_token: rt } : undefined),\n retry,\n redirectTo,\n } = options;\n\n const useAuthStore = createAuthStore<TUser>({ name: storeName, storage });\n const refreshKey = `${storeName}-refresh`;\n\n function storageImpl(): Storage | null {\n if (typeof window === \"undefined\") return null;\n return storage === \"session\" ? window.sessionStorage : window.localStorage;\n }\n function readRefreshToken(): string | null {\n return storageImpl()?.getItem(refreshKey) ?? null;\n }\n function writeRefreshToken(token: string | null): void {\n const s = storageImpl();\n if (!s) return;\n if (token) s.setItem(refreshKey, token);\n else s.removeItem(refreshKey);\n }\n\n const state = (): AuthState<TUser> => useAuthStore.getState();\n const getToken = (): string | null => state().token;\n\n // Bare client (no auth/refresh) used for the login + refresh calls themselves.\n const bareApi = createApiClient({ baseURL, prefix, withCredentials, fetcher });\n\n async function fetchUser(): Promise<TUser | null> {\n if (!mePath) return state().user;\n const token = getToken();\n const user = await createApiClient({\n baseURL,\n prefix,\n withCredentials,\n fetcher,\n getToken: () => token,\n }).get<TUser>(mePath);\n state().setUser(user);\n return user;\n }\n\n async function login(credentials: TCredentials): Promise<TUser | null> {\n const data = await bareApi.post<unknown>(loginPath, { body: credentials });\n const { token, refreshToken } = parseTokens(data);\n state().setToken(token);\n writeRefreshToken(refreshToken ?? null);\n const embedded = parseUser?.(data);\n if (embedded != null) {\n state().setUser(embedded);\n return embedded;\n }\n return fetchUser();\n }\n\n function logout(): void {\n state().logout();\n writeRefreshToken(null);\n }\n\n /**\n * Clear the session and, when `redirectTo` is set, leave the page.\n *\n * Separate from `logout` so an explicit sign-out stays a pure state change:\n * a caller that already navigates itself would otherwise get a second,\n * competing navigation.\n */\n function endSession(): void {\n logout();\n if (redirectTo && typeof window !== \"undefined\") {\n window.location.assign(redirectTo);\n }\n }\n\n const refresh = createRefreshQueue(async () => {\n const data = await bareApi.post<unknown>(refreshPath, {\n body: refreshBody(readRefreshToken()),\n });\n const { token, refreshToken } = parseTokens(data);\n state().setToken(token);\n if (refreshToken) writeRefreshToken(refreshToken);\n });\n\n const api = createApiClient({\n baseURL,\n prefix,\n withCredentials,\n fetcher,\n getToken,\n refresh,\n retry,\n onUnauthorized: () => endSession(),\n });\n\n return { useAuthStore, api, login, logout, refresh, getToken };\n}\n"],"mappings":"gHAyFA,SAAS,EAAmB,EAAyD,CACjF,IAAM,EAAK,GAAQ,CAAC,EACpB,MAAO,CAAE,MAAO,EAAE,aAAc,aAAc,EAAE,aAAc,CAClE,CA2BA,SAAgB,EACZ,EACgC,CAChC,GAAM,CACF,UACA,SACA,YAAY,kBACZ,cAAc,oBACd,SACA,YAAY,eACZ,UAAU,QACV,kBAAkB,GAClB,UACA,cAAc,EACd,YACA,cAAe,GAAQ,EAAK,CAAE,cAAe,CAAG,EAAI,IAAA,GACpD,QACA,cACA,EAEE,EAAe,EAAA,gBAAuB,CAAE,KAAM,EAAW,SAAQ,CAAC,EAClE,EAAa,GAAG,EAAU,UAEhC,SAAS,GAA8B,CAEnC,OADI,OAAO,OAAW,IAAoB,KACnC,IAAY,UAAY,OAAO,eAAiB,OAAO,YAClE,CACA,SAAS,GAAkC,CACvC,OAAO,EAAY,CAAC,EAAE,QAAQ,CAAU,GAAK,IACjD,CACA,SAAS,EAAkB,EAA4B,CACnD,IAAM,EAAI,EAAY,EACjB,IACD,EAAO,EAAE,QAAQ,EAAY,CAAK,EACjC,EAAE,WAAW,CAAU,EAChC,CAEA,IAAM,MAAgC,EAAa,SAAS,EACtD,MAAgC,EAAM,CAAC,CAAC,MAGxC,EAAU,EAAA,gBAAgB,CAAE,UAAS,SAAQ,kBAAiB,SAAQ,CAAC,EAE7E,eAAe,GAAmC,CAC9C,GAAI,CAAC,EAAQ,OAAO,EAAM,CAAC,CAAC,KAC5B,IAAM,EAAQ,EAAS,EACjB,EAAO,MAAM,EAAA,gBAAgB,CAC/B,UACA,SACA,kBACA,UACA,aAAgB,CACpB,CAAC,CAAC,CAAC,IAAW,CAAM,EAEpB,OADA,EAAM,CAAC,CAAC,QAAQ,CAAI,EACb,CACX,CAEA,eAAe,EAAM,EAAkD,CACnE,IAAM,EAAO,MAAM,EAAQ,KAAc,EAAW,CAAE,KAAM,CAAY,CAAC,EACnE,CAAE,QAAO,gBAAiB,EAAY,CAAI,EAChD,EAAM,CAAC,CAAC,SAAS,CAAK,EACtB,EAAkB,GAAgB,IAAI,EACtC,IAAM,EAAW,IAAY,CAAI,EAKjC,OAJI,GAAY,KAIT,EAAU,GAHb,EAAM,CAAC,CAAC,QAAQ,CAAQ,EACjB,EAGf,CAEA,SAAS,GAAe,CACpB,EAAM,CAAC,CAAC,OAAO,EACf,EAAkB,IAAI,CAC1B,CASA,SAAS,GAAmB,CACxB,EAAO,EACH,GAAc,OAAO,OAAW,KAChC,OAAO,SAAS,OAAO,CAAU,CAEzC,CAEA,IAAM,EAAU,EAAA,mBAAmB,SAAY,CAC3C,IAAM,EAAO,MAAM,EAAQ,KAAc,EAAa,CAClD,KAAM,EAAY,EAAiB,CAAC,CACxC,CAAC,EACK,CAAE,QAAO,gBAAiB,EAAY,CAAI,EAChD,EAAM,CAAC,CAAC,SAAS,CAAK,EAClB,GAAc,EAAkB,CAAY,CACpD,CAAC,EAaD,MAAO,CAAE,eAAc,IAXX,EAAA,gBAAgB,CACxB,UACA,SACA,kBACA,UACA,WACA,UACA,QACA,mBAAsB,EAAW,CACrC,CAEuB,EAAK,QAAO,SAAQ,UAAS,UAAS,CACjE"}
|
|
@@ -10,66 +10,69 @@ function r(e) {
|
|
|
10
10
|
};
|
|
11
11
|
}
|
|
12
12
|
function i(i) {
|
|
13
|
-
let { baseURL: a,
|
|
14
|
-
name:
|
|
15
|
-
storage:
|
|
16
|
-
}),
|
|
17
|
-
function b() {
|
|
18
|
-
return typeof window > "u" ? null : u === "session" ? window.sessionStorage : window.localStorage;
|
|
19
|
-
}
|
|
13
|
+
let { baseURL: a, prefix: o, loginPath: s = "/api/auth/login", refreshPath: c = "/api/auth/refresh", mePath: l, storeName: u = "tempest-auth", storage: d = "local", withCredentials: f = !1, fetcher: p, parseTokens: m = r, parseUser: h, refreshBody: g = (e) => e ? { refresh_token: e } : void 0, retry: _, redirectTo: v } = i, y = t({
|
|
14
|
+
name: u,
|
|
15
|
+
storage: d
|
|
16
|
+
}), b = `${u}-refresh`;
|
|
20
17
|
function x() {
|
|
21
|
-
return
|
|
18
|
+
return typeof window > "u" ? null : d === "session" ? window.sessionStorage : window.localStorage;
|
|
19
|
+
}
|
|
20
|
+
function S() {
|
|
21
|
+
return x()?.getItem(b) ?? null;
|
|
22
22
|
}
|
|
23
|
-
function
|
|
24
|
-
let t =
|
|
25
|
-
t && (e ? t.setItem(
|
|
23
|
+
function C(e) {
|
|
24
|
+
let t = x();
|
|
25
|
+
t && (e ? t.setItem(b, e) : t.removeItem(b));
|
|
26
26
|
}
|
|
27
|
-
let
|
|
27
|
+
let w = () => y.getState(), T = () => w().token, E = e({
|
|
28
28
|
baseURL: a,
|
|
29
|
-
|
|
30
|
-
|
|
29
|
+
prefix: o,
|
|
30
|
+
withCredentials: f,
|
|
31
|
+
fetcher: p
|
|
31
32
|
});
|
|
32
|
-
async function
|
|
33
|
-
if (!
|
|
34
|
-
let t =
|
|
33
|
+
async function D() {
|
|
34
|
+
if (!l) return w().user;
|
|
35
|
+
let t = T(), n = await e({
|
|
35
36
|
baseURL: a,
|
|
36
|
-
|
|
37
|
-
|
|
37
|
+
prefix: o,
|
|
38
|
+
withCredentials: f,
|
|
39
|
+
fetcher: p,
|
|
38
40
|
getToken: () => t
|
|
39
|
-
}).get(
|
|
40
|
-
return
|
|
41
|
+
}).get(l);
|
|
42
|
+
return w().setUser(n), n;
|
|
41
43
|
}
|
|
42
|
-
async function
|
|
43
|
-
let t = await
|
|
44
|
-
|
|
45
|
-
let i =
|
|
46
|
-
return i == null ?
|
|
47
|
-
}
|
|
48
|
-
function O() {
|
|
49
|
-
C().logout(), S(null);
|
|
44
|
+
async function O(e) {
|
|
45
|
+
let t = await E.post(s, { body: e }), { token: n, refreshToken: r } = m(t);
|
|
46
|
+
w().setToken(n), C(r ?? null);
|
|
47
|
+
let i = h?.(t);
|
|
48
|
+
return i == null ? D() : (w().setUser(i), i);
|
|
50
49
|
}
|
|
51
50
|
function k() {
|
|
52
|
-
|
|
51
|
+
w().logout(), C(null);
|
|
52
|
+
}
|
|
53
|
+
function A() {
|
|
54
|
+
k(), v && typeof window < "u" && window.location.assign(v);
|
|
53
55
|
}
|
|
54
|
-
let
|
|
55
|
-
let e = await
|
|
56
|
-
|
|
56
|
+
let j = n(async () => {
|
|
57
|
+
let e = await E.post(c, { body: g(S()) }), { token: t, refreshToken: n } = m(e);
|
|
58
|
+
w().setToken(t), n && C(n);
|
|
57
59
|
});
|
|
58
60
|
return {
|
|
59
|
-
useAuthStore:
|
|
61
|
+
useAuthStore: y,
|
|
60
62
|
api: e({
|
|
61
63
|
baseURL: a,
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
64
|
+
prefix: o,
|
|
65
|
+
withCredentials: f,
|
|
66
|
+
fetcher: p,
|
|
67
|
+
getToken: T,
|
|
68
|
+
refresh: j,
|
|
69
|
+
retry: _,
|
|
70
|
+
onUnauthorized: () => A()
|
|
68
71
|
}),
|
|
69
|
-
login:
|
|
70
|
-
logout:
|
|
71
|
-
refresh:
|
|
72
|
-
getToken:
|
|
72
|
+
login: O,
|
|
73
|
+
logout: k,
|
|
74
|
+
refresh: j,
|
|
75
|
+
getToken: T
|
|
73
76
|
};
|
|
74
77
|
}
|
|
75
78
|
//#endregion
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"create-tempest-auth.js","names":[],"sources":["../../src/auth/create-tempest-auth.ts"],"sourcesContent":["import { createApiClient } from \"../http\";\nimport type { ApiClient, RetryOptions } from \"../http\";\nimport { createAuthStore } from \"./create-auth-store\";\nimport type { AuthState } from \"./create-auth-store\";\nimport { createRefreshQueue } from \"./refresh-queue\";\n\n/** The token envelope returned by a Tempest FastAPI SDK login/refresh route. */\nexport interface TempestTokenResponse {\n /** The bearer access token. */\n access_token: string;\n /** Token type — always `\"bearer\"` for the SDK. */\n token_type?: string;\n /** Optional refresh token (when the API returns it in the body, not a cookie). */\n refresh_token?: string;\n}\n\nexport interface CreateTempestAuthOptions<TUser> {\n /** Base URL of the API. Required. */\n baseURL: string;\n /** Login route (`POST`). Default: `\"/api/auth/login\"`. */\n loginPath?: string;\n /** Refresh route (`POST`). Default: `\"/api/auth/refresh\"`. */\n refreshPath?: string;\n /** Optional current-user route (`GET`) called after login/refresh. */\n mePath?: string;\n /** Persist key for the store. Default: `\"tempest-auth\"`. */\n storeName?: string;\n /** Storage backend. Default: `\"local\"`. */\n storage?: \"local\" | \"session\";\n /** Send cookies (needed when the refresh token lives in an httpOnly cookie). */\n withCredentials?: boolean;\n /** Custom fetch implementation (testing / SSR). Defaults to `globalThis.fetch`. */\n fetcher?: typeof fetch;\n /**\n * Extract tokens from a login/refresh response. Default reads\n * `access_token` + `refresh_token`.\n */\n parseTokens?: (data: unknown) => { token: string; refreshToken?: string };\n /** Pull the user out of the login response, when the API embeds it. */\n parseUser?: (data: unknown) => TUser | null;\n /**\n * Build the refresh request body. Default sends `{ refresh_token }` when a\n * refresh token is stored, else `undefined` (cookie-based refresh).\n */\n refreshBody?: (refreshToken: string | null) => unknown;\n /**\n * Retry policy for `api`, forwarded to {@link createApiClient}. Off by\n * default; `true` enables the conservative built-in policy, which never\n * replays a write.\n */\n retry?: boolean | RetryOptions;\n /**\n * Where to send the browser when the session ends — a hard navigation via\n * `window.location.assign`, after the store is cleared.\n *\n * **Prefer leaving this unset.** `logout()` already clears the store, so a\n * `<RouteGuard when={isAuthenticated} redirectTo=\"/login\">` wrapped around\n * the protected area navigates on its own, which keeps the SPA alive and the\n * router history intact. Reach for this only when the expiry can happen\n * outside any guarded subtree and a full reload is acceptable.\n */\n redirectTo?: string;\n}\n\nexport interface TempestAuth<TUser, TCredentials> {\n /** The persisted Zustand auth store hook (compatible with `<AuthGuard>`). */\n useAuthStore: ReturnType<typeof createAuthStore<TUser>>;\n /** A `createApiClient` wired with bearer auth + 401 → refresh → retry. */\n api: ApiClient;\n /** Authenticate, store the session, and resolve the user (or null). */\n login: (credentials: TCredentials) => Promise<TUser | null>;\n /** Clear the session (and the stored refresh token). */\n logout: () => void;\n /** Refresh the access token (deduplicated across concurrent callers). */\n refresh: () => Promise<void>;\n /** The current access token, or null. */\n getToken: () => string | null;\n}\n\nfunction defaultParseTokens(data: unknown): { token: string; refreshToken?: string } {\n const d = (data ?? {}) as TempestTokenResponse;\n return { token: d.access_token, refreshToken: d.refresh_token };\n}\n\n/**\n * Turn-key auth preset wiring `createAuthStore` + `createRefreshQueue` +\n * `createApiClient` to the Tempest FastAPI SDK auth contract: login returns\n * `{ access_token, token_type }`, requests carry `Authorization: Bearer`, and a\n * `401` triggers a single deduplicated refresh + replay.\n *\n * The session is cleared whenever that path ends unauthorized anyway — the\n * refresh threw, or the replay came back `401` — so a refresh token that the\n * backend has revoked cannot leave the app holding a dead session. With\n * `redirectTo` set, the browser also leaves the page; without it, clearing the\n * store is enough for a `<RouteGuard>` to navigate on its own.\n *\n * @example\n * const auth = createTempestAuth<User, { email: string; password: string }>({\n * baseURL: import.meta.env.VITE_API_URL,\n * mePath: \"/api/auth/me\",\n * });\n *\n * await auth.login({ email, password }); // stores session, returns the user\n * const orders = await auth.api.get(\"/api/orders\"); // sends the bearer token\n * auth.logout();\n *\n * @param options - The auth configuration.\n * @returns The store hook, a wired API client, and login/logout/refresh helpers.\n */\nexport function createTempestAuth<TUser, TCredentials = { email: string; password: string }>(\n options: CreateTempestAuthOptions<TUser>,\n): TempestAuth<TUser, TCredentials> {\n const {\n baseURL,\n loginPath = \"/api/auth/login\",\n refreshPath = \"/api/auth/refresh\",\n mePath,\n storeName = \"tempest-auth\",\n storage = \"local\",\n withCredentials = false,\n fetcher,\n parseTokens = defaultParseTokens,\n parseUser,\n refreshBody = (rt) => (rt ? { refresh_token: rt } : undefined),\n retry,\n redirectTo,\n } = options;\n\n const useAuthStore = createAuthStore<TUser>({ name: storeName, storage });\n const refreshKey = `${storeName}-refresh`;\n\n function storageImpl(): Storage | null {\n if (typeof window === \"undefined\") return null;\n return storage === \"session\" ? window.sessionStorage : window.localStorage;\n }\n function readRefreshToken(): string | null {\n return storageImpl()?.getItem(refreshKey) ?? null;\n }\n function writeRefreshToken(token: string | null): void {\n const s = storageImpl();\n if (!s) return;\n if (token) s.setItem(refreshKey, token);\n else s.removeItem(refreshKey);\n }\n\n const state = (): AuthState<TUser> => useAuthStore.getState();\n const getToken = (): string | null => state().token;\n\n // Bare client (no auth/refresh) used for the login + refresh calls themselves.\n const bareApi = createApiClient({ baseURL, withCredentials, fetcher });\n\n async function fetchUser(): Promise<TUser | null> {\n if (!mePath) return state().user;\n const token = getToken();\n const user = await createApiClient({\n baseURL,\n withCredentials,\n fetcher,\n getToken: () => token,\n }).get<TUser>(mePath);\n state().setUser(user);\n return user;\n }\n\n async function login(credentials: TCredentials): Promise<TUser | null> {\n const data = await bareApi.post<unknown>(loginPath, { body: credentials });\n const { token, refreshToken } = parseTokens(data);\n state().setToken(token);\n writeRefreshToken(refreshToken ?? null);\n const embedded = parseUser?.(data);\n if (embedded != null) {\n state().setUser(embedded);\n return embedded;\n }\n return fetchUser();\n }\n\n function logout(): void {\n state().logout();\n writeRefreshToken(null);\n }\n\n /**\n * Clear the session and, when `redirectTo` is set, leave the page.\n *\n * Separate from `logout` so an explicit sign-out stays a pure state change:\n * a caller that already navigates itself would otherwise get a second,\n * competing navigation.\n */\n function endSession(): void {\n logout();\n if (redirectTo && typeof window !== \"undefined\") {\n window.location.assign(redirectTo);\n }\n }\n\n const refresh = createRefreshQueue(async () => {\n const data = await bareApi.post<unknown>(refreshPath, {\n body: refreshBody(readRefreshToken()),\n });\n const { token, refreshToken } = parseTokens(data);\n state().setToken(token);\n if (refreshToken) writeRefreshToken(refreshToken);\n });\n\n const api = createApiClient({\n baseURL,\n withCredentials,\n fetcher,\n getToken,\n refresh,\n retry,\n onUnauthorized: () => endSession(),\n });\n\n return { useAuthStore, api, login, logout, refresh, getToken };\n}\n"],"mappings":";;;;AA+EA,SAAS,EAAmB,GAAyD;CACjF,IAAM,IAAK,KAAQ,CAAC;CACpB,OAAO;EAAE,OAAO,EAAE;EAAc,cAAc,EAAE;CAAc;AAClE;AA2BA,SAAgB,EACZ,GACgC;CAChC,IAAM,EACF,YACA,eAAY,mBACZ,iBAAc,qBACd,WACA,eAAY,gBACZ,aAAU,SACV,qBAAkB,IAClB,YACA,iBAAc,GACd,cACA,kBAAe,MAAQ,IAAK,EAAE,eAAe,EAAG,IAAI,KAAA,GACpD,UACA,kBACA,GAEE,IAAe,EAAuB;EAAE,MAAM;EAAW;CAAQ,CAAC,GAClE,IAAa,GAAG,EAAU;CAEhC,SAAS,IAA8B;EAEnC,OADI,OAAO,SAAW,MAAoB,OACnC,MAAY,YAAY,OAAO,iBAAiB,OAAO;CAClE;CACA,SAAS,IAAkC;EACvC,OAAO,EAAY,CAAC,EAAE,QAAQ,CAAU,KAAK;CACjD;CACA,SAAS,EAAkB,GAA4B;EACnD,IAAM,IAAI,EAAY;EACjB,MACD,IAAO,EAAE,QAAQ,GAAY,CAAK,IACjC,EAAE,WAAW,CAAU;CAChC;CAEA,IAAM,UAAgC,EAAa,SAAS,GACtD,UAAgC,EAAM,CAAC,CAAC,OAGxC,IAAU,EAAgB;EAAE;EAAS;EAAiB;CAAQ,CAAC;CAErE,eAAe,IAAmC;EAC9C,IAAI,CAAC,GAAQ,OAAO,EAAM,CAAC,CAAC;EAC5B,IAAM,IAAQ,EAAS,GACjB,IAAO,MAAM,EAAgB;GAC/B;GACA;GACA;GACA,gBAAgB;EACpB,CAAC,CAAC,CAAC,IAAW,CAAM;EAEpB,OADA,EAAM,CAAC,CAAC,QAAQ,CAAI,GACb;CACX;CAEA,eAAe,EAAM,GAAkD;EACnE,IAAM,IAAO,MAAM,EAAQ,KAAc,GAAW,EAAE,MAAM,EAAY,CAAC,GACnE,EAAE,UAAO,oBAAiB,EAAY,CAAI;EAEhD,AADA,EAAM,CAAC,CAAC,SAAS,CAAK,GACtB,EAAkB,KAAgB,IAAI;EACtC,IAAM,IAAW,IAAY,CAAI;EAKjC,OAJI,KAAY,OAIT,EAAU,KAHb,EAAM,CAAC,CAAC,QAAQ,CAAQ,GACjB;CAGf;CAEA,SAAS,IAAe;EAEpB,AADA,EAAM,CAAC,CAAC,OAAO,GACf,EAAkB,IAAI;CAC1B;CASA,SAAS,IAAmB;EAExB,AADA,EAAO,GACH,KAAc,OAAO,SAAW,OAChC,OAAO,SAAS,OAAO,CAAU;CAEzC;CAEA,IAAM,IAAU,EAAmB,YAAY;EAC3C,IAAM,IAAO,MAAM,EAAQ,KAAc,GAAa,EAClD,MAAM,EAAY,EAAiB,CAAC,EACxC,CAAC,GACK,EAAE,UAAO,oBAAiB,EAAY,CAAI;EAEhD,AADA,EAAM,CAAC,CAAC,SAAS,CAAK,GAClB,KAAc,EAAkB,CAAY;CACpD,CAAC;CAYD,OAAO;EAAE;EAAc,KAVX,EAAgB;GACxB;GACA;GACA;GACA;GACA;GACA;GACA,sBAAsB,EAAW;EACrC,CAEuB;EAAK;EAAO;EAAQ;EAAS;CAAS;AACjE"}
|
|
1
|
+
{"version":3,"file":"create-tempest-auth.js","names":[],"sources":["../../src/auth/create-tempest-auth.ts"],"sourcesContent":["import { createApiClient } from \"../http\";\nimport type { ApiClient, RetryOptions } from \"../http\";\nimport { createAuthStore } from \"./create-auth-store\";\nimport type { AuthState } from \"./create-auth-store\";\nimport { createRefreshQueue } from \"./refresh-queue\";\n\n/** The token envelope returned by a Tempest FastAPI SDK login/refresh route. */\nexport interface TempestTokenResponse {\n /** The bearer access token. */\n access_token: string;\n /** Token type — always `\"bearer\"` for the SDK. */\n token_type?: string;\n /** Optional refresh token (when the API returns it in the body, not a cookie). */\n refresh_token?: string;\n}\n\nexport interface CreateTempestAuthOptions<TUser> {\n /** Base URL of the API. Required. */\n baseURL: string;\n /**\n * Path segment the API is mounted under, such as `\"/api\"`, forwarded to\n * every client this preset builds — see the `prefix` option of\n * `createApiClient`.\n *\n * Safe to combine with the default paths below: the prefix is applied at\n * most once, so `\"/api/auth/login\"` under a `\"/api\"` prefix stays\n * `\"/api/auth/login\"`.\n */\n prefix?: string;\n /** Login route (`POST`). Default: `\"/api/auth/login\"`. */\n loginPath?: string;\n /** Refresh route (`POST`). Default: `\"/api/auth/refresh\"`. */\n refreshPath?: string;\n /** Optional current-user route (`GET`) called after login/refresh. */\n mePath?: string;\n /** Persist key for the store. Default: `\"tempest-auth\"`. */\n storeName?: string;\n /** Storage backend. Default: `\"local\"`. */\n storage?: \"local\" | \"session\";\n /** Send cookies (needed when the refresh token lives in an httpOnly cookie). */\n withCredentials?: boolean;\n /** Custom fetch implementation (testing / SSR). Defaults to `globalThis.fetch`. */\n fetcher?: typeof fetch;\n /**\n * Extract tokens from a login/refresh response. Default reads\n * `access_token` + `refresh_token`.\n */\n parseTokens?: (data: unknown) => { token: string; refreshToken?: string };\n /** Pull the user out of the login response, when the API embeds it. */\n parseUser?: (data: unknown) => TUser | null;\n /**\n * Build the refresh request body. Default sends `{ refresh_token }` when a\n * refresh token is stored, else `undefined` (cookie-based refresh).\n */\n refreshBody?: (refreshToken: string | null) => unknown;\n /**\n * Retry policy for `api`, forwarded to {@link createApiClient}. Off by\n * default; `true` enables the conservative built-in policy, which never\n * replays a write.\n */\n retry?: boolean | RetryOptions;\n /**\n * Where to send the browser when the session ends — a hard navigation via\n * `window.location.assign`, after the store is cleared.\n *\n * **Prefer leaving this unset.** `logout()` already clears the store, so a\n * `<RouteGuard when={isAuthenticated} redirectTo=\"/login\">` wrapped around\n * the protected area navigates on its own, which keeps the SPA alive and the\n * router history intact. Reach for this only when the expiry can happen\n * outside any guarded subtree and a full reload is acceptable.\n */\n redirectTo?: string;\n}\n\nexport interface TempestAuth<TUser, TCredentials> {\n /** The persisted Zustand auth store hook (compatible with `<AuthGuard>`). */\n useAuthStore: ReturnType<typeof createAuthStore<TUser>>;\n /** A `createApiClient` wired with bearer auth + 401 → refresh → retry. */\n api: ApiClient;\n /** Authenticate, store the session, and resolve the user (or null). */\n login: (credentials: TCredentials) => Promise<TUser | null>;\n /** Clear the session (and the stored refresh token). */\n logout: () => void;\n /** Refresh the access token (deduplicated across concurrent callers). */\n refresh: () => Promise<void>;\n /** The current access token, or null. */\n getToken: () => string | null;\n}\n\nfunction defaultParseTokens(data: unknown): { token: string; refreshToken?: string } {\n const d = (data ?? {}) as TempestTokenResponse;\n return { token: d.access_token, refreshToken: d.refresh_token };\n}\n\n/**\n * Turn-key auth preset wiring `createAuthStore` + `createRefreshQueue` +\n * `createApiClient` to the Tempest FastAPI SDK auth contract: login returns\n * `{ access_token, token_type }`, requests carry `Authorization: Bearer`, and a\n * `401` triggers a single deduplicated refresh + replay.\n *\n * The session is cleared whenever that path ends unauthorized anyway — the\n * refresh threw, or the replay came back `401` — so a refresh token that the\n * backend has revoked cannot leave the app holding a dead session. With\n * `redirectTo` set, the browser also leaves the page; without it, clearing the\n * store is enough for a `<RouteGuard>` to navigate on its own.\n *\n * @example\n * const auth = createTempestAuth<User, { email: string; password: string }>({\n * baseURL: import.meta.env.VITE_API_URL,\n * mePath: \"/api/auth/me\",\n * });\n *\n * await auth.login({ email, password }); // stores session, returns the user\n * const orders = await auth.api.get(\"/api/orders\"); // sends the bearer token\n * auth.logout();\n *\n * @param options - The auth configuration.\n * @returns The store hook, a wired API client, and login/logout/refresh helpers.\n */\nexport function createTempestAuth<TUser, TCredentials = { email: string; password: string }>(\n options: CreateTempestAuthOptions<TUser>,\n): TempestAuth<TUser, TCredentials> {\n const {\n baseURL,\n prefix,\n loginPath = \"/api/auth/login\",\n refreshPath = \"/api/auth/refresh\",\n mePath,\n storeName = \"tempest-auth\",\n storage = \"local\",\n withCredentials = false,\n fetcher,\n parseTokens = defaultParseTokens,\n parseUser,\n refreshBody = (rt) => (rt ? { refresh_token: rt } : undefined),\n retry,\n redirectTo,\n } = options;\n\n const useAuthStore = createAuthStore<TUser>({ name: storeName, storage });\n const refreshKey = `${storeName}-refresh`;\n\n function storageImpl(): Storage | null {\n if (typeof window === \"undefined\") return null;\n return storage === \"session\" ? window.sessionStorage : window.localStorage;\n }\n function readRefreshToken(): string | null {\n return storageImpl()?.getItem(refreshKey) ?? null;\n }\n function writeRefreshToken(token: string | null): void {\n const s = storageImpl();\n if (!s) return;\n if (token) s.setItem(refreshKey, token);\n else s.removeItem(refreshKey);\n }\n\n const state = (): AuthState<TUser> => useAuthStore.getState();\n const getToken = (): string | null => state().token;\n\n // Bare client (no auth/refresh) used for the login + refresh calls themselves.\n const bareApi = createApiClient({ baseURL, prefix, withCredentials, fetcher });\n\n async function fetchUser(): Promise<TUser | null> {\n if (!mePath) return state().user;\n const token = getToken();\n const user = await createApiClient({\n baseURL,\n prefix,\n withCredentials,\n fetcher,\n getToken: () => token,\n }).get<TUser>(mePath);\n state().setUser(user);\n return user;\n }\n\n async function login(credentials: TCredentials): Promise<TUser | null> {\n const data = await bareApi.post<unknown>(loginPath, { body: credentials });\n const { token, refreshToken } = parseTokens(data);\n state().setToken(token);\n writeRefreshToken(refreshToken ?? null);\n const embedded = parseUser?.(data);\n if (embedded != null) {\n state().setUser(embedded);\n return embedded;\n }\n return fetchUser();\n }\n\n function logout(): void {\n state().logout();\n writeRefreshToken(null);\n }\n\n /**\n * Clear the session and, when `redirectTo` is set, leave the page.\n *\n * Separate from `logout` so an explicit sign-out stays a pure state change:\n * a caller that already navigates itself would otherwise get a second,\n * competing navigation.\n */\n function endSession(): void {\n logout();\n if (redirectTo && typeof window !== \"undefined\") {\n window.location.assign(redirectTo);\n }\n }\n\n const refresh = createRefreshQueue(async () => {\n const data = await bareApi.post<unknown>(refreshPath, {\n body: refreshBody(readRefreshToken()),\n });\n const { token, refreshToken } = parseTokens(data);\n state().setToken(token);\n if (refreshToken) writeRefreshToken(refreshToken);\n });\n\n const api = createApiClient({\n baseURL,\n prefix,\n withCredentials,\n fetcher,\n getToken,\n refresh,\n retry,\n onUnauthorized: () => endSession(),\n });\n\n return { useAuthStore, api, login, logout, refresh, getToken };\n}\n"],"mappings":";;;;AAyFA,SAAS,EAAmB,GAAyD;CACjF,IAAM,IAAK,KAAQ,CAAC;CACpB,OAAO;EAAE,OAAO,EAAE;EAAc,cAAc,EAAE;CAAc;AAClE;AA2BA,SAAgB,EACZ,GACgC;CAChC,IAAM,EACF,YACA,WACA,eAAY,mBACZ,iBAAc,qBACd,WACA,eAAY,gBACZ,aAAU,SACV,qBAAkB,IAClB,YACA,iBAAc,GACd,cACA,kBAAe,MAAQ,IAAK,EAAE,eAAe,EAAG,IAAI,KAAA,GACpD,UACA,kBACA,GAEE,IAAe,EAAuB;EAAE,MAAM;EAAW;CAAQ,CAAC,GAClE,IAAa,GAAG,EAAU;CAEhC,SAAS,IAA8B;EAEnC,OADI,OAAO,SAAW,MAAoB,OACnC,MAAY,YAAY,OAAO,iBAAiB,OAAO;CAClE;CACA,SAAS,IAAkC;EACvC,OAAO,EAAY,CAAC,EAAE,QAAQ,CAAU,KAAK;CACjD;CACA,SAAS,EAAkB,GAA4B;EACnD,IAAM,IAAI,EAAY;EACjB,MACD,IAAO,EAAE,QAAQ,GAAY,CAAK,IACjC,EAAE,WAAW,CAAU;CAChC;CAEA,IAAM,UAAgC,EAAa,SAAS,GACtD,UAAgC,EAAM,CAAC,CAAC,OAGxC,IAAU,EAAgB;EAAE;EAAS;EAAQ;EAAiB;CAAQ,CAAC;CAE7E,eAAe,IAAmC;EAC9C,IAAI,CAAC,GAAQ,OAAO,EAAM,CAAC,CAAC;EAC5B,IAAM,IAAQ,EAAS,GACjB,IAAO,MAAM,EAAgB;GAC/B;GACA;GACA;GACA;GACA,gBAAgB;EACpB,CAAC,CAAC,CAAC,IAAW,CAAM;EAEpB,OADA,EAAM,CAAC,CAAC,QAAQ,CAAI,GACb;CACX;CAEA,eAAe,EAAM,GAAkD;EACnE,IAAM,IAAO,MAAM,EAAQ,KAAc,GAAW,EAAE,MAAM,EAAY,CAAC,GACnE,EAAE,UAAO,oBAAiB,EAAY,CAAI;EAEhD,AADA,EAAM,CAAC,CAAC,SAAS,CAAK,GACtB,EAAkB,KAAgB,IAAI;EACtC,IAAM,IAAW,IAAY,CAAI;EAKjC,OAJI,KAAY,OAIT,EAAU,KAHb,EAAM,CAAC,CAAC,QAAQ,CAAQ,GACjB;CAGf;CAEA,SAAS,IAAe;EAEpB,AADA,EAAM,CAAC,CAAC,OAAO,GACf,EAAkB,IAAI;CAC1B;CASA,SAAS,IAAmB;EAExB,AADA,EAAO,GACH,KAAc,OAAO,SAAW,OAChC,OAAO,SAAS,OAAO,CAAU;CAEzC;CAEA,IAAM,IAAU,EAAmB,YAAY;EAC3C,IAAM,IAAO,MAAM,EAAQ,KAAc,GAAa,EAClD,MAAM,EAAY,EAAiB,CAAC,EACxC,CAAC,GACK,EAAE,UAAO,oBAAiB,EAAY,CAAI;EAEhD,AADA,EAAM,CAAC,CAAC,SAAS,CAAK,GAClB,KAAc,EAAkB,CAAY;CACpD,CAAC;CAaD,OAAO;EAAE;EAAc,KAXX,EAAgB;GACxB;GACA;GACA;GACA;GACA;GACA;GACA;GACA,sBAAsB,EAAW;EACrC,CAEuB;EAAK;EAAO;EAAQ;EAAS;CAAS;AACjE"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
let e=require("react");function t(t,n={}){let{retries:r=3,initialDelay:i=400,reloadOnFinalFailure:a=!0}=n;async function o(e=1){try{return await t()}catch(t){if(e>=r)throw a&&typeof window<`u`&&window.location.reload(),t;return await new Promise(t=>setTimeout(t,i*2**(e-1))),o(e+1)}}return(0,e.lazy)(
|
|
1
|
+
let e=require("react");function t(t,n={}){let{retries:r=3,initialDelay:i=400,reloadOnFinalFailure:a=!0}=n;async function o(e=1){try{return await t()}catch(t){if(e>=r)throw a&&typeof window<`u`&&window.location.reload(),t;return await new Promise(t=>setTimeout(t,i*2**(e-1))),o(e+1)}}let s=null;function c(){return s||(s=o(),s.catch(()=>{s=null})),s}let l=(0,e.lazy)(c);return l.preload=c,l}exports.lazyWithRetry=t;
|
|
2
2
|
//# sourceMappingURL=lazy-with-retry.cjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"lazy-with-retry.cjs","names":[],"sources":["../../src/auth/lazy-with-retry.ts"],"sourcesContent":["import { lazy } from \"react\";\nimport type { ComponentType } from \"react\";\n\nexport interface LazyWithRetryOptions {\n /** Max attempts. Default: 3. */\n retries?: number;\n /** Initial delay (ms) before retrying. Default: 400. */\n initialDelay?: number;\n /**\n * Reload the page after every retry fails. Helps when the stale chunk\n * error is caused by an old `index.html` referencing deleted bundles.\n * Default: true.\n */\n reloadOnFinalFailure?: boolean;\n}\n\n/**\n * Wrap `React.lazy` with automatic retry
|
|
1
|
+
{"version":3,"file":"lazy-with-retry.cjs","names":[],"sources":["../../src/auth/lazy-with-retry.ts"],"sourcesContent":["import { lazy } from \"react\";\nimport type { ComponentType } from \"react\";\n\nexport interface LazyWithRetryOptions {\n /** Max attempts. Default: 3. */\n retries?: number;\n /** Initial delay (ms) before retrying. Default: 400. */\n initialDelay?: number;\n /**\n * Reload the page after every retry fails. Helps when the stale chunk\n * error is caused by an old `index.html` referencing deleted bundles.\n * Default: true.\n */\n reloadOnFinalFailure?: boolean;\n}\n\n/** A lazy component that can also be fetched ahead of being rendered. */\nexport type PreloadableLazy<T extends ComponentType<unknown>> = ReturnType<typeof lazy<T>> & {\n /**\n * Start fetching the chunk now, before anything renders it.\n *\n * Call it on the interaction that makes the route likely — hovering the\n * link, opening the menu that holds it, finishing the step before it — so\n * the chunk is warm by the time the user commits and the suspense fallback\n * never appears.\n *\n * Shares its work with the render path: whichever fires first performs the\n * single fetch and the other awaits the same promise. Safe to call\n * repeatedly.\n *\n * @returns The module, once loaded. Rejects when every retry failed; that\n * rejection is already handled internally, so a fire-and-forget call\n * never surfaces as an unhandled rejection.\n */\n preload: () => Promise<{ default: T }>;\n};\n\n/**\n * Wrap `React.lazy` with automatic retry and a `preload()` method.\n *\n * Common cause of failure: deployed-then-cached `index.html` references chunk\n * filenames that no longer exist. Retrying after a short delay typically picks\n * up the new bundle; a final `location.reload()` recovers from stale\n * `index.html`.\n *\n * @example\n * const Settings = lazyWithRetry(() => import(\"./Settings\"));\n *\n * // Warm the chunk when the route becomes likely, not when it is needed.\n * <a href=\"/settings\" onMouseEnter={() => void Settings.preload()}>Settings</a>\n */\nexport function lazyWithRetry<T extends ComponentType<unknown>>(\n factory: () => Promise<{ default: T }>,\n options: LazyWithRetryOptions = {},\n): PreloadableLazy<T> {\n const { retries = 3, initialDelay = 400, reloadOnFinalFailure = true } = options;\n\n async function load(attempt = 1): Promise<{ default: T }> {\n try {\n return await factory();\n } catch (error) {\n if (attempt >= retries) {\n if (reloadOnFinalFailure && typeof window !== \"undefined\") {\n window.location.reload();\n }\n throw error;\n }\n await new Promise((resolve) => setTimeout(resolve, initialDelay * 2 ** (attempt - 1)));\n return load(attempt + 1);\n }\n }\n\n let pending: Promise<{ default: T }> | null = null;\n\n /**\n * Run `load` at most once at a time, so preloading and rendering never\n * fetch the same chunk twice.\n *\n * The internal `catch` does two jobs: it clears the memo, so a component\n * that failed can be tried again once an error boundary resets, and it\n * marks the promise as handled, so a `preload()` nobody awaited does not\n * raise an unhandled rejection. Callers still get a promise that rejects.\n */\n function loadOnce(): Promise<{ default: T }> {\n if (!pending) {\n pending = load();\n pending.catch(() => {\n pending = null;\n });\n }\n return pending;\n }\n\n const component = lazy(loadOnce) as PreloadableLazy<T>;\n component.preload = loadOnce;\n return component;\n}\n"],"mappings":"uBAmDA,SAAgB,EACZ,EACA,EAAgC,CAAC,EACf,CAClB,GAAM,CAAE,UAAU,EAAG,eAAe,IAAK,uBAAuB,IAAS,EAEzE,eAAe,EAAK,EAAU,EAA4B,CACtD,GAAI,CACA,OAAO,MAAM,EAAQ,CACzB,OAAS,EAAO,CACZ,GAAI,GAAW,EAIX,MAHI,GAAwB,OAAO,OAAW,KAC1C,OAAO,SAAS,OAAO,EAErB,EAGV,OADA,MAAM,IAAI,QAAS,GAAY,WAAW,EAAS,EAAe,IAAM,EAAU,EAAE,CAAC,EAC9E,EAAK,EAAU,CAAC,CAC3B,CACJ,CAEA,IAAI,EAA0C,KAW9C,SAAS,GAAoC,CAOzC,OANK,IACD,EAAU,EAAK,EACf,EAAQ,UAAY,CAChB,EAAU,IACd,CAAC,GAEE,CACX,CAEA,IAAM,GAAA,EAAY,EAAA,KAAA,CAAK,CAAQ,EAE/B,MADA,GAAU,QAAU,EACb,CACX"}
|