tempest-react-sdk 0.21.0 → 0.22.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 +61 -61
- package/dist/sw.cjs +1 -1
- package/dist/sw.cjs.map +1 -1
- package/dist/sw.d.ts +26 -0
- package/dist/sw.js +90 -74
- package/dist/sw.js.map +1 -1
- package/dist/tempest-react-sdk.cjs +3 -3
- package/dist/tempest-react-sdk.cjs.map +1 -1
- package/dist/tempest-react-sdk.d.ts +289 -0
- package/dist/tempest-react-sdk.js +3362 -3198
- package/dist/tempest-react-sdk.js.map +1 -1
- package/package.json +2 -1
package/README.md
CHANGED
|
@@ -193,67 +193,67 @@ The styles ship hashed under the `tempest_` namespace — they do **not** collid
|
|
|
193
193
|
|
|
194
194
|
Every module is re-exported from the package root — `import { Button, useDebounce, createApiClient } from "tempest-react-sdk"` always works.
|
|
195
195
|
|
|
196
|
-
| Module | Exports
|
|
197
|
-
| ------------------------------------------------------------------------------------------------- |
|
|
198
|
-
| `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`
|
|
199
|
-
| `hooks` | `useDebounce`, `usePagination`, `useClientFilter`, `useMediaQuery`, `useOnline`, `useDocumentVisibility`, `useIntersectionObserver`, `useResizeObserver`, `useClipboard`, `useKeyboardShortcut`, `useBeforeInstallPrompt`, `useIdle`, `useGeolocation`, `useScrollLock`, `useFocusTrap`, `useStableCallback`, `useDeepMemo`, `useObjectUrl`
|
|
200
|
-
| `http` | `createApiClient`, `parseResponse`, `uploadWithProgress`, `retry`, `generateIdempotencyKey`, `usePoll`, types: `ApiClient`, `ApiClientConfig`, `ApiError`, `RequestOptions`, `RetryOptions`, `UploadProgressEvent`, `UploadWithProgressOptions`, `UsePollOptions`, `UsePollResult`
|
|
201
|
-
| `auth` _(peer: `zustand`)_ | `createAuthStore`, `AuthGuard`, `decodeJWT`, `isJWTExpired`, `lazyWithRetry`, `createRefreshQueue`, types: `AuthState`, `CreateAuthStoreOptions`, `AuthGuardProps`, `DecodedJWT`, `LazyWithRetryOptions`
|
|
202
|
-
| `query` _(peer: `@tanstack/react-query`)_ | `QueryProvider`, `createQueryKeys`, `STALE_TIME`, `CACHE_TIME`, `REFETCH_TIME`
|
|
203
|
-
| `router` _(dep: `react-router-dom`)_ | `defineRoutes`, `AppRouter`, `RouteGuard`, + re-exports (`Link`, `NavLink`, `Outlet`, `Navigate`, `useNavigate`, `useParams`, `useSearchParams`, `useLocation`, `useMatch`, `useRouteError`, `redirect`, `BrowserRouter`/`HashRouter`/`MemoryRouter`/`Routes`/`Route`), types: `TempestRouteObject`, `RouterKind`, `AppRouterProps`, `RouteGuardProps`
|
|
204
|
-
| `store` _(dep: `zustand`)_ | `createStore`, `createSelectors`, types: `CreateStoreOptions`, `CreateStorePersistOptions`, `WithSelectors`
|
|
205
|
-
| `app` | `AppProviders` (composes `ErrorBoundary` → `QueryProvider` → `ThemeProvider` → `I18nProvider`), type: `AppProvidersProps`
|
|
206
|
-
| `vite` _(subpath `tempest-react-sdk/vite`)_ | `createViteConfig`, `tempestPwaManifest` (emits `precache-manifest.json` for offline precache), `tempestPwaIcons` (generates the PNG icon set from one SVG via `sharp`), `tempestPwaDevSw` (serves the SW under `npm run dev`), `tempestPwaIcons({ appleSplash })` (Apple splash screens), types: `CreateViteConfigOptions`, `ProxyEntry`, `TempestViteConfig`, `TempestPwaManifestOptions`, `TempestPwaIconsOptions`, `TempestPwaDevSwOptions`, `AppleSplashSpec`, `TempestVitePlugin`
|
|
207
|
-
| `forms` _(peer: `zod`, `react-hook-form`)_ | `validateForm`, `zodResolver`, `useZodForm`, `validateCPF`, `validateCNPJ`, `formatCEP`, `formatCNPJ`, `unmask`, `CPFInput`, `CNPJInput`, `PhoneInput`, `CEPInput`, `MoneyInput`, `useViaCEP`
|
|
208
|
-
| `sse` | `createEventStream`, `useEventStream`
|
|
209
|
-
| `ws` | `createWebSocket`, `useWebSocket`
|
|
210
|
-
| `geo` _(opt. peer `leaflet`)_ | `haversineKm`, `pathLengthKm`, `bearingDeg`, `estimateTravel`, `createOSRMBackend`, `boundingBox`, `projectMercator`, `fitProjection`, `createPositionTracker`, `usePositionTracker`, `TrajectoryMap` — tile-free SVG map + trajectory tracking (no external/paid API; Leaflet is an opt-in, lazy-loaded tile layer for self-hosted tiles), types: `Coordinate`, `TrackPoint`, `TravelEstimate`, `TravelMode`, `GeoBounds`, `RoutingBackend`
|
|
211
|
-
| `br` _(subpath `tempest-react-sdk/br`)_ | `BrazilMap`, `BrazilStateMap`, `BrazilStateCitySelect`, `listStates`, `getState`, `citiesByUf`, `statesByRegion`, `ufChoices`, `cityChoices`, `isValidUf`, `normalizeUf`, `isValidCity`, `loadBrUfGeoJson`, `loadStateMunicipalities`, types `UF`, `BrRegion`, `BrazilState` — clickable 27-UF SVG map + per-state municipality submaps (bundled simplified IBGE GeoJSON, lazy per UF) + states/cities dataset, no external API; mirrors the FastAPI SDK `utils/locations`
|
|
212
|
-
| `push` | `WebPushClient`, `WebPushUnsupportedError`, `WebPushPermissionDeniedError`, `usePushSubscription`, `urlBase64ToUint8Array`, `isPushSupported`
|
|
213
|
-
| `sw` _(also subpath `tempest-react-sdk/sw`)_ | `registerServiceWorker
|
|
214
|
-
| `charts` _(subpath `tempest-react-sdk/charts`, opt. peer `recharts`)_ | `AreaChart`, `BarChart`, `LineChart`, `PieChart`, `RadarChart`, `DEFAULT_CHART_COLORS` — themed recharts wrappers (recharts externalized; install it only if you use charts)
|
|
215
|
-
| `audio` | `createAudioPlayer`, `playAudio`, `stopAudio`, `useAudio`
|
|
216
|
-
| `offline` _(peer: `dexie`)_ | `createOfflineStore`, `createOfflineSync` (outbox + delta-pull + watermark engine), types: `OfflineStore`, `OfflineStoreConfig`, `ListOptions`, `OfflineSync`, `OfflineSyncConfig`, `OutboxEntry`, `PullPage`, `SyncRunSummary`, `SyncTrigger`, `WatermarkStore`
|
|
217
|
-
| `error-boundary` | `ErrorBoundary`, `useErrorHandler`, types: `ErrorBoundaryProps`, `ErrorBoundaryRenderProps`
|
|
218
|
-
| `theme` | `ThemeProvider`, `useTheme`, `getInitialTheme`, `themeInitScript`, types: `ThemeMode`, `ResolvedTheme`
|
|
219
|
-
| `i18n` | `createI18n`, `I18nProvider`, `useI18n`, `useTranslate`, types: `Catalog`, `Messages`, `I18n`, `InterpolationValues`
|
|
220
|
-
| `logger` | `createLogger`, `consoleSink`, types: `Logger`, `LogEntry`, `LogLevel`, `LoggerSink`
|
|
221
|
-
| `telemetry` | `TelemetryProvider`, `useTelemetry`, `consoleTelemetryAdapter`, `createSentryTelemetryAdapter`, `createPostHogTelemetryAdapter`, types: `TelemetryAdapter`, `TelemetryEvent`, `TelemetryUser`, `CreateSentryTelemetryAdapterOptions`, `SentryLike`, `CreatePostHogTelemetryAdapterOptions`, `PostHogLike`
|
|
222
|
-
| `feature-flags` | `FeatureFlagsProvider`, `useFeatureFlag`, `useFlagValue`, `createInMemoryFlags`, `createGrowthBookFeatureFlagsAdapter`, `createLaunchDarklyFeatureFlagsAdapter`, types: `FeatureFlagsAdapter`, `FlagValue`, `GrowthBookLike`, `LDClientLike`
|
|
223
|
-
| `share` | `share`, `isShareSupported`, types: `SharePayload`, `ShareResult`
|
|
224
|
-
| `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` |
|
|
225
|
-
| generic components | display (`CopyButton`, `RelativeTime`, `Money`, `TruncateText`, `VisuallyHidden`), headless (`Portal`, `ClickOutside`, `ConditionalWrapper`, `For`, `ErrorText`), media/content (`Image`, `DataList`, `DescriptionList`)
|
|
226
|
-
| Module | Exports
|
|
227
|
-
| ------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
|
|
228
|
-
| `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`
|
|
229
|
-
| `hooks` | `useDebounce`, `usePagination`, `useClientFilter`, `useMediaQuery`, `useOnline`, `useDocumentVisibility`, `useIntersectionObserver`, `useResizeObserver`, `useClipboard`, `useKeyboardShortcut`, `useBeforeInstallPrompt`, `useIdle`, `useGeolocation`, `useScrollLock`, `useFocusTrap`, `useStableCallback`, `useDeepMemo`, `useObjectUrl`
|
|
230
|
-
| `http` | `createApiClient`, `parseResponse`, `uploadWithProgress`, `retry`, `generateIdempotencyKey`, `usePoll`, types: `ApiClient`, `ApiClientConfig`, `ApiError`, `RequestOptions`, `RetryOptions`, `UploadProgressEvent`, `UploadWithProgressOptions`, `UsePollOptions`, `UsePollResult`
|
|
231
|
-
| `auth` _(peer: `zustand`)_ | `createAuthStore`, `AuthGuard`, `decodeJWT`, `isJWTExpired`, `lazyWithRetry`, `createRefreshQueue`, types: `AuthState`, `CreateAuthStoreOptions`, `AuthGuardProps`, `DecodedJWT`, `LazyWithRetryOptions`
|
|
232
|
-
| `query` _(peer: `@tanstack/react-query`)_ | `QueryProvider`, `createQueryKeys`, `STALE_TIME`, `CACHE_TIME`, `REFETCH_TIME`
|
|
233
|
-
| `router` _(dep: `react-router-dom`)_ | `defineRoutes`, `AppRouter`, `RouteGuard`, + re-exports (`Link`, `NavLink`, `Outlet`, `Navigate`, `useNavigate`, `useParams`, `useSearchParams`, `useLocation`, `useMatch`, `useRouteError`, `redirect`, `BrowserRouter`/`HashRouter`/`MemoryRouter`/`Routes`/`Route`), types: `TempestRouteObject`, `RouterKind`, `AppRouterProps`, `RouteGuardProps`
|
|
234
|
-
| `store` _(dep: `zustand`)_ | `createStore`, `createSelectors`, types: `CreateStoreOptions`, `CreateStorePersistOptions`, `WithSelectors`
|
|
235
|
-
| `app` | `AppProviders` (composes `ErrorBoundary` → `QueryProvider` → `ThemeProvider` → `I18nProvider`), type: `AppProvidersProps`
|
|
236
|
-
| `vite` _(subpath `tempest-react-sdk/vite`)_ | `createViteConfig`, `tempestPwaManifest` (emits `precache-manifest.json` for offline precache), `tempestPwaIcons` (generates the PNG icon set from one SVG via `sharp`), `tempestPwaDevSw` (serves the SW under `npm run dev`), `tempestPwaIcons({ appleSplash })` (Apple splash screens), types: `CreateViteConfigOptions`, `ProxyEntry`, `TempestViteConfig`, `TempestPwaManifestOptions`, `TempestPwaIconsOptions`, `TempestPwaDevSwOptions`, `AppleSplashSpec`, `TempestVitePlugin`
|
|
237
|
-
| `forms` _(peer: `zod`, `react-hook-form`)_ | `validateForm`, `zodResolver`, `useZodForm`, `validateCPF`, `validateCNPJ`, `formatCEP`, `formatCNPJ`, `unmask`, `CPFInput`, `CNPJInput`, `PhoneInput`, `CEPInput`, `MoneyInput`, `useViaCEP`
|
|
238
|
-
| `sse` | `createEventStream`, `useEventStream`
|
|
239
|
-
| `ws` | `createWebSocket`, `useWebSocket`
|
|
240
|
-
| `geo` _(opt. peer `leaflet`)_ | `haversineKm`, `pathLengthKm`, `bearingDeg`, `estimateTravel`, `createOSRMBackend`, `boundingBox`, `projectMercator`, `fitProjection`, `createPositionTracker`, `usePositionTracker`, `TrajectoryMap` — tile-free SVG map + trajectory tracking (no external/paid API; Leaflet is an opt-in, lazy-loaded tile layer for self-hosted tiles), types: `Coordinate`, `TrackPoint`, `TravelEstimate`, `TravelMode`, `GeoBounds`, `RoutingBackend`
|
|
241
|
-
| `br` _(subpath `tempest-react-sdk/br`)_ | `BrazilMap`, `BrazilStateMap`, `BrazilStateCitySelect`, `listStates`, `getState`, `citiesByUf`, `statesByRegion`, `ufChoices`, `cityChoices`, `isValidUf`, `normalizeUf`, `isValidCity`, `loadBrUfGeoJson`, `loadStateMunicipalities`, types `UF`, `BrRegion`, `BrazilState` — clickable 27-UF SVG map + per-state municipality submaps (bundled simplified IBGE GeoJSON, lazy per UF) + states/cities dataset, no external API; mirrors the FastAPI SDK `utils/locations`
|
|
242
|
-
| `push` | `WebPushClient`, `WebPushUnsupportedError`, `WebPushPermissionDeniedError`, `usePushSubscription`, `urlBase64ToUint8Array`, `isPushSupported`
|
|
243
|
-
| `sw` _(also subpath `tempest-react-sdk/sw`)_ | `registerServiceWorker
|
|
244
|
-
| `editor` _(subpath `tempest-react-sdk/editor`, opt. peers `@tiptap/react`+`@tiptap/starter-kit`)_ | `RichTextEditor` — themed tiptap v3 rich-text editor with toolbar (tiptap externalized; install it only if you use the editor)
|
|
245
|
-
| `vision` _(subpath `tempest-react-sdk/vision`, opt. peer `onnxruntime-web`)_ | `Classifier`, `Detector`, `Segmenter` + results/labels/preprocess — on-device ONNX vision inference, vendored from `@mauriciobenjamin700/ort-vision-sdk-web` (onnxruntime-web externalized; install it only if you use vision). Plus browser capture primitives: `useCameraStream` (rear-camera `getUserMedia` + classified errors + `retry()`), `computeImageLuminance`/`isLuminanceAcceptable`/`LowLuminanceError`/`LUMINANCE_SAMPLE_MAX_EDGE` (BT.709 brightness), `useLiveLuminance` (live rAF sampling)
|
|
246
|
-
| `audio` | `createAudioPlayer`, `playAudio`, `stopAudio`, `useAudio`
|
|
247
|
-
| `offline` _(peer: `dexie`)_ | `createOfflineStore`, `createOfflineSync` (outbox + delta-pull + watermark engine), types: `OfflineStore`, `OfflineStoreConfig`, `ListOptions`, `OfflineSync`, `OfflineSyncConfig`, `OutboxEntry`, `PullPage`, `SyncRunSummary`, `SyncTrigger`, `WatermarkStore`
|
|
248
|
-
| `error-boundary` | `ErrorBoundary`, `useErrorHandler`, types: `ErrorBoundaryProps`, `ErrorBoundaryRenderProps`
|
|
249
|
-
| `theme` | `ThemeProvider`, `useTheme`, `getInitialTheme`, `themeInitScript`, types: `ThemeMode`, `ResolvedTheme`
|
|
250
|
-
| `i18n` | `createI18n`, `I18nProvider`, `useI18n`, `useTranslate`, types: `Catalog`, `Messages`, `I18n`, `InterpolationValues`
|
|
251
|
-
| `logger` | `createLogger`, `consoleSink`, types: `Logger`, `LogEntry`, `LogLevel`, `LoggerSink`
|
|
252
|
-
| `telemetry` | `TelemetryProvider`, `useTelemetry`, `consoleTelemetryAdapter`, `createSentryTelemetryAdapter`, `createPostHogTelemetryAdapter`, types: `TelemetryAdapter`, `TelemetryEvent`, `TelemetryUser`, `CreateSentryTelemetryAdapterOptions`, `SentryLike`, `CreatePostHogTelemetryAdapterOptions`, `PostHogLike`
|
|
253
|
-
| `feature-flags` | `FeatureFlagsProvider`, `useFeatureFlag`, `useFlagValue`, `createInMemoryFlags`, `createGrowthBookFeatureFlagsAdapter`, `createLaunchDarklyFeatureFlagsAdapter`, types: `FeatureFlagsAdapter`, `FlagValue`, `GrowthBookLike`, `LDClientLike`
|
|
254
|
-
| `share` | `share`, `isShareSupported`, types: `SharePayload`, `ShareResult`
|
|
255
|
-
| `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` |
|
|
256
|
-
| generic components | display (`CopyButton`, `RelativeTime`, `Money`, `TruncateText`, `VisuallyHidden`), headless (`Portal`, `ClickOutside`, `ConditionalWrapper`, `For`, `ErrorText`), media/content (`Image`, `DataList`, `DescriptionList`)
|
|
196
|
+
| Module | Exports |
|
|
197
|
+
| ------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
|
|
198
|
+
| `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` |
|
|
199
|
+
| `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), PWA env helpers `isIOS`/`isAndroid`/`isAndroidWithoutPromptApi`/`isStandalone`/`buildOpenInChromeIntent`, type `BeforeInstallPromptEvent` |
|
|
200
|
+
| `http` | `createApiClient`, `parseResponse`, `uploadWithProgress`, `retry`, `generateIdempotencyKey`, `usePoll`, types: `ApiClient`, `ApiClientConfig`, `ApiError`, `RequestOptions`, `RetryOptions`, `UploadProgressEvent`, `UploadWithProgressOptions`, `UsePollOptions`, `UsePollResult` |
|
|
201
|
+
| `auth` _(peer: `zustand`)_ | `createAuthStore`, `AuthGuard`, `decodeJWT`, `isJWTExpired`, `lazyWithRetry`, `createRefreshQueue`, types: `AuthState`, `CreateAuthStoreOptions`, `AuthGuardProps`, `DecodedJWT`, `LazyWithRetryOptions` |
|
|
202
|
+
| `query` _(peer: `@tanstack/react-query`)_ | `QueryProvider`, `createQueryKeys`, `STALE_TIME`, `CACHE_TIME`, `REFETCH_TIME` |
|
|
203
|
+
| `router` _(dep: `react-router-dom`)_ | `defineRoutes`, `AppRouter`, `RouteGuard`, + re-exports (`Link`, `NavLink`, `Outlet`, `Navigate`, `useNavigate`, `useParams`, `useSearchParams`, `useLocation`, `useMatch`, `useRouteError`, `redirect`, `BrowserRouter`/`HashRouter`/`MemoryRouter`/`Routes`/`Route`), types: `TempestRouteObject`, `RouterKind`, `AppRouterProps`, `RouteGuardProps` |
|
|
204
|
+
| `store` _(dep: `zustand`)_ | `createStore`, `createSelectors`, types: `CreateStoreOptions`, `CreateStorePersistOptions`, `WithSelectors` |
|
|
205
|
+
| `app` | `AppProviders` (composes `ErrorBoundary` → `QueryProvider` → `ThemeProvider` → `I18nProvider`), type: `AppProvidersProps` |
|
|
206
|
+
| `vite` _(subpath `tempest-react-sdk/vite`)_ | `createViteConfig`, `tempestPwaManifest` (emits `precache-manifest.json` for offline precache), `tempestPwaIcons` (generates the PNG icon set from one SVG via `sharp`), `tempestPwaDevSw` (serves the SW under `npm run dev`), `tempestPwaIcons({ appleSplash })` (Apple splash screens), types: `CreateViteConfigOptions`, `ProxyEntry`, `TempestViteConfig`, `TempestPwaManifestOptions`, `TempestPwaIconsOptions`, `TempestPwaDevSwOptions`, `AppleSplashSpec`, `TempestVitePlugin` |
|
|
207
|
+
| `forms` _(peer: `zod`, `react-hook-form`)_ | `validateForm`, `zodResolver`, `useZodForm`, `validateCPF`, `validateCNPJ`, `formatCEP`, `formatCNPJ`, `unmask`, `CPFInput`, `CNPJInput`, `PhoneInput`, `CEPInput`, `MoneyInput`, `useViaCEP` |
|
|
208
|
+
| `sse` | `createEventStream`, `useEventStream` |
|
|
209
|
+
| `ws` | `createWebSocket`, `useWebSocket` |
|
|
210
|
+
| `geo` _(opt. peer `leaflet`)_ | `haversineKm`, `pathLengthKm`, `bearingDeg`, `estimateTravel`, `createOSRMBackend`, `boundingBox`, `projectMercator`, `fitProjection`, `createPositionTracker`, `usePositionTracker`, `TrajectoryMap` — tile-free SVG map + trajectory tracking (no external/paid API; Leaflet is an opt-in, lazy-loaded tile layer for self-hosted tiles), types: `Coordinate`, `TrackPoint`, `TravelEstimate`, `TravelMode`, `GeoBounds`, `RoutingBackend` |
|
|
211
|
+
| `br` _(subpath `tempest-react-sdk/br`)_ | `BrazilMap`, `BrazilStateMap`, `BrazilStateCitySelect`, `listStates`, `getState`, `citiesByUf`, `statesByRegion`, `ufChoices`, `cityChoices`, `isValidUf`, `normalizeUf`, `isValidCity`, `loadBrUfGeoJson`, `loadStateMunicipalities`, types `UF`, `BrRegion`, `BrazilState` — clickable 27-UF SVG map + per-state municipality submaps (bundled simplified IBGE GeoJSON, lazy per UF) + states/cities dataset, no external API; mirrors the FastAPI SDK `utils/locations` |
|
|
212
|
+
| `push` | `WebPushClient`, `WebPushUnsupportedError`, `WebPushPermissionDeniedError`, `usePushSubscription`, `urlBase64ToUint8Array`, `isPushSupported` |
|
|
213
|
+
| `sw` _(also subpath `tempest-react-sdk/sw`)_ | `registerServiceWorker` (opt-in `autoUpdate` poll + reload, no `vite-plugin-pwa`), `skipWaiting`, `unregisterAllServiceWorkers`, `installPushHandler`, `installNotificationClickHandler`, `installSkipWaitingListener`, `installPrecache` (app-shell offline), `installRuntimeCache` (per-route caching, incl. `rangeRequests`), `createPartialResponse` (206 range slicing), `installBackgroundSync` (offline mutation queue) — the React-free `tempest-react-sdk/sw` subpath is ideal for bundling into your own `sw.ts` |
|
|
214
|
+
| `charts` _(subpath `tempest-react-sdk/charts`, opt. peer `recharts`)_ | `AreaChart`, `BarChart`, `LineChart`, `PieChart`, `RadarChart`, `DEFAULT_CHART_COLORS` — themed recharts wrappers (recharts externalized; install it only if you use charts) |
|
|
215
|
+
| `audio` | `createAudioPlayer`, `playAudio`, `stopAudio`, `useAudio` |
|
|
216
|
+
| `offline` _(peer: `dexie`)_ | `createOfflineStore`, `createOfflineSync` (outbox + delta-pull + watermark engine), types: `OfflineStore`, `OfflineStoreConfig`, `ListOptions`, `OfflineSync`, `OfflineSyncConfig`, `OutboxEntry`, `PullPage`, `SyncRunSummary`, `SyncTrigger`, `WatermarkStore` |
|
|
217
|
+
| `error-boundary` | `ErrorBoundary`, `useErrorHandler`, types: `ErrorBoundaryProps`, `ErrorBoundaryRenderProps` |
|
|
218
|
+
| `theme` | `ThemeProvider`, `useTheme`, `getInitialTheme`, `themeInitScript`, types: `ThemeMode`, `ResolvedTheme` |
|
|
219
|
+
| `i18n` | `createI18n`, `I18nProvider`, `useI18n`, `useTranslate`, types: `Catalog`, `Messages`, `I18n`, `InterpolationValues` |
|
|
220
|
+
| `logger` | `createLogger`, `consoleSink`, types: `Logger`, `LogEntry`, `LogLevel`, `LoggerSink` |
|
|
221
|
+
| `telemetry` | `TelemetryProvider`, `useTelemetry`, `consoleTelemetryAdapter`, `createSentryTelemetryAdapter`, `createPostHogTelemetryAdapter`, types: `TelemetryAdapter`, `TelemetryEvent`, `TelemetryUser`, `CreateSentryTelemetryAdapterOptions`, `SentryLike`, `CreatePostHogTelemetryAdapterOptions`, `PostHogLike` |
|
|
222
|
+
| `feature-flags` | `FeatureFlagsProvider`, `useFeatureFlag`, `useFlagValue`, `createInMemoryFlags`, `createGrowthBookFeatureFlagsAdapter`, `createLaunchDarklyFeatureFlagsAdapter`, types: `FeatureFlagsAdapter`, `FlagValue`, `GrowthBookLike`, `LDClientLike` |
|
|
223
|
+
| `share` | `share`, `isShareSupported`, `shareOrDownloadBlob` (Web Share file → download fallback), types: `SharePayload`, `ShareResult`, `ShareOrDownloadOptions` |
|
|
224
|
+
| `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`) |
|
|
225
|
+
| generic components | display (`CopyButton`, `RelativeTime`, `Money`, `TruncateText`, `VisuallyHidden`), headless (`Portal`, `ClickOutside`, `ConditionalWrapper`, `For`, `ErrorText`), media/content (`Image`, `DataList`, `DescriptionList`) |
|
|
226
|
+
| Module | Exports |
|
|
227
|
+
| ------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
|
|
228
|
+
| `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` |
|
|
229
|
+
| `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), PWA env helpers `isIOS`/`isAndroid`/`isAndroidWithoutPromptApi`/`isStandalone`/`buildOpenInChromeIntent`, type `BeforeInstallPromptEvent` |
|
|
230
|
+
| `http` | `createApiClient`, `parseResponse`, `uploadWithProgress`, `retry`, `generateIdempotencyKey`, `usePoll`, types: `ApiClient`, `ApiClientConfig`, `ApiError`, `RequestOptions`, `RetryOptions`, `UploadProgressEvent`, `UploadWithProgressOptions`, `UsePollOptions`, `UsePollResult` |
|
|
231
|
+
| `auth` _(peer: `zustand`)_ | `createAuthStore`, `AuthGuard`, `decodeJWT`, `isJWTExpired`, `lazyWithRetry`, `createRefreshQueue`, types: `AuthState`, `CreateAuthStoreOptions`, `AuthGuardProps`, `DecodedJWT`, `LazyWithRetryOptions` |
|
|
232
|
+
| `query` _(peer: `@tanstack/react-query`)_ | `QueryProvider`, `createQueryKeys`, `STALE_TIME`, `CACHE_TIME`, `REFETCH_TIME` |
|
|
233
|
+
| `router` _(dep: `react-router-dom`)_ | `defineRoutes`, `AppRouter`, `RouteGuard`, + re-exports (`Link`, `NavLink`, `Outlet`, `Navigate`, `useNavigate`, `useParams`, `useSearchParams`, `useLocation`, `useMatch`, `useRouteError`, `redirect`, `BrowserRouter`/`HashRouter`/`MemoryRouter`/`Routes`/`Route`), types: `TempestRouteObject`, `RouterKind`, `AppRouterProps`, `RouteGuardProps` |
|
|
234
|
+
| `store` _(dep: `zustand`)_ | `createStore`, `createSelectors`, types: `CreateStoreOptions`, `CreateStorePersistOptions`, `WithSelectors` |
|
|
235
|
+
| `app` | `AppProviders` (composes `ErrorBoundary` → `QueryProvider` → `ThemeProvider` → `I18nProvider`), type: `AppProvidersProps` |
|
|
236
|
+
| `vite` _(subpath `tempest-react-sdk/vite`)_ | `createViteConfig`, `tempestPwaManifest` (emits `precache-manifest.json` for offline precache), `tempestPwaIcons` (generates the PNG icon set from one SVG via `sharp`), `tempestPwaDevSw` (serves the SW under `npm run dev`), `tempestPwaIcons({ appleSplash })` (Apple splash screens), types: `CreateViteConfigOptions`, `ProxyEntry`, `TempestViteConfig`, `TempestPwaManifestOptions`, `TempestPwaIconsOptions`, `TempestPwaDevSwOptions`, `AppleSplashSpec`, `TempestVitePlugin` |
|
|
237
|
+
| `forms` _(peer: `zod`, `react-hook-form`)_ | `validateForm`, `zodResolver`, `useZodForm`, `validateCPF`, `validateCNPJ`, `formatCEP`, `formatCNPJ`, `unmask`, `CPFInput`, `CNPJInput`, `PhoneInput`, `CEPInput`, `MoneyInput`, `useViaCEP` |
|
|
238
|
+
| `sse` | `createEventStream`, `useEventStream` |
|
|
239
|
+
| `ws` | `createWebSocket`, `useWebSocket` |
|
|
240
|
+
| `geo` _(opt. peer `leaflet`)_ | `haversineKm`, `pathLengthKm`, `bearingDeg`, `estimateTravel`, `createOSRMBackend`, `boundingBox`, `projectMercator`, `fitProjection`, `createPositionTracker`, `usePositionTracker`, `TrajectoryMap` — tile-free SVG map + trajectory tracking (no external/paid API; Leaflet is an opt-in, lazy-loaded tile layer for self-hosted tiles), types: `Coordinate`, `TrackPoint`, `TravelEstimate`, `TravelMode`, `GeoBounds`, `RoutingBackend` |
|
|
241
|
+
| `br` _(subpath `tempest-react-sdk/br`)_ | `BrazilMap`, `BrazilStateMap`, `BrazilStateCitySelect`, `listStates`, `getState`, `citiesByUf`, `statesByRegion`, `ufChoices`, `cityChoices`, `isValidUf`, `normalizeUf`, `isValidCity`, `loadBrUfGeoJson`, `loadStateMunicipalities`, types `UF`, `BrRegion`, `BrazilState` — clickable 27-UF SVG map + per-state municipality submaps (bundled simplified IBGE GeoJSON, lazy per UF) + states/cities dataset, no external API; mirrors the FastAPI SDK `utils/locations` |
|
|
242
|
+
| `push` | `WebPushClient`, `WebPushUnsupportedError`, `WebPushPermissionDeniedError`, `usePushSubscription`, `urlBase64ToUint8Array`, `isPushSupported` |
|
|
243
|
+
| `sw` _(also subpath `tempest-react-sdk/sw`)_ | `registerServiceWorker` (opt-in `autoUpdate` poll + reload, no `vite-plugin-pwa`), `skipWaiting`, `unregisterAllServiceWorkers`, `installPushHandler`, `installNotificationClickHandler`, `installSkipWaitingListener`, `installPrecache` (app-shell offline), `installRuntimeCache` (per-route caching, incl. `rangeRequests`), `createPartialResponse` (206 range slicing), `installBackgroundSync` (offline mutation queue) — the React-free `tempest-react-sdk/sw` subpath is ideal for bundling into your own `sw.ts` |
|
|
244
|
+
| `editor` _(subpath `tempest-react-sdk/editor`, opt. peers `@tiptap/react`+`@tiptap/starter-kit`)_ | `RichTextEditor` — themed tiptap v3 rich-text editor with toolbar (tiptap externalized; install it only if you use the editor) |
|
|
245
|
+
| `vision` _(subpath `tempest-react-sdk/vision`, opt. peer `onnxruntime-web`)_ | `Classifier`, `Detector`, `Segmenter` + results/labels/preprocess — on-device ONNX vision inference, vendored from `@mauriciobenjamin700/ort-vision-sdk-web` (onnxruntime-web externalized; install it only if you use vision). Plus browser capture primitives: `useCameraStream` (rear-camera `getUserMedia` + classified errors + `retry()`), `computeImageLuminance`/`isLuminanceAcceptable`/`LowLuminanceError`/`LUMINANCE_SAMPLE_MAX_EDGE` (BT.709 brightness), `useLiveLuminance` (live rAF sampling) |
|
|
246
|
+
| `audio` | `createAudioPlayer`, `playAudio`, `stopAudio`, `useAudio` |
|
|
247
|
+
| `offline` _(peer: `dexie`)_ | `createOfflineStore`, `createOfflineSync` (outbox + delta-pull + watermark engine), types: `OfflineStore`, `OfflineStoreConfig`, `ListOptions`, `OfflineSync`, `OfflineSyncConfig`, `OutboxEntry`, `PullPage`, `SyncRunSummary`, `SyncTrigger`, `WatermarkStore` |
|
|
248
|
+
| `error-boundary` | `ErrorBoundary`, `useErrorHandler`, types: `ErrorBoundaryProps`, `ErrorBoundaryRenderProps` |
|
|
249
|
+
| `theme` | `ThemeProvider`, `useTheme`, `getInitialTheme`, `themeInitScript`, types: `ThemeMode`, `ResolvedTheme` |
|
|
250
|
+
| `i18n` | `createI18n`, `I18nProvider`, `useI18n`, `useTranslate`, types: `Catalog`, `Messages`, `I18n`, `InterpolationValues` |
|
|
251
|
+
| `logger` | `createLogger`, `consoleSink`, types: `Logger`, `LogEntry`, `LogLevel`, `LoggerSink` |
|
|
252
|
+
| `telemetry` | `TelemetryProvider`, `useTelemetry`, `consoleTelemetryAdapter`, `createSentryTelemetryAdapter`, `createPostHogTelemetryAdapter`, types: `TelemetryAdapter`, `TelemetryEvent`, `TelemetryUser`, `CreateSentryTelemetryAdapterOptions`, `SentryLike`, `CreatePostHogTelemetryAdapterOptions`, `PostHogLike` |
|
|
253
|
+
| `feature-flags` | `FeatureFlagsProvider`, `useFeatureFlag`, `useFlagValue`, `createInMemoryFlags`, `createGrowthBookFeatureFlagsAdapter`, `createLaunchDarklyFeatureFlagsAdapter`, types: `FeatureFlagsAdapter`, `FlagValue`, `GrowthBookLike`, `LDClientLike` |
|
|
254
|
+
| `share` | `share`, `isShareSupported`, `shareOrDownloadBlob` (Web Share file → download fallback), types: `SharePayload`, `ShareResult`, `ShareOrDownloadOptions` |
|
|
255
|
+
| `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`) |
|
|
256
|
+
| generic components | display (`CopyButton`, `RelativeTime`, `Money`, `TruncateText`, `VisuallyHidden`), headless (`Portal`, `ClickOutside`, `ConditionalWrapper`, `For`, `ErrorText`), media/content (`Image`, `DataList`, `DescriptionList`) |
|
|
257
257
|
|
|
258
258
|
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).
|
|
259
259
|
|
package/dist/sw.cjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});async function
|
|
1
|
+
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const L=3600*1e3;let p=!1;function N(){if(p)return;p=!0;let t=!1;navigator.serviceWorker.addEventListener("controllerchange",()=>{t||(t=!0,window.location.reload())})}async function T(t){if(typeof navigator>"u"||!("serviceWorker"in navigator))return null;try{const e=await navigator.serviceWorker.register(t.url,{scope:t.scope});if(e.active&&t.onReady?.(e),e.addEventListener("updatefound",()=>{const a=e.installing;a&&a.addEventListener("statechange",()=>{a.state==="installed"&&navigator.serviceWorker.controller&&t.onUpdate?.(a,e)})}),t.autoUpdate){t.reloadOnActivate!==!1&&N();const a=t.updateIntervalMs??L;window.setInterval(()=>{e.update()},a)}return e}catch(e){return t.onError?.(e),null}}function P(t){t.postMessage({type:"SKIP_WAITING"})}async function U(){if(typeof navigator>"u"||!("serviceWorker"in navigator))return 0;const t=await navigator.serviceWorker.getRegistrations();let e=0;for(const a of t)await a.unregister()&&(e+=1);return e}function w(){return globalThis}function A(t={}){const e=w(),{defaultTitle:a="Notificação",defaultIcon:n,defaultBadge:c,transform:i}=t;e.addEventListener("push",r=>{if(!r.data)return;let s;try{s=r.data.json()}catch{s={title:a,body:r.data.text()}}const o=i?i(s):s;if(!o)return;const l=o.title??a,u={body:o.body,icon:o.icon??n,badge:o.badge??c,image:o.image,tag:o.tag,data:{url:o.url??"/",...o.data??{}}};r.waitUntil(e.registration.showNotification(l,u))})}function x(t={}){const e=w(),a=t.resolveUrl??(n=>{if(typeof n=="string")return n;if(n&&typeof n=="object"&&"url"in n){const c=n.url;return typeof c=="string"?c:"/"}return"/"});e.addEventListener("notificationclick",n=>{n.notification.close();const c=a(n.notification.data);n.waitUntil((async()=>{const i=await e.clients.matchAll({type:"window",includeUncontrolled:!0});for(const r of i)if(r.url.includes(c))return r.focus();return e.clients.openWindow(c)})())})}function D(){const t=w();t.addEventListener("message",e=>{e.data?.type==="SKIP_WAITING"&&t.skipWaiting()})}function R(){return globalThis}let h="";const y=new Set;function E(t,e){if(!e)return!1;const a=t.headers.get("date");return a?(Date.now()-new Date(a).getTime())/1e3>e:!1}async function g(t,e){if(!e)return;const a=await caches.open(t),n=await a.keys();if(!(n.length<=e))for(const c of n.slice(0,n.length-e))await a.delete(c)}async function I(t,e){const a=await caches.open(e.cacheName),n=await a.match(t);if(n&&!E(n,e.maxAgeSeconds))return n;const c=await fetch(t);return c.ok&&(await a.put(t,c.clone()),await g(e.cacheName,e.maxEntries)),c}async function M(t,e){const a=await caches.open(e.cacheName),n=(async()=>{const i=await fetch(t);return i.ok&&(await a.put(t,i.clone()),await g(e.cacheName,e.maxEntries)),i})(),c=(e.networkTimeoutSeconds??0)*1e3;try{if(c>0){const i=new Promise((r,s)=>setTimeout(()=>s(new Error("network-timeout")),c));return await Promise.race([n,i])}return await n}catch{const i=await a.match(t);if(i)return i;throw new Error("network-first: no network and no cache")}}async function $(t,e){const a=await caches.open(e.cacheName),n=await a.match(t),c=fetch(t).then(async r=>(r.ok&&(await a.put(t,r.clone()),await g(e.cacheName,e.maxEntries)),r)).catch(()=>{});if(n&&!E(n,e.maxAgeSeconds))return n;const i=await c;if(i)return i;if(n)return n;throw new Error("stale-while-revalidate: no network and no cache")}function k(t,e){switch(e.strategy){case"cache-first":return I(t,e);case"network-first":return M(t,e);case"stale-while-revalidate":return $(t,e)}}function C(t,e,a){return typeof t.match=="function"?t.match(e,a):t.match.test(e.href)}async function S(t,e){const a=t.headers.get("range");if(!a)return e;const n=/^bytes=(\d*)-(\d*)$/.exec(a.trim());if(!n||n[1]===""&&n[2]==="")return new Response(null,{status:416,statusText:"Range Not Satisfiable"});const c=await e.clone().arrayBuffer(),i=c.byteLength;let r,s;if(n[1]===""){const u=Number(n[2]);r=Math.max(0,i-u),s=i-1}else r=Number(n[1]),s=n[2]===""?i-1:Math.min(Number(n[2]),i-1);if(r>s||r>=i)return new Response(null,{status:416,statusText:"Range Not Satisfiable",headers:{"Content-Range":`bytes */${i}`}});const o=c.slice(r,s+1),l=new Headers(e.headers);return l.set("Content-Range",`bytes ${r}-${s}/${i}`),l.set("Content-Length",String(o.byteLength)),l.set("Accept-Ranges","bytes"),new Response(o,{status:206,statusText:"Partial Content",headers:l})}function H(t){R().addEventListener("fetch",a=>{const n=a.request;if(n.method!=="GET")return;const c=new URL(n.url),i=t.find(r=>C(r,c,n));if(i){if(i.rangeRequests&&n.headers.has("range")){const r=new Request(n.url,{headers:j(n.headers),credentials:n.credentials,mode:n.mode==="navigate"?"same-origin":n.mode});a.respondWith(k(r,i).then(s=>S(n,s)));return}a.respondWith(k(n,i))}})}function j(t){const e=new Headers(t);return e.delete("range"),e}function q(t={}){const e=R(),{manifestUrl:a="/precache-manifest.json",cacheName:n="tempest-precache",navigateFallback:c="/index.html",navigateFallbackDenylist:i=[],skipWaiting:r=!0}=t;e.addEventListener("install",s=>{s.waitUntil((async()=>{const l=await(await fetch(a,{cache:"no-cache"})).json();h=`${n}-${l.version}`,await(await caches.open(h)).addAll(l.urls);for(const f of l.urls)y.add(new URL(f,e.location.origin).pathname);r&&await e.skipWaiting()})())}),e.addEventListener("activate",s=>{s.waitUntil((async()=>{const o=await caches.keys();await Promise.all(o.filter(l=>l.startsWith(`${n}-`)&&l!==h).map(l=>caches.delete(l))),await e.clients.claim()})())}),e.addEventListener("fetch",s=>{const o=s.request;if(o.method!=="GET")return;const l=new URL(o.url);if(l.origin===e.location.origin){if(o.mode==="navigate"){if(i.some(u=>u.test(l.pathname)))return;s.respondWith((async()=>{try{return await fetch(o)}catch{const f=await(await caches.open(h)).match(c);if(f)return f;throw new Error("offline and no cached app shell")}})());return}y.has(l.pathname)&&s.respondWith((async()=>await(await caches.open(h)).match(o)??fetch(o))())}})}function B(){return globalThis}const d="requests";function m(t){return new Promise((e,a)=>{const n=indexedDB.open(t,1);n.onupgradeneeded=()=>{n.result.createObjectStore(d,{keyPath:"id",autoIncrement:!0})},n.onsuccess=()=>e(n.result),n.onerror=()=>a(n.error)})}function W(t){return new Promise((e,a)=>{t.oncomplete=()=>e(),t.onerror=()=>a(t.error),t.onabort=()=>a(t.error)})}async function G(t,e){const a=await m(t),n=a.transaction(d,"readwrite");n.objectStore(d).add(e),await W(n),a.close()}async function _(t){const e=await m(t),a=e.transaction(d,"readonly"),n=await new Promise((c,i)=>{const r=a.objectStore(d).getAll();r.onsuccess=()=>c(r.result),r.onerror=()=>i(r.error)});return e.close(),n}async function v(t,e){const a=await m(t),n=a.transaction(d,"readwrite");n.objectStore(d).delete(e),await W(n),a.close()}async function F(t,e){const a=await t.clone().arrayBuffer();return{url:t.url,method:t.method,headers:[...t.headers.entries()],body:a.byteLength>0?a:null,timestamp:e}}function O(t){return new Request(t.url,{method:t.method,headers:t.headers,body:t.body??void 0})}async function b(t,e,a){const n=await _(t);let c=0;for(const i of n)if(i.id!==void 0){if(a-i.timestamp>e){await v(t,i.id);continue}try{const r=await fetch(O(i));r.ok||r.status>=400&&r.status<500?await v(t,i.id):c+=1}catch{c+=1}}if(c>0)throw new Error(`background-sync: ${c} request(s) still pending`)}function z(t,e,a){return t?typeof t=="function"?t(e,a):t.test(e.href):!0}function K(t={}){const e=B(),{match:a,queueName:n="tempest-bg-sync",maxRetentionMinutes:c=1440}=t,i=c*60*1e3;e.addEventListener("fetch",r=>{const s=r.request;if(s.method==="GET"||s.method==="HEAD")return;const o=new URL(s.url);z(a,o,s)&&r.respondWith(fetch(s.clone()).catch(async l=>{const u=await F(s,Date.now());await G(n,u);try{await e.registration.sync?.register(n)}catch{}throw l}))}),e.addEventListener("sync",r=>{r.tag===n&&r.waitUntil(b(n,i,Date.now()))}),e.addEventListener("fetch",r=>{e.registration.sync||r.request.method==="GET"&&r.waitUntil(b(n,i,Date.now()).catch(()=>{}))})}exports.createPartialResponse=S;exports.installBackgroundSync=K;exports.installNotificationClickHandler=x;exports.installPrecache=q;exports.installPushHandler=A;exports.installRuntimeCache=H;exports.installSkipWaitingListener=D;exports.registerServiceWorker=T;exports.skipWaiting=P;exports.unregisterAllServiceWorkers=U;
|
|
2
2
|
//# sourceMappingURL=sw.cjs.map
|
package/dist/sw.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"sw.cjs","sources":["../src/sw/register-service-worker.ts","../src/sw/create-push-handler.ts","../src/sw/cache.ts","../src/sw/background-sync.ts"],"sourcesContent":["export interface RegisterServiceWorkerOptions {\n /** Public URL of the compiled service worker file (e.g. `/sw.js`). */\n url: string;\n /** SW scope (default: SW directory). */\n scope?: string;\n /** Called once the registration is active. */\n onReady?: (registration: ServiceWorkerRegistration) => void;\n /**\n * Called when a new worker has finished installing while another worker\n * still controls the page. The host app typically prompts the user to\n * reload and then calls {@link skipWaiting} on the returned worker.\n */\n onUpdate?: (waiting: ServiceWorker, registration: ServiceWorkerRegistration) => void;\n /** Called on registration failure. */\n onError?: (error: unknown) => void;\n}\n\n/**\n * Register a service worker with consistent update-detection wiring.\n *\n * Skips silently when the runtime has no `serviceWorker` support. The host\n * app keeps full control over the SW file — this helper only handles the\n * boilerplate around `register()` and `updatefound`.\n *\n * @returns The registration when it succeeds, or `null` when unsupported.\n */\nexport async function registerServiceWorker(\n options: RegisterServiceWorkerOptions,\n): Promise<ServiceWorkerRegistration | null> {\n if (typeof navigator === \"undefined\" || !(\"serviceWorker\" in navigator)) {\n return null;\n }\n\n try {\n const registration = await navigator.serviceWorker.register(options.url, {\n scope: options.scope,\n });\n\n if (registration.active) options.onReady?.(registration);\n\n registration.addEventListener(\"updatefound\", () => {\n const installing = registration.installing;\n if (!installing) return;\n installing.addEventListener(\"statechange\", () => {\n if (installing.state === \"installed\" && navigator.serviceWorker.controller) {\n options.onUpdate?.(installing, registration);\n }\n });\n });\n\n return registration;\n } catch (error) {\n options.onError?.(error);\n return null;\n }\n}\n\n/**\n * Tell a waiting worker to activate immediately. Pair with `onUpdate` to roll\n * out updates after the user confirms a reload prompt.\n */\nexport function skipWaiting(worker: ServiceWorker): void {\n worker.postMessage({ type: \"SKIP_WAITING\" });\n}\n\n/**\n * Unregister all registered service workers for this origin.\n *\n * @returns Number of workers that were unregistered.\n */\nexport async function unregisterAllServiceWorkers(): Promise<number> {\n if (typeof navigator === \"undefined\" || !(\"serviceWorker\" in navigator)) return 0;\n const registrations = await navigator.serviceWorker.getRegistrations();\n let count = 0;\n for (const registration of registrations) {\n const result = await registration.unregister();\n if (result) count += 1;\n }\n return count;\n}\n","/**\n * Service-worker context helpers for handling `push` and `notificationclick`\n * events. Import these inside your own `sw.ts` — they expect to run in the\n * service-worker global scope, not in the main thread.\n *\n * @example\n * /// <reference lib=\"webworker\" />\n * import { installPushHandler, installNotificationClickHandler } from \"tempest-react-sdk\";\n *\n * installPushHandler({ defaultIcon: \"/icons/Logo.png\" });\n * installNotificationClickHandler();\n */\n\ninterface SwGlobal {\n registration: {\n showNotification(title: string, options?: NotificationOptions): Promise<void>;\n };\n clients: {\n matchAll(options: { type: \"window\"; includeUncontrolled?: boolean }): Promise<\n {\n url: string;\n focused: boolean;\n focus(): Promise<unknown>;\n navigate(url: string): Promise<unknown>;\n }[]\n >;\n openWindow(url: string): Promise<unknown>;\n };\n addEventListener(\n type: \"push\",\n listener: (event: {\n data: { json(): unknown; text(): string } | null;\n waitUntil(promise: Promise<unknown>): void;\n }) => void,\n ): void;\n addEventListener(\n type: \"notificationclick\",\n listener: (event: {\n notification: { close(): void; data?: unknown };\n waitUntil(promise: Promise<unknown>): void;\n }) => void,\n ): void;\n skipWaiting(): Promise<void>;\n}\n\nfunction getSwScope(): SwGlobal {\n return globalThis as unknown as SwGlobal;\n}\n\nexport interface PushPayload {\n title?: string;\n body?: string;\n icon?: string;\n badge?: string;\n image?: string;\n tag?: string;\n url?: string;\n /** Arbitrary extra data forwarded to `event.notification.data`. */\n data?: Record<string, unknown>;\n}\n\nexport interface InstallPushHandlerOptions {\n /** Title used when the payload omits one. */\n defaultTitle?: string;\n /** Icon used when the payload omits one. */\n defaultIcon?: string;\n /** Badge image (mobile). */\n defaultBadge?: string;\n /**\n * Transform the raw payload before showing the notification. Return `null`\n * to suppress the notification entirely (e.g. silent pings).\n */\n transform?: (payload: PushPayload) => PushPayload | null;\n}\n\n/**\n * Install a `push` event listener that parses the payload as JSON (with a\n * plain-text fallback) and shows a notification.\n */\nexport function installPushHandler(options: InstallPushHandlerOptions = {}): void {\n const sw = getSwScope();\n const { defaultTitle = \"Notificação\", defaultIcon, defaultBadge, transform } = options;\n\n sw.addEventListener(\"push\", (event) => {\n if (!event.data) return;\n\n let raw: PushPayload;\n try {\n raw = event.data.json() as PushPayload;\n } catch {\n raw = { title: defaultTitle, body: event.data.text() };\n }\n\n const payload = transform ? transform(raw) : raw;\n if (!payload) return;\n\n const title = payload.title ?? defaultTitle;\n const notification: NotificationOptions & { image?: string } = {\n body: payload.body,\n icon: payload.icon ?? defaultIcon,\n badge: payload.badge ?? defaultBadge,\n image: payload.image,\n tag: payload.tag,\n data: { url: payload.url ?? \"/\", ...(payload.data ?? {}) },\n };\n\n event.waitUntil(sw.registration.showNotification(title, notification));\n });\n}\n\nexport interface InstallNotificationClickHandlerOptions {\n /** Resolve the destination URL from the notification data. Default: `data.url`. */\n resolveUrl?: (data: unknown) => string;\n}\n\n/**\n * Install a `notificationclick` handler that focuses an existing client when\n * possible and falls back to opening a new window.\n */\nexport function installNotificationClickHandler(\n options: InstallNotificationClickHandlerOptions = {},\n): void {\n const sw = getSwScope();\n const resolveUrl =\n options.resolveUrl ??\n ((data: unknown) => {\n if (typeof data === \"string\") return data;\n if (data && typeof data === \"object\" && \"url\" in data) {\n const url = (data as Record<string, unknown>).url;\n return typeof url === \"string\" ? url : \"/\";\n }\n return \"/\";\n });\n\n sw.addEventListener(\"notificationclick\", (event) => {\n event.notification.close();\n const target = resolveUrl(event.notification.data);\n\n event.waitUntil(\n (async () => {\n const clients = await sw.clients.matchAll({\n type: \"window\",\n includeUncontrolled: true,\n });\n for (const client of clients) {\n if (client.url.includes(target)) {\n return client.focus();\n }\n }\n return sw.clients.openWindow(target);\n })(),\n );\n });\n}\n\n/**\n * Install a `message` listener that activates a waiting worker when the host\n * app sends `{ type: \"SKIP_WAITING\" }`.\n */\nexport function installSkipWaitingListener(): void {\n const sw = getSwScope() as SwGlobal & {\n addEventListener(\n type: \"message\",\n listener: (event: { data?: { type?: string } }) => void,\n ): void;\n };\n sw.addEventListener(\"message\", (event) => {\n if (event.data?.type === \"SKIP_WAITING\") {\n void sw.skipWaiting();\n }\n });\n}\n","/**\n * Service-worker caching helpers — a small, dependency-free subset of what\n * Workbox provides: precaching of the build's app shell (so the app launches\n * offline) plus runtime caching strategies for fonts, APIs and images.\n *\n * Import these inside your own `sw.ts`. They run in the service-worker global\n * scope, not the main thread. Pair `installPrecache` with the\n * `tempestPwaManifest()` Vite plugin (from `tempest-react-sdk/vite`), which\n * emits the `precache-manifest.json` this reads at install time.\n *\n * @example\n * /// <reference lib=\"webworker\" />\n * import { installRuntimeCache, installPrecache } from \"tempest-react-sdk/sw\";\n *\n * // Register specific routes FIRST so they win over the precache catch-all.\n * installRuntimeCache([\n * { match: /\\/api\\//, strategy: \"network-first\", cacheName: \"api\", maxAgeSeconds: 300 },\n * ]);\n * installPrecache();\n */\n\n/** Minimal shape of the events we touch, to avoid pulling in `lib.webworker`. */\ninterface ExtendableEventLike {\n waitUntil(promise: Promise<unknown>): void;\n}\n\ninterface FetchEventLike extends ExtendableEventLike {\n request: Request;\n respondWith(response: Response | Promise<Response>): void;\n}\n\ninterface CacheSwGlobal {\n addEventListener(type: \"install\", listener: (event: ExtendableEventLike) => void): void;\n addEventListener(type: \"activate\", listener: (event: ExtendableEventLike) => void): void;\n addEventListener(type: \"fetch\", listener: (event: FetchEventLike) => void): void;\n clients: { claim(): Promise<void> };\n skipWaiting(): Promise<void>;\n location: { origin: string };\n}\n\nfunction getSwScope(): CacheSwGlobal {\n return globalThis as unknown as CacheSwGlobal;\n}\n\n/** Caching strategy for a runtime route. Mirrors the common Workbox trio. */\nexport type RuntimeStrategy = \"cache-first\" | \"network-first\" | \"stale-while-revalidate\";\n\n/** A single runtime-caching rule, matched against each `GET` request. */\nexport interface RuntimeRoute {\n /** A `RegExp` tested against the full URL, or a predicate over the parsed URL. */\n match: RegExp | ((url: URL, request: Request) => boolean);\n /** How to resolve a match. */\n strategy: RuntimeStrategy;\n /** Cache bucket name for this route. */\n cacheName: string;\n /** Trim the cache to at most this many entries (FIFO) after each write. */\n maxEntries?: number;\n /** Treat a cached response older than this (seconds) as a miss. */\n maxAgeSeconds?: number;\n /** For `network-first`: fall back to cache after this timeout (seconds). */\n networkTimeoutSeconds?: number;\n /**\n * Serve HTTP `Range` requests (206 Partial Content) by slicing the cached\n * full response. Enable for audio/video so seeking works offline. The full\n * resource is cached once (the `Range` header is stripped before caching).\n */\n rangeRequests?: boolean;\n}\n\n/** Options for {@link installPrecache}. */\nexport interface InstallPrecacheOptions {\n /** URL of the manifest emitted by `tempestPwaManifest()`. Default `/precache-manifest.json`. */\n manifestUrl?: string;\n /** Cache name prefix; the manifest `version` is appended. Default `tempest-precache`. */\n cacheName?: string;\n /** App-shell document served for navigation requests offline. Default `/index.html`. */\n navigateFallback?: string;\n /** Navigation paths that should NOT use the fallback (e.g. `[/^\\/api\\//]`). */\n navigateFallbackDenylist?: RegExp[];\n /** Activate the new worker immediately after precaching. Default `true`. */\n skipWaiting?: boolean;\n}\n\ninterface PrecacheManifest {\n version: string;\n urls: string[];\n}\n\nlet precacheName = \"\";\nconst precachedPaths = new Set<string>();\n\n/** Whether a cached response has aged past `maxAgeSeconds` (best-effort, via `Date`). */\nfunction isExpired(response: Response, maxAgeSeconds?: number): boolean {\n if (!maxAgeSeconds) return false;\n const dateHeader = response.headers.get(\"date\");\n if (!dateHeader) return false;\n const age = (Date.now() - new Date(dateHeader).getTime()) / 1000;\n return age > maxAgeSeconds;\n}\n\n/** Drop oldest entries until the cache holds at most `maxEntries`. */\nasync function trimCache(cacheName: string, maxEntries?: number): Promise<void> {\n if (!maxEntries) return;\n const cache = await caches.open(cacheName);\n const keys = await cache.keys();\n if (keys.length <= maxEntries) return;\n for (const key of keys.slice(0, keys.length - maxEntries)) {\n await cache.delete(key);\n }\n}\n\nasync function cacheFirst(request: Request, route: RuntimeRoute): Promise<Response> {\n const cache = await caches.open(route.cacheName);\n const cached = await cache.match(request);\n if (cached && !isExpired(cached, route.maxAgeSeconds)) return cached;\n\n const response = await fetch(request);\n if (response.ok) {\n await cache.put(request, response.clone());\n await trimCache(route.cacheName, route.maxEntries);\n }\n return response;\n}\n\nasync function networkFirst(request: Request, route: RuntimeRoute): Promise<Response> {\n const cache = await caches.open(route.cacheName);\n\n const network = (async (): Promise<Response> => {\n const response = await fetch(request);\n if (response.ok) {\n await cache.put(request, response.clone());\n await trimCache(route.cacheName, route.maxEntries);\n }\n return response;\n })();\n\n const timeoutMs = (route.networkTimeoutSeconds ?? 0) * 1000;\n try {\n if (timeoutMs > 0) {\n const timeout = new Promise<never>((_, reject) =>\n setTimeout(() => reject(new Error(\"network-timeout\")), timeoutMs),\n );\n return await Promise.race([network, timeout]);\n }\n return await network;\n } catch {\n const cached = await cache.match(request);\n if (cached) return cached;\n throw new Error(\"network-first: no network and no cache\");\n }\n}\n\nasync function staleWhileRevalidate(request: Request, route: RuntimeRoute): Promise<Response> {\n const cache = await caches.open(route.cacheName);\n const cached = await cache.match(request);\n\n const network = fetch(request)\n .then(async (response) => {\n if (response.ok) {\n await cache.put(request, response.clone());\n await trimCache(route.cacheName, route.maxEntries);\n }\n return response;\n })\n .catch(() => undefined);\n\n if (cached && !isExpired(cached, route.maxAgeSeconds)) return cached;\n const response = await network;\n if (response) return response;\n if (cached) return cached;\n throw new Error(\"stale-while-revalidate: no network and no cache\");\n}\n\nfunction runRoute(request: Request, route: RuntimeRoute): Promise<Response> {\n switch (route.strategy) {\n case \"cache-first\":\n return cacheFirst(request, route);\n case \"network-first\":\n return networkFirst(request, route);\n case \"stale-while-revalidate\":\n return staleWhileRevalidate(request, route);\n }\n}\n\nfunction routeMatches(route: RuntimeRoute, url: URL, request: Request): boolean {\n return typeof route.match === \"function\"\n ? route.match(url, request)\n : route.match.test(url.href);\n}\n\n/**\n * Build a `206 Partial Content` response from a full one for an HTTP `Range`\n * request. Supports `bytes=start-end`, open-ended `bytes=start-` and suffix\n * `bytes=-suffixLength`. Returns the original response when there is no usable\n * `Range` header, or a `416` when the range is unsatisfiable.\n *\n * @param request The incoming request (its `Range` header drives the slice).\n * @param response The full (200) response to slice.\n */\nexport async function createPartialResponse(\n request: Request,\n response: Response,\n): Promise<Response> {\n const rangeHeader = request.headers.get(\"range\");\n if (!rangeHeader) return response;\n\n const match = /^bytes=(\\d*)-(\\d*)$/.exec(rangeHeader.trim());\n if (!match || (match[1] === \"\" && match[2] === \"\")) {\n return new Response(null, { status: 416, statusText: \"Range Not Satisfiable\" });\n }\n\n const buffer = await response.clone().arrayBuffer();\n const total = buffer.byteLength;\n\n let start: number;\n let end: number;\n if (match[1] === \"\") {\n // Suffix range: last N bytes.\n const suffix = Number(match[2]);\n start = Math.max(0, total - suffix);\n end = total - 1;\n } else {\n start = Number(match[1]);\n end = match[2] === \"\" ? total - 1 : Math.min(Number(match[2]), total - 1);\n }\n\n if (start > end || start >= total) {\n return new Response(null, {\n status: 416,\n statusText: \"Range Not Satisfiable\",\n headers: { \"Content-Range\": `bytes */${total}` },\n });\n }\n\n const slice = buffer.slice(start, end + 1);\n const headers = new Headers(response.headers);\n headers.set(\"Content-Range\", `bytes ${start}-${end}/${total}`);\n headers.set(\"Content-Length\", String(slice.byteLength));\n headers.set(\"Accept-Ranges\", \"bytes\");\n\n return new Response(slice, {\n status: 206,\n statusText: \"Partial Content\",\n headers,\n });\n}\n\n/**\n * Install a `fetch` handler that resolves matching `GET` requests with the\n * given runtime strategies. Non-matching requests are left untouched (no\n * `respondWith`), so a later {@link installPrecache} can handle them.\n *\n * Register this BEFORE `installPrecache` so specific routes win over the\n * precache catch-all.\n *\n * @param routes Ordered rules; the first whose `match` passes handles the request.\n */\nexport function installRuntimeCache(routes: RuntimeRoute[]): void {\n const sw = getSwScope();\n sw.addEventListener(\"fetch\", (event) => {\n const request = event.request;\n if (request.method !== \"GET\") return;\n\n const url = new URL(request.url);\n const route = routes.find((candidate) => routeMatches(candidate, url, request));\n if (!route) return;\n\n if (route.rangeRequests && request.headers.has(\"range\")) {\n // Cache/serve the FULL resource once (no Range), then slice it.\n const full = new Request(request.url, {\n headers: stripRange(request.headers),\n credentials: request.credentials,\n mode: request.mode === \"navigate\" ? \"same-origin\" : request.mode,\n });\n event.respondWith(\n runRoute(full, route).then((response) => createPartialResponse(request, response)),\n );\n return;\n }\n\n event.respondWith(runRoute(request, route));\n });\n}\n\n/** Copy headers without the `Range` header (so the cached entry is the full file). */\nfunction stripRange(headers: Headers): Headers {\n const out = new Headers(headers);\n out.delete(\"range\");\n return out;\n}\n\n/**\n * Precache the app shell at `install` and serve it offline:\n * - reads `precache-manifest.json` (emitted by `tempestPwaManifest()`),\n * - caches every listed URL under a versioned cache,\n * - on `activate`, deletes stale precache versions and claims open clients,\n * - on `fetch`, serves precached assets cache-first and falls back to the\n * `navigateFallback` document for offline navigations (SPA routing).\n *\n * Same-origin only. Register this LAST, after any {@link installRuntimeCache}.\n */\nexport function installPrecache(options: InstallPrecacheOptions = {}): void {\n const sw = getSwScope();\n const {\n manifestUrl = \"/precache-manifest.json\",\n cacheName = \"tempest-precache\",\n navigateFallback = \"/index.html\",\n navigateFallbackDenylist = [],\n skipWaiting = true,\n } = options;\n\n sw.addEventListener(\"install\", (event) => {\n event.waitUntil(\n (async () => {\n const response = await fetch(manifestUrl, { cache: \"no-cache\" });\n const manifest = (await response.json()) as PrecacheManifest;\n precacheName = `${cacheName}-${manifest.version}`;\n\n const cache = await caches.open(precacheName);\n await cache.addAll(manifest.urls);\n for (const url of manifest.urls) {\n precachedPaths.add(new URL(url, sw.location.origin).pathname);\n }\n if (skipWaiting) await sw.skipWaiting();\n })(),\n );\n });\n\n sw.addEventListener(\"activate\", (event) => {\n event.waitUntil(\n (async () => {\n const keys = await caches.keys();\n await Promise.all(\n keys\n .filter((key) => key.startsWith(`${cacheName}-`) && key !== precacheName)\n .map((key) => caches.delete(key)),\n );\n await sw.clients.claim();\n })(),\n );\n });\n\n sw.addEventListener(\"fetch\", (event) => {\n const request = event.request;\n if (request.method !== \"GET\") return;\n\n const url = new URL(request.url);\n if (url.origin !== sw.location.origin) return;\n\n // SPA navigations: serve the cached app shell when offline.\n if (request.mode === \"navigate\") {\n if (navigateFallbackDenylist.some((re) => re.test(url.pathname))) return;\n event.respondWith(\n (async () => {\n try {\n return await fetch(request);\n } catch {\n const cache = await caches.open(precacheName);\n const shell = await cache.match(navigateFallback);\n if (shell) return shell;\n throw new Error(\"offline and no cached app shell\");\n }\n })(),\n );\n return;\n }\n\n // Precached static assets: cache-first.\n if (precachedPaths.has(url.pathname)) {\n event.respondWith(\n (async () => {\n const cache = await caches.open(precacheName);\n const cached = await cache.match(request);\n return cached ?? fetch(request);\n })(),\n );\n }\n });\n}\n","/**\n * Background-sync helper: queue failed mutating requests (POST/PUT/PATCH/DELETE)\n * while offline and replay them when connectivity returns. A dependency-free\n * take on Workbox's `BackgroundSyncPlugin`, backed by a tiny IndexedDB queue.\n *\n * Import inside your `sw.ts`. Uses the Background Sync API (`registration.sync`)\n * when available, and also replays opportunistically on the next request as a\n * fallback for browsers without it (e.g. Safari).\n *\n * @example\n * import { installBackgroundSync } from \"tempest-react-sdk/sw\";\n *\n * installBackgroundSync({ match: (url) => url.pathname.startsWith(\"/api/\") });\n */\n\ninterface SyncEventLike {\n tag: string;\n waitUntil(promise: Promise<unknown>): void;\n}\n\ninterface BgFetchEventLike {\n request: Request;\n respondWith(response: Response | Promise<Response>): void;\n waitUntil(promise: Promise<unknown>): void;\n}\n\ninterface BgSwGlobal {\n registration: { sync?: { register(tag: string): Promise<void> } };\n addEventListener(type: \"sync\", listener: (event: SyncEventLike) => void): void;\n addEventListener(type: \"fetch\", listener: (event: BgFetchEventLike) => void): void;\n}\n\nfunction getSwScope(): BgSwGlobal {\n return globalThis as unknown as BgSwGlobal;\n}\n\n/** A serialized request stored in the queue. */\ninterface QueuedRequest {\n id?: number;\n url: string;\n method: string;\n headers: [string, string][];\n body: ArrayBuffer | null;\n timestamp: number;\n}\n\n/** Options for {@link installBackgroundSync}. */\nexport interface InstallBackgroundSyncOptions {\n /**\n * Which requests to queue on failure. A `RegExp` against the URL or a\n * predicate. Only non-`GET` requests are ever considered. Default: all\n * non-`GET` requests.\n */\n match?: RegExp | ((url: URL, request: Request) => boolean);\n /** IndexedDB database name, also used as the sync tag. Default `tempest-bg-sync`. */\n queueName?: string;\n /** Drop queued requests older than this (minutes) on replay. Default `1440` (24h). */\n maxRetentionMinutes?: number;\n}\n\nconst STORE = \"requests\";\n\nfunction openQueueDb(name: string): Promise<IDBDatabase> {\n return new Promise((resolve, reject) => {\n const request = indexedDB.open(name, 1);\n request.onupgradeneeded = () => {\n request.result.createObjectStore(STORE, { keyPath: \"id\", autoIncrement: true });\n };\n request.onsuccess = () => resolve(request.result);\n request.onerror = () => reject(request.error);\n });\n}\n\nfunction txDone(tx: IDBTransaction): Promise<void> {\n return new Promise((resolve, reject) => {\n tx.oncomplete = () => resolve();\n tx.onerror = () => reject(tx.error);\n tx.onabort = () => reject(tx.error);\n });\n}\n\nasync function enqueue(name: string, entry: QueuedRequest): Promise<void> {\n const db = await openQueueDb(name);\n const tx = db.transaction(STORE, \"readwrite\");\n tx.objectStore(STORE).add(entry);\n await txDone(tx);\n db.close();\n}\n\nasync function readAll(name: string): Promise<QueuedRequest[]> {\n const db = await openQueueDb(name);\n const tx = db.transaction(STORE, \"readonly\");\n const all = await new Promise<QueuedRequest[]>((resolve, reject) => {\n const req = tx.objectStore(STORE).getAll();\n req.onsuccess = () => resolve(req.result as QueuedRequest[]);\n req.onerror = () => reject(req.error);\n });\n db.close();\n return all;\n}\n\nasync function remove(name: string, id: number): Promise<void> {\n const db = await openQueueDb(name);\n const tx = db.transaction(STORE, \"readwrite\");\n tx.objectStore(STORE).delete(id);\n await txDone(tx);\n db.close();\n}\n\nasync function serializeRequest(request: Request, timestamp: number): Promise<QueuedRequest> {\n const buffer = await request.clone().arrayBuffer();\n return {\n url: request.url,\n method: request.method,\n headers: [...request.headers.entries()],\n body: buffer.byteLength > 0 ? buffer : null,\n timestamp,\n };\n}\n\nfunction deserializeRequest(entry: QueuedRequest): Request {\n return new Request(entry.url, {\n method: entry.method,\n headers: entry.headers,\n body: entry.body ?? undefined,\n });\n}\n\n/**\n * Replay every queued request once. Successful (or stale) entries are removed;\n * entries that fail again are kept for the next attempt. Throws if any entry\n * still fails, so a `sync` handler keeps the sync pending.\n */\nasync function replayQueue(name: string, maxRetentionMs: number, now: number): Promise<void> {\n const entries = await readAll(name);\n let pending = 0;\n\n for (const entry of entries) {\n if (entry.id === undefined) continue;\n if (now - entry.timestamp > maxRetentionMs) {\n await remove(name, entry.id);\n continue;\n }\n try {\n const response = await fetch(deserializeRequest(entry));\n if (response.ok || (response.status >= 400 && response.status < 500)) {\n // 2xx = done; 4xx = client error that won't fix itself → drop it.\n await remove(name, entry.id);\n } else {\n pending += 1;\n }\n } catch {\n pending += 1;\n }\n }\n\n if (pending > 0) throw new Error(`background-sync: ${pending} request(s) still pending`);\n}\n\nfunction matches(\n match: InstallBackgroundSyncOptions[\"match\"],\n url: URL,\n request: Request,\n): boolean {\n if (!match) return true;\n return typeof match === \"function\" ? match(url, request) : match.test(url.href);\n}\n\n/**\n * Install the background-sync queue: on a failed mutating request, the request\n * is serialized to IndexedDB and a sync is registered; the original fetch still\n * rejects (so your app can show an offline state), and the request is replayed\n * later when the network returns.\n */\nexport function installBackgroundSync(options: InstallBackgroundSyncOptions = {}): void {\n const sw = getSwScope();\n const { match, queueName = \"tempest-bg-sync\", maxRetentionMinutes = 1440 } = options;\n const maxRetentionMs = maxRetentionMinutes * 60 * 1000;\n\n sw.addEventListener(\"fetch\", (event) => {\n const request = event.request;\n if (request.method === \"GET\" || request.method === \"HEAD\") return;\n\n const url = new URL(request.url);\n if (!matches(match, url, request)) return;\n\n event.respondWith(\n fetch(request.clone()).catch(async (error) => {\n const entry = await serializeRequest(request, Date.now());\n await enqueue(queueName, entry);\n try {\n await sw.registration.sync?.register(queueName);\n } catch {\n // Background Sync API unavailable — opportunistic replay covers it.\n }\n throw error;\n }),\n );\n });\n\n sw.addEventListener(\"sync\", (event) => {\n if (event.tag !== queueName) return;\n event.waitUntil(replayQueue(queueName, maxRetentionMs, Date.now()));\n });\n\n // Fallback for browsers without the Background Sync API: whenever a GET\n // succeeds (a sign we're online), drain the queue opportunistically.\n sw.addEventListener(\"fetch\", (event) => {\n if (sw.registration.sync) return; // native sync will handle it\n if (event.request.method !== \"GET\") return;\n event.waitUntil(replayQueue(queueName, maxRetentionMs, Date.now()).catch(() => undefined));\n });\n}\n"],"names":["registerServiceWorker","options","registration","installing","error","skipWaiting","worker","unregisterAllServiceWorkers","registrations","count","getSwScope","installPushHandler","sw","defaultTitle","defaultIcon","defaultBadge","transform","event","raw","payload","title","notification","installNotificationClickHandler","resolveUrl","data","url","target","clients","client","installSkipWaitingListener","precacheName","precachedPaths","isExpired","response","maxAgeSeconds","dateHeader","trimCache","cacheName","maxEntries","cache","keys","key","cacheFirst","request","route","cached","networkFirst","network","timeoutMs","timeout","_","reject","staleWhileRevalidate","runRoute","routeMatches","createPartialResponse","rangeHeader","match","buffer","total","start","end","suffix","slice","headers","installRuntimeCache","routes","candidate","full","stripRange","out","installPrecache","manifestUrl","navigateFallback","navigateFallbackDenylist","manifest","re","shell","STORE","openQueueDb","name","resolve","txDone","tx","enqueue","entry","db","readAll","all","req","remove","id","serializeRequest","timestamp","deserializeRequest","replayQueue","maxRetentionMs","now","entries","pending","matches","installBackgroundSync","queueName","maxRetentionMinutes"],"mappings":"gFA0BA,eAAsBA,EAClBC,EACyC,CACzC,GAAI,OAAO,UAAc,KAAe,EAAE,kBAAmB,WACzD,OAAO,KAGX,GAAI,CACA,MAAMC,EAAe,MAAM,UAAU,cAAc,SAASD,EAAQ,IAAK,CACrE,MAAOA,EAAQ,KAAA,CAClB,EAED,OAAIC,EAAa,QAAQD,EAAQ,UAAUC,CAAY,EAEvDA,EAAa,iBAAiB,cAAe,IAAM,CAC/C,MAAMC,EAAaD,EAAa,WAC3BC,GACLA,EAAW,iBAAiB,cAAe,IAAM,CACzCA,EAAW,QAAU,aAAe,UAAU,cAAc,YAC5DF,EAAQ,WAAWE,EAAYD,CAAY,CAEnD,CAAC,CACL,CAAC,EAEMA,CACX,OAASE,EAAO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,CACV,CAAC,CAAA,CAET,CAAC,EAEDQ,EAAG,iBAAiB,OAASK,GAAU,CAC/BA,EAAM,MAAQqF,GAClBrF,EAAM,UAAU8E,EAAYO,EAAWN,EAAgB,KAAK,IAAA,CAAK,CAAC,CACtE,CAAC,EAIDpF,EAAG,iBAAiB,QAAUK,GAAU,CAChCL,EAAG,aAAa,MAChBK,EAAM,QAAQ,SAAW,OAC7BA,EAAM,UAAU8E,EAAYO,EAAWN,EAAgB,KAAK,KAAK,EAAE,MAAM,IAAA,EAAe,CAAC,CAC7F,CAAC,CACL"}
|
|
1
|
+
{"version":3,"file":"sw.cjs","sources":["../src/sw/register-service-worker.ts","../src/sw/create-push-handler.ts","../src/sw/cache.ts","../src/sw/background-sync.ts"],"sourcesContent":["export interface RegisterServiceWorkerOptions {\n /** Public URL of the compiled service worker file (e.g. `/sw.js`). */\n url: string;\n /** SW scope (default: SW directory). */\n scope?: string;\n /** Called once the registration is active. */\n onReady?: (registration: ServiceWorkerRegistration) => void;\n /**\n * Called when a new worker has finished installing while another worker\n * still controls the page. The host app typically prompts the user to\n * reload and then calls {@link skipWaiting} on the returned worker.\n */\n onUpdate?: (waiting: ServiceWorker, registration: ServiceWorkerRegistration) => void;\n /** Called on registration failure. */\n onError?: (error: unknown) => void;\n /**\n * When `true`, poll the server for a fresh service worker on an interval\n * (see {@link RegisterServiceWorkerOptions.updateIntervalMs}) and, unless\n * {@link RegisterServiceWorkerOptions.reloadOnActivate} is disabled, reload\n * the page as soon as a new worker takes control. Mirrors the auto-update\n * behaviour of `vite-plugin-pwa` without depending on it. Default `false`.\n */\n autoUpdate?: boolean;\n /**\n * How often, in ms, to call `registration.update()` while `autoUpdate` is\n * on. Browsers already re-check roughly every 24h; an hourly poll keeps\n * long-lived sessions current without flooding the network. Default\n * `3600000` (1 hour).\n */\n updateIntervalMs?: number;\n /**\n * When `autoUpdate` is on, reload the page once a new worker takes control\n * (`controllerchange`), guarded against reload loops. Set to `false` to\n * keep polling but leave the reload to the host app. Default `true`.\n */\n reloadOnActivate?: boolean;\n}\n\nconst DEFAULT_UPDATE_INTERVAL_MS = 60 * 60 * 1000;\n\nlet controllerReloadWired = false;\n\nfunction wireControllerReload(): void {\n if (controllerReloadWired) return;\n controllerReloadWired = true;\n let refreshing = false;\n navigator.serviceWorker.addEventListener(\"controllerchange\", () => {\n if (refreshing) return;\n refreshing = true;\n window.location.reload();\n });\n}\n\n/**\n * Register a service worker with consistent update-detection wiring.\n *\n * Skips silently when the runtime has no `serviceWorker` support. The host\n * app keeps full control over the SW file — this helper only handles the\n * boilerplate around `register()` and `updatefound`.\n *\n * With `autoUpdate` enabled it additionally polls `registration.update()` on\n * an interval and (by default) reloads the page when a freshly activated worker\n * takes control — a framework-agnostic equivalent of `vite-plugin-pwa`'s\n * auto-update client, implemented directly on `navigator.serviceWorker`.\n *\n * @returns The registration when it succeeds, or `null` when unsupported.\n */\nexport async function registerServiceWorker(\n options: RegisterServiceWorkerOptions,\n): Promise<ServiceWorkerRegistration | null> {\n if (typeof navigator === \"undefined\" || !(\"serviceWorker\" in navigator)) {\n return null;\n }\n\n try {\n const registration = await navigator.serviceWorker.register(options.url, {\n scope: options.scope,\n });\n\n if (registration.active) options.onReady?.(registration);\n\n registration.addEventListener(\"updatefound\", () => {\n const installing = registration.installing;\n if (!installing) return;\n installing.addEventListener(\"statechange\", () => {\n if (installing.state === \"installed\" && navigator.serviceWorker.controller) {\n options.onUpdate?.(installing, registration);\n }\n });\n });\n\n if (options.autoUpdate) {\n if (options.reloadOnActivate !== false) wireControllerReload();\n const intervalMs = options.updateIntervalMs ?? DEFAULT_UPDATE_INTERVAL_MS;\n window.setInterval(() => {\n void registration.update();\n }, intervalMs);\n }\n\n return registration;\n } catch (error) {\n options.onError?.(error);\n return null;\n }\n}\n\n/**\n * Tell a waiting worker to activate immediately. Pair with `onUpdate` to roll\n * out updates after the user confirms a reload prompt.\n */\nexport function skipWaiting(worker: ServiceWorker): void {\n worker.postMessage({ type: \"SKIP_WAITING\" });\n}\n\n/**\n * Unregister all registered service workers for this origin.\n *\n * @returns Number of workers that were unregistered.\n */\nexport async function unregisterAllServiceWorkers(): Promise<number> {\n if (typeof navigator === \"undefined\" || !(\"serviceWorker\" in navigator)) return 0;\n const registrations = await navigator.serviceWorker.getRegistrations();\n let count = 0;\n for (const registration of registrations) {\n const result = await registration.unregister();\n if (result) count += 1;\n }\n return count;\n}\n","/**\n * Service-worker context helpers for handling `push` and `notificationclick`\n * events. Import these inside your own `sw.ts` — they expect to run in the\n * service-worker global scope, not in the main thread.\n *\n * @example\n * /// <reference lib=\"webworker\" />\n * import { installPushHandler, installNotificationClickHandler } from \"tempest-react-sdk\";\n *\n * installPushHandler({ defaultIcon: \"/icons/Logo.png\" });\n * installNotificationClickHandler();\n */\n\ninterface SwGlobal {\n registration: {\n showNotification(title: string, options?: NotificationOptions): Promise<void>;\n };\n clients: {\n matchAll(options: { type: \"window\"; includeUncontrolled?: boolean }): Promise<\n {\n url: string;\n focused: boolean;\n focus(): Promise<unknown>;\n navigate(url: string): Promise<unknown>;\n }[]\n >;\n openWindow(url: string): Promise<unknown>;\n };\n addEventListener(\n type: \"push\",\n listener: (event: {\n data: { json(): unknown; text(): string } | null;\n waitUntil(promise: Promise<unknown>): void;\n }) => void,\n ): void;\n addEventListener(\n type: \"notificationclick\",\n listener: (event: {\n notification: { close(): void; data?: unknown };\n waitUntil(promise: Promise<unknown>): void;\n }) => void,\n ): void;\n skipWaiting(): Promise<void>;\n}\n\nfunction getSwScope(): SwGlobal {\n return globalThis as unknown as SwGlobal;\n}\n\nexport interface PushPayload {\n title?: string;\n body?: string;\n icon?: string;\n badge?: string;\n image?: string;\n tag?: string;\n url?: string;\n /** Arbitrary extra data forwarded to `event.notification.data`. */\n data?: Record<string, unknown>;\n}\n\nexport interface InstallPushHandlerOptions {\n /** Title used when the payload omits one. */\n defaultTitle?: string;\n /** Icon used when the payload omits one. */\n defaultIcon?: string;\n /** Badge image (mobile). */\n defaultBadge?: string;\n /**\n * Transform the raw payload before showing the notification. Return `null`\n * to suppress the notification entirely (e.g. silent pings).\n */\n transform?: (payload: PushPayload) => PushPayload | null;\n}\n\n/**\n * Install a `push` event listener that parses the payload as JSON (with a\n * plain-text fallback) and shows a notification.\n */\nexport function installPushHandler(options: InstallPushHandlerOptions = {}): void {\n const sw = getSwScope();\n const { defaultTitle = \"Notificação\", defaultIcon, defaultBadge, transform } = options;\n\n sw.addEventListener(\"push\", (event) => {\n if (!event.data) return;\n\n let raw: PushPayload;\n try {\n raw = event.data.json() as PushPayload;\n } catch {\n raw = { title: defaultTitle, body: event.data.text() };\n }\n\n const payload = transform ? transform(raw) : raw;\n if (!payload) return;\n\n const title = payload.title ?? defaultTitle;\n const notification: NotificationOptions & { image?: string } = {\n body: payload.body,\n icon: payload.icon ?? defaultIcon,\n badge: payload.badge ?? defaultBadge,\n image: payload.image,\n tag: payload.tag,\n data: { url: payload.url ?? \"/\", ...(payload.data ?? {}) },\n };\n\n event.waitUntil(sw.registration.showNotification(title, notification));\n });\n}\n\nexport interface InstallNotificationClickHandlerOptions {\n /** Resolve the destination URL from the notification data. Default: `data.url`. */\n resolveUrl?: (data: unknown) => string;\n}\n\n/**\n * Install a `notificationclick` handler that focuses an existing client when\n * possible and falls back to opening a new window.\n */\nexport function installNotificationClickHandler(\n options: InstallNotificationClickHandlerOptions = {},\n): void {\n const sw = getSwScope();\n const resolveUrl =\n options.resolveUrl ??\n ((data: unknown) => {\n if (typeof data === \"string\") return data;\n if (data && typeof data === \"object\" && \"url\" in data) {\n const url = (data as Record<string, unknown>).url;\n return typeof url === \"string\" ? url : \"/\";\n }\n return \"/\";\n });\n\n sw.addEventListener(\"notificationclick\", (event) => {\n event.notification.close();\n const target = resolveUrl(event.notification.data);\n\n event.waitUntil(\n (async () => {\n const clients = await sw.clients.matchAll({\n type: \"window\",\n includeUncontrolled: true,\n });\n for (const client of clients) {\n if (client.url.includes(target)) {\n return client.focus();\n }\n }\n return sw.clients.openWindow(target);\n })(),\n );\n });\n}\n\n/**\n * Install a `message` listener that activates a waiting worker when the host\n * app sends `{ type: \"SKIP_WAITING\" }`.\n */\nexport function installSkipWaitingListener(): void {\n const sw = getSwScope() as SwGlobal & {\n addEventListener(\n type: \"message\",\n listener: (event: { data?: { type?: string } }) => void,\n ): void;\n };\n sw.addEventListener(\"message\", (event) => {\n if (event.data?.type === \"SKIP_WAITING\") {\n void sw.skipWaiting();\n }\n });\n}\n","/**\n * Service-worker caching helpers — a small, dependency-free subset of what\n * Workbox provides: precaching of the build's app shell (so the app launches\n * offline) plus runtime caching strategies for fonts, APIs and images.\n *\n * Import these inside your own `sw.ts`. They run in the service-worker global\n * scope, not the main thread. Pair `installPrecache` with the\n * `tempestPwaManifest()` Vite plugin (from `tempest-react-sdk/vite`), which\n * emits the `precache-manifest.json` this reads at install time.\n *\n * @example\n * /// <reference lib=\"webworker\" />\n * import { installRuntimeCache, installPrecache } from \"tempest-react-sdk/sw\";\n *\n * // Register specific routes FIRST so they win over the precache catch-all.\n * installRuntimeCache([\n * { match: /\\/api\\//, strategy: \"network-first\", cacheName: \"api\", maxAgeSeconds: 300 },\n * ]);\n * installPrecache();\n */\n\n/** Minimal shape of the events we touch, to avoid pulling in `lib.webworker`. */\ninterface ExtendableEventLike {\n waitUntil(promise: Promise<unknown>): void;\n}\n\ninterface FetchEventLike extends ExtendableEventLike {\n request: Request;\n respondWith(response: Response | Promise<Response>): void;\n}\n\ninterface CacheSwGlobal {\n addEventListener(type: \"install\", listener: (event: ExtendableEventLike) => void): void;\n addEventListener(type: \"activate\", listener: (event: ExtendableEventLike) => void): void;\n addEventListener(type: \"fetch\", listener: (event: FetchEventLike) => void): void;\n clients: { claim(): Promise<void> };\n skipWaiting(): Promise<void>;\n location: { origin: string };\n}\n\nfunction getSwScope(): CacheSwGlobal {\n return globalThis as unknown as CacheSwGlobal;\n}\n\n/** Caching strategy for a runtime route. Mirrors the common Workbox trio. */\nexport type RuntimeStrategy = \"cache-first\" | \"network-first\" | \"stale-while-revalidate\";\n\n/** A single runtime-caching rule, matched against each `GET` request. */\nexport interface RuntimeRoute {\n /** A `RegExp` tested against the full URL, or a predicate over the parsed URL. */\n match: RegExp | ((url: URL, request: Request) => boolean);\n /** How to resolve a match. */\n strategy: RuntimeStrategy;\n /** Cache bucket name for this route. */\n cacheName: string;\n /** Trim the cache to at most this many entries (FIFO) after each write. */\n maxEntries?: number;\n /** Treat a cached response older than this (seconds) as a miss. */\n maxAgeSeconds?: number;\n /** For `network-first`: fall back to cache after this timeout (seconds). */\n networkTimeoutSeconds?: number;\n /**\n * Serve HTTP `Range` requests (206 Partial Content) by slicing the cached\n * full response. Enable for audio/video so seeking works offline. The full\n * resource is cached once (the `Range` header is stripped before caching).\n */\n rangeRequests?: boolean;\n}\n\n/** Options for {@link installPrecache}. */\nexport interface InstallPrecacheOptions {\n /** URL of the manifest emitted by `tempestPwaManifest()`. Default `/precache-manifest.json`. */\n manifestUrl?: string;\n /** Cache name prefix; the manifest `version` is appended. Default `tempest-precache`. */\n cacheName?: string;\n /** App-shell document served for navigation requests offline. Default `/index.html`. */\n navigateFallback?: string;\n /** Navigation paths that should NOT use the fallback (e.g. `[/^\\/api\\//]`). */\n navigateFallbackDenylist?: RegExp[];\n /** Activate the new worker immediately after precaching. Default `true`. */\n skipWaiting?: boolean;\n}\n\ninterface PrecacheManifest {\n version: string;\n urls: string[];\n}\n\nlet precacheName = \"\";\nconst precachedPaths = new Set<string>();\n\n/** Whether a cached response has aged past `maxAgeSeconds` (best-effort, via `Date`). */\nfunction isExpired(response: Response, maxAgeSeconds?: number): boolean {\n if (!maxAgeSeconds) return false;\n const dateHeader = response.headers.get(\"date\");\n if (!dateHeader) return false;\n const age = (Date.now() - new Date(dateHeader).getTime()) / 1000;\n return age > maxAgeSeconds;\n}\n\n/** Drop oldest entries until the cache holds at most `maxEntries`. */\nasync function trimCache(cacheName: string, maxEntries?: number): Promise<void> {\n if (!maxEntries) return;\n const cache = await caches.open(cacheName);\n const keys = await cache.keys();\n if (keys.length <= maxEntries) return;\n for (const key of keys.slice(0, keys.length - maxEntries)) {\n await cache.delete(key);\n }\n}\n\nasync function cacheFirst(request: Request, route: RuntimeRoute): Promise<Response> {\n const cache = await caches.open(route.cacheName);\n const cached = await cache.match(request);\n if (cached && !isExpired(cached, route.maxAgeSeconds)) return cached;\n\n const response = await fetch(request);\n if (response.ok) {\n await cache.put(request, response.clone());\n await trimCache(route.cacheName, route.maxEntries);\n }\n return response;\n}\n\nasync function networkFirst(request: Request, route: RuntimeRoute): Promise<Response> {\n const cache = await caches.open(route.cacheName);\n\n const network = (async (): Promise<Response> => {\n const response = await fetch(request);\n if (response.ok) {\n await cache.put(request, response.clone());\n await trimCache(route.cacheName, route.maxEntries);\n }\n return response;\n })();\n\n const timeoutMs = (route.networkTimeoutSeconds ?? 0) * 1000;\n try {\n if (timeoutMs > 0) {\n const timeout = new Promise<never>((_, reject) =>\n setTimeout(() => reject(new Error(\"network-timeout\")), timeoutMs),\n );\n return await Promise.race([network, timeout]);\n }\n return await network;\n } catch {\n const cached = await cache.match(request);\n if (cached) return cached;\n throw new Error(\"network-first: no network and no cache\");\n }\n}\n\nasync function staleWhileRevalidate(request: Request, route: RuntimeRoute): Promise<Response> {\n const cache = await caches.open(route.cacheName);\n const cached = await cache.match(request);\n\n const network = fetch(request)\n .then(async (response) => {\n if (response.ok) {\n await cache.put(request, response.clone());\n await trimCache(route.cacheName, route.maxEntries);\n }\n return response;\n })\n .catch(() => undefined);\n\n if (cached && !isExpired(cached, route.maxAgeSeconds)) return cached;\n const response = await network;\n if (response) return response;\n if (cached) return cached;\n throw new Error(\"stale-while-revalidate: no network and no cache\");\n}\n\nfunction runRoute(request: Request, route: RuntimeRoute): Promise<Response> {\n switch (route.strategy) {\n case \"cache-first\":\n return cacheFirst(request, route);\n case \"network-first\":\n return networkFirst(request, route);\n case \"stale-while-revalidate\":\n return staleWhileRevalidate(request, route);\n }\n}\n\nfunction routeMatches(route: RuntimeRoute, url: URL, request: Request): boolean {\n return typeof route.match === \"function\"\n ? route.match(url, request)\n : route.match.test(url.href);\n}\n\n/**\n * Build a `206 Partial Content` response from a full one for an HTTP `Range`\n * request. Supports `bytes=start-end`, open-ended `bytes=start-` and suffix\n * `bytes=-suffixLength`. Returns the original response when there is no usable\n * `Range` header, or a `416` when the range is unsatisfiable.\n *\n * @param request The incoming request (its `Range` header drives the slice).\n * @param response The full (200) response to slice.\n */\nexport async function createPartialResponse(\n request: Request,\n response: Response,\n): Promise<Response> {\n const rangeHeader = request.headers.get(\"range\");\n if (!rangeHeader) return response;\n\n const match = /^bytes=(\\d*)-(\\d*)$/.exec(rangeHeader.trim());\n if (!match || (match[1] === \"\" && match[2] === \"\")) {\n return new Response(null, { status: 416, statusText: \"Range Not Satisfiable\" });\n }\n\n const buffer = await response.clone().arrayBuffer();\n const total = buffer.byteLength;\n\n let start: number;\n let end: number;\n if (match[1] === \"\") {\n // Suffix range: last N bytes.\n const suffix = Number(match[2]);\n start = Math.max(0, total - suffix);\n end = total - 1;\n } else {\n start = Number(match[1]);\n end = match[2] === \"\" ? total - 1 : Math.min(Number(match[2]), total - 1);\n }\n\n if (start > end || start >= total) {\n return new Response(null, {\n status: 416,\n statusText: \"Range Not Satisfiable\",\n headers: { \"Content-Range\": `bytes */${total}` },\n });\n }\n\n const slice = buffer.slice(start, end + 1);\n const headers = new Headers(response.headers);\n headers.set(\"Content-Range\", `bytes ${start}-${end}/${total}`);\n headers.set(\"Content-Length\", String(slice.byteLength));\n headers.set(\"Accept-Ranges\", \"bytes\");\n\n return new Response(slice, {\n status: 206,\n statusText: \"Partial Content\",\n headers,\n });\n}\n\n/**\n * Install a `fetch` handler that resolves matching `GET` requests with the\n * given runtime strategies. Non-matching requests are left untouched (no\n * `respondWith`), so a later {@link installPrecache} can handle them.\n *\n * Register this BEFORE `installPrecache` so specific routes win over the\n * precache catch-all.\n *\n * @param routes Ordered rules; the first whose `match` passes handles the request.\n */\nexport function installRuntimeCache(routes: RuntimeRoute[]): void {\n const sw = getSwScope();\n sw.addEventListener(\"fetch\", (event) => {\n const request = event.request;\n if (request.method !== \"GET\") return;\n\n const url = new URL(request.url);\n const route = routes.find((candidate) => routeMatches(candidate, url, request));\n if (!route) return;\n\n if (route.rangeRequests && request.headers.has(\"range\")) {\n // Cache/serve the FULL resource once (no Range), then slice it.\n const full = new Request(request.url, {\n headers: stripRange(request.headers),\n credentials: request.credentials,\n mode: request.mode === \"navigate\" ? \"same-origin\" : request.mode,\n });\n event.respondWith(\n runRoute(full, route).then((response) => createPartialResponse(request, response)),\n );\n return;\n }\n\n event.respondWith(runRoute(request, route));\n });\n}\n\n/** Copy headers without the `Range` header (so the cached entry is the full file). */\nfunction stripRange(headers: Headers): Headers {\n const out = new Headers(headers);\n out.delete(\"range\");\n return out;\n}\n\n/**\n * Precache the app shell at `install` and serve it offline:\n * - reads `precache-manifest.json` (emitted by `tempestPwaManifest()`),\n * - caches every listed URL under a versioned cache,\n * - on `activate`, deletes stale precache versions and claims open clients,\n * - on `fetch`, serves precached assets cache-first and falls back to the\n * `navigateFallback` document for offline navigations (SPA routing).\n *\n * Same-origin only. Register this LAST, after any {@link installRuntimeCache}.\n */\nexport function installPrecache(options: InstallPrecacheOptions = {}): void {\n const sw = getSwScope();\n const {\n manifestUrl = \"/precache-manifest.json\",\n cacheName = \"tempest-precache\",\n navigateFallback = \"/index.html\",\n navigateFallbackDenylist = [],\n skipWaiting = true,\n } = options;\n\n sw.addEventListener(\"install\", (event) => {\n event.waitUntil(\n (async () => {\n const response = await fetch(manifestUrl, { cache: \"no-cache\" });\n const manifest = (await response.json()) as PrecacheManifest;\n precacheName = `${cacheName}-${manifest.version}`;\n\n const cache = await caches.open(precacheName);\n await cache.addAll(manifest.urls);\n for (const url of manifest.urls) {\n precachedPaths.add(new URL(url, sw.location.origin).pathname);\n }\n if (skipWaiting) await sw.skipWaiting();\n })(),\n );\n });\n\n sw.addEventListener(\"activate\", (event) => {\n event.waitUntil(\n (async () => {\n const keys = await caches.keys();\n await Promise.all(\n keys\n .filter((key) => key.startsWith(`${cacheName}-`) && key !== precacheName)\n .map((key) => caches.delete(key)),\n );\n await sw.clients.claim();\n })(),\n );\n });\n\n sw.addEventListener(\"fetch\", (event) => {\n const request = event.request;\n if (request.method !== \"GET\") return;\n\n const url = new URL(request.url);\n if (url.origin !== sw.location.origin) return;\n\n // SPA navigations: serve the cached app shell when offline.\n if (request.mode === \"navigate\") {\n if (navigateFallbackDenylist.some((re) => re.test(url.pathname))) return;\n event.respondWith(\n (async () => {\n try {\n return await fetch(request);\n } catch {\n const cache = await caches.open(precacheName);\n const shell = await cache.match(navigateFallback);\n if (shell) return shell;\n throw new Error(\"offline and no cached app shell\");\n }\n })(),\n );\n return;\n }\n\n // Precached static assets: cache-first.\n if (precachedPaths.has(url.pathname)) {\n event.respondWith(\n (async () => {\n const cache = await caches.open(precacheName);\n const cached = await cache.match(request);\n return cached ?? fetch(request);\n })(),\n );\n }\n });\n}\n","/**\n * Background-sync helper: queue failed mutating requests (POST/PUT/PATCH/DELETE)\n * while offline and replay them when connectivity returns. A dependency-free\n * take on Workbox's `BackgroundSyncPlugin`, backed by a tiny IndexedDB queue.\n *\n * Import inside your `sw.ts`. Uses the Background Sync API (`registration.sync`)\n * when available, and also replays opportunistically on the next request as a\n * fallback for browsers without it (e.g. Safari).\n *\n * @example\n * import { installBackgroundSync } from \"tempest-react-sdk/sw\";\n *\n * installBackgroundSync({ match: (url) => url.pathname.startsWith(\"/api/\") });\n */\n\ninterface SyncEventLike {\n tag: string;\n waitUntil(promise: Promise<unknown>): void;\n}\n\ninterface BgFetchEventLike {\n request: Request;\n respondWith(response: Response | Promise<Response>): void;\n waitUntil(promise: Promise<unknown>): void;\n}\n\ninterface BgSwGlobal {\n registration: { sync?: { register(tag: string): Promise<void> } };\n addEventListener(type: \"sync\", listener: (event: SyncEventLike) => void): void;\n addEventListener(type: \"fetch\", listener: (event: BgFetchEventLike) => void): void;\n}\n\nfunction getSwScope(): BgSwGlobal {\n return globalThis as unknown as BgSwGlobal;\n}\n\n/** A serialized request stored in the queue. */\ninterface QueuedRequest {\n id?: number;\n url: string;\n method: string;\n headers: [string, string][];\n body: ArrayBuffer | null;\n timestamp: number;\n}\n\n/** Options for {@link installBackgroundSync}. */\nexport interface InstallBackgroundSyncOptions {\n /**\n * Which requests to queue on failure. A `RegExp` against the URL or a\n * predicate. Only non-`GET` requests are ever considered. Default: all\n * non-`GET` requests.\n */\n match?: RegExp | ((url: URL, request: Request) => boolean);\n /** IndexedDB database name, also used as the sync tag. Default `tempest-bg-sync`. */\n queueName?: string;\n /** Drop queued requests older than this (minutes) on replay. Default `1440` (24h). */\n maxRetentionMinutes?: number;\n}\n\nconst STORE = \"requests\";\n\nfunction openQueueDb(name: string): Promise<IDBDatabase> {\n return new Promise((resolve, reject) => {\n const request = indexedDB.open(name, 1);\n request.onupgradeneeded = () => {\n request.result.createObjectStore(STORE, { keyPath: \"id\", autoIncrement: true });\n };\n request.onsuccess = () => resolve(request.result);\n request.onerror = () => reject(request.error);\n });\n}\n\nfunction txDone(tx: IDBTransaction): Promise<void> {\n return new Promise((resolve, reject) => {\n tx.oncomplete = () => resolve();\n tx.onerror = () => reject(tx.error);\n tx.onabort = () => reject(tx.error);\n });\n}\n\nasync function enqueue(name: string, entry: QueuedRequest): Promise<void> {\n const db = await openQueueDb(name);\n const tx = db.transaction(STORE, \"readwrite\");\n tx.objectStore(STORE).add(entry);\n await txDone(tx);\n db.close();\n}\n\nasync function readAll(name: string): Promise<QueuedRequest[]> {\n const db = await openQueueDb(name);\n const tx = db.transaction(STORE, \"readonly\");\n const all = await new Promise<QueuedRequest[]>((resolve, reject) => {\n const req = tx.objectStore(STORE).getAll();\n req.onsuccess = () => resolve(req.result as QueuedRequest[]);\n req.onerror = () => reject(req.error);\n });\n db.close();\n return all;\n}\n\nasync function remove(name: string, id: number): Promise<void> {\n const db = await openQueueDb(name);\n const tx = db.transaction(STORE, \"readwrite\");\n tx.objectStore(STORE).delete(id);\n await txDone(tx);\n db.close();\n}\n\nasync function serializeRequest(request: Request, timestamp: number): Promise<QueuedRequest> {\n const buffer = await request.clone().arrayBuffer();\n return {\n url: request.url,\n method: request.method,\n headers: [...request.headers.entries()],\n body: buffer.byteLength > 0 ? buffer : null,\n timestamp,\n };\n}\n\nfunction deserializeRequest(entry: QueuedRequest): Request {\n return new Request(entry.url, {\n method: entry.method,\n headers: entry.headers,\n body: entry.body ?? undefined,\n });\n}\n\n/**\n * Replay every queued request once. Successful (or stale) entries are removed;\n * entries that fail again are kept for the next attempt. Throws if any entry\n * still fails, so a `sync` handler keeps the sync pending.\n */\nasync function replayQueue(name: string, maxRetentionMs: number, now: number): Promise<void> {\n const entries = await readAll(name);\n let pending = 0;\n\n for (const entry of entries) {\n if (entry.id === undefined) continue;\n if (now - entry.timestamp > maxRetentionMs) {\n await remove(name, entry.id);\n continue;\n }\n try {\n const response = await fetch(deserializeRequest(entry));\n if (response.ok || (response.status >= 400 && response.status < 500)) {\n // 2xx = done; 4xx = client error that won't fix itself → drop it.\n await remove(name, entry.id);\n } else {\n pending += 1;\n }\n } catch {\n pending += 1;\n }\n }\n\n if (pending > 0) throw new Error(`background-sync: ${pending} request(s) still pending`);\n}\n\nfunction matches(\n match: InstallBackgroundSyncOptions[\"match\"],\n url: URL,\n request: Request,\n): boolean {\n if (!match) return true;\n return typeof match === \"function\" ? match(url, request) : match.test(url.href);\n}\n\n/**\n * Install the background-sync queue: on a failed mutating request, the request\n * is serialized to IndexedDB and a sync is registered; the original fetch still\n * rejects (so your app can show an offline state), and the request is replayed\n * later when the network returns.\n */\nexport function installBackgroundSync(options: InstallBackgroundSyncOptions = {}): void {\n const sw = getSwScope();\n const { match, queueName = \"tempest-bg-sync\", maxRetentionMinutes = 1440 } = options;\n const maxRetentionMs = maxRetentionMinutes * 60 * 1000;\n\n sw.addEventListener(\"fetch\", (event) => {\n const request = event.request;\n if (request.method === \"GET\" || request.method === \"HEAD\") return;\n\n const url = new URL(request.url);\n if (!matches(match, url, request)) return;\n\n event.respondWith(\n fetch(request.clone()).catch(async (error) => {\n const entry = await serializeRequest(request, Date.now());\n await enqueue(queueName, entry);\n try {\n await sw.registration.sync?.register(queueName);\n } catch {\n // Background Sync API unavailable — opportunistic replay covers it.\n }\n throw error;\n }),\n );\n });\n\n sw.addEventListener(\"sync\", (event) => {\n if (event.tag !== queueName) return;\n event.waitUntil(replayQueue(queueName, maxRetentionMs, Date.now()));\n });\n\n // Fallback for browsers without the Background Sync API: whenever a GET\n // succeeds (a sign we're online), drain the queue opportunistically.\n sw.addEventListener(\"fetch\", (event) => {\n if (sw.registration.sync) return; // native sync will handle it\n if (event.request.method !== \"GET\") return;\n event.waitUntil(replayQueue(queueName, maxRetentionMs, Date.now()).catch(() => undefined));\n });\n}\n"],"names":["DEFAULT_UPDATE_INTERVAL_MS","controllerReloadWired","wireControllerReload","refreshing","registerServiceWorker","options","registration","installing","intervalMs","error","skipWaiting","worker","unregisterAllServiceWorkers","registrations","count","getSwScope","installPushHandler","sw","defaultTitle","defaultIcon","defaultBadge","transform","event","raw","payload","title","notification","installNotificationClickHandler","resolveUrl","data","url","target","clients","client","installSkipWaitingListener","precacheName","precachedPaths","isExpired","response","maxAgeSeconds","dateHeader","trimCache","cacheName","maxEntries","cache","keys","key","cacheFirst","request","route","cached","networkFirst","network","timeoutMs","timeout","_","reject","staleWhileRevalidate","runRoute","routeMatches","createPartialResponse","rangeHeader","match","buffer","total","start","end","suffix","slice","headers","installRuntimeCache","routes","candidate","full","stripRange","out","installPrecache","manifestUrl","navigateFallback","navigateFallbackDenylist","manifest","re","shell","STORE","openQueueDb","name","resolve","txDone","tx","enqueue","entry","db","readAll","all","req","remove","id","serializeRequest","timestamp","deserializeRequest","replayQueue","maxRetentionMs","now","entries","pending","matches","installBackgroundSync","queueName","maxRetentionMinutes"],"mappings":"gFAsCA,MAAMA,EAA6B,KAAU,IAE7C,IAAIC,EAAwB,GAE5B,SAASC,GAA6B,CAClC,GAAID,EAAuB,OAC3BA,EA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