portal-mojo 0.1.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/LICENSE +201 -0
- package/README.md +55 -0
- package/docs/DetailView.md +173 -0
- package/docs/ModelTable.md +128 -0
- package/docs/README.md +98 -0
- package/docs/admin-assistant.md +72 -0
- package/docs/admin-bouncer.md +120 -0
- package/docs/admin-cloudwatch.md +38 -0
- package/docs/admin-credentials.md +116 -0
- package/docs/admin-dashboard.md +15 -0
- package/docs/admin-devices-geoip.md +284 -0
- package/docs/admin-dns-certificates.md +122 -0
- package/docs/admin-dns-records.md +65 -0
- package/docs/admin-dns-registrar.md +33 -0
- package/docs/admin-dns.md +80 -0
- package/docs/admin-identity-users.md +103 -0
- package/docs/admin-incidents.md +71 -0
- package/docs/admin-jobs.md +426 -0
- package/docs/admin-members.md +112 -0
- package/docs/admin-messaging.md +56 -0
- package/docs/admin-metrics-explorer.md +63 -0
- package/docs/admin-monitoring.md +99 -0
- package/docs/admin-network-security.md +393 -0
- package/docs/admin-phonehub.md +27 -0
- package/docs/admin-push.md +36 -0
- package/docs/admin-rules.md +87 -0
- package/docs/admin-security-tickets.md +40 -0
- package/docs/admin-settings.md +78 -0
- package/docs/admin-shortlinks.md +32 -0
- package/docs/admin-storage.md +141 -0
- package/docs/auth-pages.md +212 -0
- package/docs/auth.md +58 -0
- package/docs/calendar.md +122 -0
- package/docs/charts.md +303 -0
- package/docs/client.md +206 -0
- package/docs/collection-multiselect.md +117 -0
- package/docs/collection-select.md +132 -0
- package/docs/combobox.md +105 -0
- package/docs/dataview.md +226 -0
- package/docs/datepicker.md +151 -0
- package/docs/daterange.md +170 -0
- package/docs/datetimepicker.md +249 -0
- package/docs/defineModel.md +72 -0
- package/docs/detail-primitives.md +174 -0
- package/docs/feedback.md +85 -0
- package/docs/file-upload-ux.md +146 -0
- package/docs/forms.md +435 -0
- package/docs/grouping-and-fmt.md +98 -0
- package/docs/idioms.md +112 -0
- package/docs/image-editor.md +101 -0
- package/docs/loading.md +242 -0
- package/docs/location-address.md +76 -0
- package/docs/markdown.md +203 -0
- package/docs/menus-and-access.md +89 -0
- package/docs/multiselect-dropdown.md +153 -0
- package/docs/params.md +73 -0
- package/docs/popover.md +130 -0
- package/docs/realtime.md +61 -0
- package/docs/record-feed.md +238 -0
- package/docs/right-panel.md +42 -0
- package/docs/tabs-and-form-wizard.md +60 -0
- package/docs/taginput.md +120 -0
- package/docs/timepicker.md +173 -0
- package/docs/timezone-select.md +147 -0
- package/docs/worldmap.md +302 -0
- package/package.json +55 -0
- package/src/admin/assistant/AssistantFeed.tsx +29 -0
- package/src/admin/assistant/AssistantPanel.tsx +65 -0
- package/src/admin/assistant/api.ts +17 -0
- package/src/admin/assistant/data.ts +63 -0
- package/src/admin/assistant/index.ts +21 -0
- package/src/admin/assistant/launchers.tsx +33 -0
- package/src/admin/assistant/pages.tsx +78 -0
- package/src/admin/assistant/streaming.ts +238 -0
- package/src/admin/assistant/types.ts +30 -0
- package/src/admin/bouncer/devices.tsx +230 -0
- package/src/admin/bouncer/index.ts +34 -0
- package/src/admin/bouncer/models.ts +199 -0
- package/src/admin/bouncer/signals.tsx +182 -0
- package/src/admin/bouncer/signatures.tsx +220 -0
- package/src/admin/cloudwatch/CloudWatchChart.tsx +61 -0
- package/src/admin/cloudwatch/CloudWatchDashboardPage.tsx +52 -0
- package/src/admin/cloudwatch/CloudWatchResourceDetail.tsx +33 -0
- package/src/admin/cloudwatch/data.ts +163 -0
- package/src/admin/cloudwatch/index.ts +16 -0
- package/src/admin/credentials/group-api-keys.tsx +433 -0
- package/src/admin/credentials/index.ts +4 -0
- package/src/admin/credentials/models.ts +244 -0
- package/src/admin/credentials/secret-dialog.tsx +77 -0
- package/src/admin/credentials/webhook-subscriptions.tsx +423 -0
- package/src/admin/dashboard/AdminDashboardPage.tsx +101 -0
- package/src/admin/dashboard/data.ts +60 -0
- package/src/admin/dashboard/index.ts +2 -0
- package/src/admin/dns/CertificateDetail.tsx +115 -0
- package/src/admin/dns/CertificateLifecyclePoller.tsx +141 -0
- package/src/admin/dns/CertificateRequestDialog.tsx +103 -0
- package/src/admin/dns/CertificatesPage.tsx +85 -0
- package/src/admin/dns/DnsRecordEditor.tsx +110 -0
- package/src/admin/dns/DnsRecordsPage.tsx +36 -0
- package/src/admin/dns/DnsRecordsPanel.tsx +71 -0
- package/src/admin/dns/DomainCertificatesSection.tsx +40 -0
- package/src/admin/dns/DomainDetail.tsx +41 -0
- package/src/admin/dns/DomainOnboardingDialog.tsx +27 -0
- package/src/admin/dns/DomainPurchaseDetail.tsx +11 -0
- package/src/admin/dns/DomainPurchaseWizard.tsx +112 -0
- package/src/admin/dns/DomainPurchasesPage.tsx +16 -0
- package/src/admin/dns/DomainsPage.tsx +27 -0
- package/src/admin/dns/ProviderCredentialsPage.tsx +304 -0
- package/src/admin/dns/RegistrantContactPage.tsx +42 -0
- package/src/admin/dns/api.ts +515 -0
- package/src/admin/dns/certificate-data.ts +221 -0
- package/src/admin/dns/data.ts +32 -0
- package/src/admin/dns/dns-data.ts +266 -0
- package/src/admin/dns/dns-integration.ts +24 -0
- package/src/admin/dns/domain-links.ts +37 -0
- package/src/admin/dns/index.ts +86 -0
- package/src/admin/dns/models.ts +418 -0
- package/src/admin/dns/purchase-data.ts +67 -0
- package/src/admin/dns/registrant-data.ts +52 -0
- package/src/admin/identity/index.ts +5 -0
- package/src/admin/identity/members/GroupMembersPanel.tsx +146 -0
- package/src/admin/identity/members/MemberDetail.tsx +226 -0
- package/src/admin/identity/members/MembersPage.tsx +144 -0
- package/src/admin/identity/members/index.ts +24 -0
- package/src/admin/identity/members/member-flows.tsx +132 -0
- package/src/admin/identity/members/models.ts +204 -0
- package/src/admin/identity/users/UserDetail.tsx +257 -0
- package/src/admin/identity/users/UsersPage.tsx +163 -0
- package/src/admin/identity/users/index.ts +27 -0
- package/src/admin/identity/users/models.ts +232 -0
- package/src/admin/identity/users/sections/ApiKeysSection.tsx +119 -0
- package/src/admin/identity/users/sections/AuditSection.tsx +190 -0
- package/src/admin/identity/users/sections/DevicesSection.tsx +140 -0
- package/src/admin/identity/users/sections/GroupsSection.tsx +64 -0
- package/src/admin/identity/users/sections/LoginsSection.tsx +106 -0
- package/src/admin/identity/users/sections/MetadataPanel.tsx +36 -0
- package/src/admin/identity/users/sections/NotificationsSection.tsx +117 -0
- package/src/admin/identity/users/sections/OAuthSection.tsx +72 -0
- package/src/admin/identity/users/sections/OverviewSection.tsx +109 -0
- package/src/admin/identity/users/sections/PermissionsSection.tsx +35 -0
- package/src/admin/identity/users/sections/PersonalSection.tsx +73 -0
- package/src/admin/identity/users/sections/ProfileSection.tsx +175 -0
- package/src/admin/identity/users/sections/SecuritySection.tsx +123 -0
- package/src/admin/identity/users/sections/actions.tsx +752 -0
- package/src/admin/identity/users/sections/permission-catalog.ts +138 -0
- package/src/admin/identity/users/sections/queries.ts +74 -0
- package/src/admin/identity/users/sections/shared.tsx +299 -0
- package/src/admin/incidents/EventDetail.tsx +43 -0
- package/src/admin/incidents/EventsPage.tsx +52 -0
- package/src/admin/incidents/IncidentDetail.tsx +68 -0
- package/src/admin/incidents/IncidentsPage.tsx +102 -0
- package/src/admin/incidents/forensics.tsx +73 -0
- package/src/admin/incidents/index.ts +16 -0
- package/src/admin/incidents/models.ts +113 -0
- package/src/admin/incidents/sanitize.ts +71 -0
- package/src/admin/index.ts +383 -0
- package/src/admin/jobs/JobDashboardPage.tsx +111 -0
- package/src/admin/jobs/JobDetail.tsx +721 -0
- package/src/admin/jobs/JobRunnersPage.tsx +216 -0
- package/src/admin/jobs/JobsTablePage.tsx +122 -0
- package/src/admin/jobs/RunnerDetail.tsx +576 -0
- package/src/admin/jobs/ScheduledTaskDetail.tsx +421 -0
- package/src/admin/jobs/ScheduledTasksPage.tsx +167 -0
- package/src/admin/jobs/columns.tsx +297 -0
- package/src/admin/jobs/control.ts +488 -0
- package/src/admin/jobs/index.ts +85 -0
- package/src/admin/jobs/models.ts +599 -0
- package/src/admin/jobs/queries.ts +272 -0
- package/src/admin/jobs/scheduled-task-form.tsx +493 -0
- package/src/admin/jobs/sections/JobChannelsPanel.tsx +142 -0
- package/src/admin/jobs/sections/JobOperationsSection.tsx +423 -0
- package/src/admin/jobs/sections/JobRunnersStrip.tsx +82 -0
- package/src/admin/jobs/sections/JobThroughputSection.tsx +118 -0
- package/src/admin/messaging/EmailDomainWizard.tsx +24 -0
- package/src/admin/messaging/EmailDomainsPage.tsx +17 -0
- package/src/admin/messaging/EmailTemplatesPage.tsx +13 -0
- package/src/admin/messaging/MailboxesPage.tsx +15 -0
- package/src/admin/messaging/PublicMessagesPage.tsx +13 -0
- package/src/admin/messaging/SandboxedEmailPreview.tsx +23 -0
- package/src/admin/messaging/SentMessagesPage.tsx +11 -0
- package/src/admin/messaging/api.ts +17 -0
- package/src/admin/messaging/data.ts +10 -0
- package/src/admin/messaging/index.ts +23 -0
- package/src/admin/messaging/models.ts +76 -0
- package/src/admin/messaging/push/PushPage.tsx +44 -0
- package/src/admin/messaging/push/api.ts +17 -0
- package/src/admin/messaging/push/index.ts +9 -0
- package/src/admin/messaging/push/models.ts +43 -0
- package/src/admin/messaging/sanitize.ts +44 -0
- package/src/admin/monitoring/LogInspector.tsx +160 -0
- package/src/admin/monitoring/LogsPage.tsx +135 -0
- package/src/admin/monitoring/MetricsExplorerPage.tsx +360 -0
- package/src/admin/monitoring/MetricsPermissionsPage.tsx +166 -0
- package/src/admin/monitoring/MetricsSourcePicker.tsx +136 -0
- package/src/admin/monitoring/index.ts +55 -0
- package/src/admin/monitoring/metrics-explorer-client.ts +229 -0
- package/src/admin/monitoring/metrics-explorer-data.ts +158 -0
- package/src/admin/monitoring/models.ts +155 -0
- package/src/admin/network/BlockedIPsPage.tsx +194 -0
- package/src/admin/network/BlockedIpDetail.tsx +262 -0
- package/src/admin/network/FirewallLogPage.tsx +115 -0
- package/src/admin/network/IPSetDetail.tsx +280 -0
- package/src/admin/network/IPSetEditor.tsx +191 -0
- package/src/admin/network/IPSetsPage.tsx +177 -0
- package/src/admin/network/geofence/BlocksTab.tsx +289 -0
- package/src/admin/network/geofence/ExemptionsTab.tsx +349 -0
- package/src/admin/network/geofence/GeofencingPage.tsx +119 -0
- package/src/admin/network/geofence/PostureHeader.tsx +184 -0
- package/src/admin/network/geofence/RuleEditor.tsx +176 -0
- package/src/admin/network/geofence/RulesTab.tsx +254 -0
- package/src/admin/network/geofence/SimulatorTab.tsx +281 -0
- package/src/admin/network/geofence/geofence-data.ts +674 -0
- package/src/admin/network/index.ts +68 -0
- package/src/admin/network/models.ts +607 -0
- package/src/admin/phonehub/PhoneHubPage.tsx +57 -0
- package/src/admin/phonehub/api.ts +47 -0
- package/src/admin/phonehub/data.ts +6 -0
- package/src/admin/phonehub/index.ts +10 -0
- package/src/admin/phonehub/models.ts +68 -0
- package/src/admin/rules/HandlerChainBuilder.tsx +51 -0
- package/src/admin/rules/RuleSetDetailPage.tsx +33 -0
- package/src/admin/rules/RuleSetsPage.tsx +33 -0
- package/src/admin/rules/editors.tsx +54 -0
- package/src/admin/rules/handler-dsl.ts +213 -0
- package/src/admin/rules/index.ts +13 -0
- package/src/admin/rules/models.ts +112 -0
- package/src/admin/security/devices/LoginEventDetail.tsx +123 -0
- package/src/admin/security/devices/LoginLocationMap.tsx +321 -0
- package/src/admin/security/devices/LoginLocationsPage.tsx +162 -0
- package/src/admin/security/devices/UserDeviceDetail.tsx +546 -0
- package/src/admin/security/devices/UserDeviceLocationDetail.tsx +272 -0
- package/src/admin/security/devices/UserDevicesPage.tsx +84 -0
- package/src/admin/security/devices/index.ts +40 -0
- package/src/admin/security/devices/models.ts +470 -0
- package/src/admin/security/geoip/GeoIpCachePage.tsx +135 -0
- package/src/admin/security/geoip/GeoIpDossier.tsx +804 -0
- package/src/admin/security/geoip/geoip-forms.ts +102 -0
- package/src/admin/security/geoip/index.ts +27 -0
- package/src/admin/security/geoip/models.ts +397 -0
- package/src/admin/security/index.ts +31 -0
- package/src/admin/security/models.ts +137 -0
- package/src/admin/security/tickets.tsx +562 -0
- package/src/admin/security-permissions.ts +5 -0
- package/src/admin/settings/SettingDetail.tsx +57 -0
- package/src/admin/settings/SettingEditor.tsx +157 -0
- package/src/admin/settings/SettingsPage.tsx +72 -0
- package/src/admin/settings/index.ts +19 -0
- package/src/admin/settings/model.ts +143 -0
- package/src/admin/shortlinks/ShortlinkDetail.tsx +55 -0
- package/src/admin/shortlinks/ShortlinkHistoryPage.tsx +18 -0
- package/src/admin/shortlinks/ShortlinksPage.tsx +59 -0
- package/src/admin/shortlinks/index.ts +18 -0
- package/src/admin/shortlinks/models.ts +246 -0
- package/src/admin/storage/BackendsPage.tsx +43 -0
- package/src/admin/storage/BucketDetail.tsx +77 -0
- package/src/admin/storage/BucketsPage.tsx +64 -0
- package/src/admin/storage/FileManagerDetail.tsx +36 -0
- package/src/admin/storage/FilePreview.tsx +54 -0
- package/src/admin/storage/FileUploadSurface.tsx +250 -0
- package/src/admin/storage/FileView.tsx +109 -0
- package/src/admin/storage/FilesPage.tsx +53 -0
- package/src/admin/storage/file-renditions.ts +99 -0
- package/src/admin/storage/index.ts +31 -0
- package/src/admin/storage/models.ts +585 -0
- package/src/admin/storage/storage-dialogs.tsx +80 -0
- package/src/charts/CircularProgress.tsx +281 -0
- package/src/charts/KPIStrip.tsx +162 -0
- package/src/charts/KPITile.tsx +125 -0
- package/src/charts/MetricsChart.tsx +459 -0
- package/src/charts/MetricsMiniWidget.tsx +588 -0
- package/src/charts/MiniChart.tsx +283 -0
- package/src/charts/PieChart.tsx +354 -0
- package/src/charts/SeriesChart.tsx +378 -0
- package/src/charts/chart-dialogs.tsx +149 -0
- package/src/charts/exportChart.ts +144 -0
- package/src/charts/index.ts +28 -0
- package/src/charts/pie-math.ts +127 -0
- package/src/charts/stats.ts +265 -0
- package/src/charts/worldmap/WorldMap.tsx +649 -0
- package/src/charts/worldmap/countryCentroids.ts +304 -0
- package/src/charts/worldmap/geo.ts +293 -0
- package/src/charts/worldmap/use-world-land.ts +47 -0
- package/src/charts/worldmap/world-land.ts +18 -0
- package/src/charts/worldmap/worldmap-data.ts +285 -0
- package/src/client/auth.ts +737 -0
- package/src/client/client.ts +268 -0
- package/src/client/duid.ts +31 -0
- package/src/client/errors.ts +33 -0
- package/src/client/group-context.ts +28 -0
- package/src/client/group.tsx +126 -0
- package/src/client/hooks.ts +50 -0
- package/src/client/index.ts +37 -0
- package/src/client/jwt.ts +75 -0
- package/src/client/location.ts +285 -0
- package/src/client/lookups.ts +41 -0
- package/src/client/markdown-fallback.tsx +115 -0
- package/src/client/markdown-parse.ts +386 -0
- package/src/client/markdown-sanitize.ts +217 -0
- package/src/client/markdown.ts +122 -0
- package/src/client/me.ts +188 -0
- package/src/client/mock.ts +9984 -0
- package/src/client/model.ts +227 -0
- package/src/client/params.ts +292 -0
- package/src/client/realtime-mock.ts +221 -0
- package/src/client/realtime.ts +561 -0
- package/src/client/record-feed.ts +329 -0
- package/src/client/safe-export.ts +71 -0
- package/src/client/types.ts +278 -0
- package/src/client/upload.ts +421 -0
- package/src/ui/AddressField.tsx +273 -0
- package/src/ui/AttachmentQueue.tsx +92 -0
- package/src/ui/CollectionMultiSelect.tsx +622 -0
- package/src/ui/CollectionSelect.tsx +517 -0
- package/src/ui/ComboBox.tsx +336 -0
- package/src/ui/DetailView.tsx +438 -0
- package/src/ui/FileDrop.tsx +194 -0
- package/src/ui/FileField.tsx +369 -0
- package/src/ui/FilterBar.tsx +269 -0
- package/src/ui/FormFields.tsx +77 -0
- package/src/ui/FormView.tsx +360 -0
- package/src/ui/FormWizard.tsx +336 -0
- package/src/ui/GroupSwitcher.tsx +202 -0
- package/src/ui/Guarded.tsx +16 -0
- package/src/ui/MarkdownView.tsx +89 -0
- package/src/ui/ModelTable.tsx +848 -0
- package/src/ui/MultiSelectDropdown.tsx +390 -0
- package/src/ui/Popover.tsx +204 -0
- package/src/ui/RecordFeed.tsx +627 -0
- package/src/ui/RequiresGroup.tsx +32 -0
- package/src/ui/RightPanel.tsx +107 -0
- package/src/ui/SidebarNav.tsx +330 -0
- package/src/ui/Tabs.tsx +161 -0
- package/src/ui/TagInput.tsx +381 -0
- package/src/ui/ThemeProvider.tsx +52 -0
- package/src/ui/UploadQueue.tsx +603 -0
- package/src/ui/armed-button.tsx +91 -0
- package/src/ui/date/Calendar.tsx +498 -0
- package/src/ui/date/DatePicker.tsx +289 -0
- package/src/ui/date/DateRangePicker.tsx +280 -0
- package/src/ui/date/DateTimePicker.tsx +587 -0
- package/src/ui/date/PresetRail.tsx +165 -0
- package/src/ui/date/TimePicker.tsx +624 -0
- package/src/ui/date/TimezoneSelect.tsx +267 -0
- package/src/ui/date/fns.ts +679 -0
- package/src/ui/detail/DataView.tsx +692 -0
- package/src/ui/detail/FlowStrip.tsx +80 -0
- package/src/ui/detail/KnownFieldsCard.tsx +121 -0
- package/src/ui/detail/MetadataSection.tsx +219 -0
- package/src/ui/detail/StackTraceView.tsx +150 -0
- package/src/ui/detail/StatusPanel.tsx +73 -0
- package/src/ui/detail/Timeline.tsx +52 -0
- package/src/ui/detail/index.ts +12 -0
- package/src/ui/field-registry.tsx +428 -0
- package/src/ui/field-wire.ts +322 -0
- package/src/ui/form-autosave.ts +583 -0
- package/src/ui/format.ts +444 -0
- package/src/ui/grouping.ts +150 -0
- package/src/ui/image-editor/ImageEditor.tsx +484 -0
- package/src/ui/image-editor/canvas.ts +254 -0
- package/src/ui/image-editor/index.ts +3 -0
- package/src/ui/image-editor/math.ts +416 -0
- package/src/ui/index.ts +58 -0
- package/src/ui/loading.tsx +604 -0
- package/src/ui/menu-registry.ts +213 -0
- package/src/ui/modal.tsx +297 -0
- package/src/ui/password.tsx +302 -0
- package/src/ui/schema-form-core.tsx +315 -0
- package/src/ui/toast.tsx +219 -0
- package/src/ui/ui.tsx +45 -0
|
@@ -0,0 +1,561 @@
|
|
|
1
|
+
import {
|
|
2
|
+
createContext, createElement, useCallback, useContext, useEffect, useMemo,
|
|
3
|
+
useSyncExternalStore, type PropsWithChildren,
|
|
4
|
+
} from 'react';
|
|
5
|
+
import { apiOrigin } from './client';
|
|
6
|
+
import { getAccessToken, subscribeAuth } from './auth';
|
|
7
|
+
|
|
8
|
+
export type RealtimeLifecycleStatus =
|
|
9
|
+
| 'disabled' | 'idle' | 'connecting' | 'authenticating' | 'ready'
|
|
10
|
+
| 'backoff' | 'auth-failed' | 'forced-disconnect';
|
|
11
|
+
export type RealtimeTopicStatus =
|
|
12
|
+
| 'idle' | 'subscribing' | 'subscribed' | 'unsubscribing' | 'denied';
|
|
13
|
+
|
|
14
|
+
export interface RealtimeStatusSnapshot {
|
|
15
|
+
status: RealtimeLifecycleStatus;
|
|
16
|
+
generation: number;
|
|
17
|
+
reconnectAttempt: number;
|
|
18
|
+
retryAt: number | null;
|
|
19
|
+
automaticUserTopic: string | null;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
export interface RealtimeEvent<T = unknown> {
|
|
23
|
+
type: string;
|
|
24
|
+
data: T;
|
|
25
|
+
topic?: string;
|
|
26
|
+
timestamp?: number;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
export interface RealtimeEventDefinition<T> {
|
|
30
|
+
readonly type: string;
|
|
31
|
+
readonly project: (value: unknown) => T | null;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
export function defineRealtimeEvent<T>(type: string, project: (value: unknown) => T | null): RealtimeEventDefinition<T> {
|
|
35
|
+
if (!type || typeof type !== 'string') throw new Error('Realtime event type is required');
|
|
36
|
+
return Object.freeze({ type, project });
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
export interface RealtimeSocket {
|
|
40
|
+
readonly readyState: number;
|
|
41
|
+
onopen: ((event: unknown) => void) | null;
|
|
42
|
+
onmessage: ((event: { data: unknown }) => void) | null;
|
|
43
|
+
onerror: ((event: unknown) => void) | null;
|
|
44
|
+
onclose: ((event: { code: number; reason?: string; wasClean?: boolean }) => void) | null;
|
|
45
|
+
send(data: string): void;
|
|
46
|
+
close(code?: number, reason?: string): void;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
export type RealtimeSocketFactory = (url: string) => RealtimeSocket;
|
|
50
|
+
|
|
51
|
+
export interface RealtimeClock {
|
|
52
|
+
now(): number;
|
|
53
|
+
random(): number;
|
|
54
|
+
setTimeout(callback: () => void, delay: number): unknown;
|
|
55
|
+
clearTimeout(handle: unknown): void;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
const browserClock: RealtimeClock = {
|
|
59
|
+
now: () => Date.now(),
|
|
60
|
+
random: () => Math.random(),
|
|
61
|
+
setTimeout: (callback, delay) => window.setTimeout(callback, delay),
|
|
62
|
+
clearTimeout: (handle) => window.clearTimeout(handle as number),
|
|
63
|
+
};
|
|
64
|
+
|
|
65
|
+
const defaultSocketFactory: RealtimeSocketFactory = (url) => new WebSocket(url) as unknown as RealtimeSocket;
|
|
66
|
+
|
|
67
|
+
interface TopicEntry {
|
|
68
|
+
refs: number;
|
|
69
|
+
status: RealtimeTopicStatus;
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
interface TopicOperation {
|
|
73
|
+
topic: string;
|
|
74
|
+
action: 'subscribe' | 'unsubscribe';
|
|
75
|
+
generation: number;
|
|
76
|
+
timeout: unknown | null;
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
export interface RealtimeClientOptions {
|
|
80
|
+
origin?: string;
|
|
81
|
+
socketFactory?: RealtimeSocketFactory;
|
|
82
|
+
clock?: RealtimeClock;
|
|
83
|
+
topicTimeoutMs?: number;
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
function deriveRealtimeUrl(origin: string): string {
|
|
87
|
+
const base = origin || (typeof window !== 'undefined' ? window.location.origin : 'http://localhost');
|
|
88
|
+
const url = new URL(base);
|
|
89
|
+
url.protocol = url.protocol === 'https:' ? 'wss:' : 'ws:';
|
|
90
|
+
url.pathname = '/ws/realtime/';
|
|
91
|
+
url.search = '';
|
|
92
|
+
url.hash = '';
|
|
93
|
+
return url.toString();
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
function object(value: unknown): Record<string, unknown> | null {
|
|
97
|
+
return value != null && typeof value === 'object' && !Array.isArray(value)
|
|
98
|
+
? value as Record<string, unknown> : null;
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
export class RealtimeClient {
|
|
102
|
+
readonly url: string;
|
|
103
|
+
private readonly socketFactory: RealtimeSocketFactory;
|
|
104
|
+
private readonly clock: RealtimeClock;
|
|
105
|
+
private readonly topicTimeoutMs: number;
|
|
106
|
+
private socket: RealtimeSocket | null = null;
|
|
107
|
+
private token: string | null = null;
|
|
108
|
+
private enabled = false;
|
|
109
|
+
private generation = 0;
|
|
110
|
+
private reconnectAttempt = 0;
|
|
111
|
+
private retryTimer: unknown | null = null;
|
|
112
|
+
private retryAt: number | null = null;
|
|
113
|
+
private extendedBackoffUntil = 0;
|
|
114
|
+
private heartbeatTimer: unknown | null = null;
|
|
115
|
+
private pongTimer: unknown | null = null;
|
|
116
|
+
private suspended: 'auth-failed' | 'forced-disconnect' | null = null;
|
|
117
|
+
private lifecycle: RealtimeLifecycleStatus = 'disabled';
|
|
118
|
+
private automaticUserTopic: string | null = null;
|
|
119
|
+
private statusSnapshot: RealtimeStatusSnapshot = {
|
|
120
|
+
status: 'disabled', generation: 0, reconnectAttempt: 0,
|
|
121
|
+
retryAt: null, automaticUserTopic: null,
|
|
122
|
+
};
|
|
123
|
+
private readonly topics = new Map<string, TopicEntry>();
|
|
124
|
+
private readonly topicQueue: Array<{ topic: string; action: 'subscribe' | 'unsubscribe' }> = [];
|
|
125
|
+
private topicOperation: TopicOperation | null = null;
|
|
126
|
+
private readonly statusListeners = new Set<() => void>();
|
|
127
|
+
private readonly topicListeners = new Map<string, Set<() => void>>();
|
|
128
|
+
private readonly eventListeners = new Map<string, Set<(event: RealtimeEvent) => void>>();
|
|
129
|
+
|
|
130
|
+
constructor(options: RealtimeClientOptions = {}) {
|
|
131
|
+
this.url = deriveRealtimeUrl(options.origin ?? apiOrigin());
|
|
132
|
+
this.socketFactory = options.socketFactory ?? defaultSocketFactory;
|
|
133
|
+
this.clock = options.clock ?? browserClock;
|
|
134
|
+
this.topicTimeoutMs = options.topicTimeoutMs ?? 10_000;
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
getStatus = (): RealtimeStatusSnapshot => this.statusSnapshot;
|
|
138
|
+
|
|
139
|
+
subscribeStatus = (listener: () => void): (() => void) => {
|
|
140
|
+
this.statusListeners.add(listener);
|
|
141
|
+
return () => this.statusListeners.delete(listener);
|
|
142
|
+
};
|
|
143
|
+
|
|
144
|
+
setEnabled(enabled: boolean): void {
|
|
145
|
+
if (this.enabled === enabled) return;
|
|
146
|
+
this.enabled = enabled;
|
|
147
|
+
if (!enabled) this.stop('disabled');
|
|
148
|
+
else if (this.token) this.open();
|
|
149
|
+
else this.setLifecycle('idle');
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
/** The only token comparison boundary. Equal token notifications are no-ops. */
|
|
153
|
+
setToken(token: string | null): void {
|
|
154
|
+
if (this.token === token) return;
|
|
155
|
+
this.token = token;
|
|
156
|
+
this.suspended = null;
|
|
157
|
+
this.stop(this.enabled && token ? 'idle' : this.enabled ? 'idle' : 'disabled');
|
|
158
|
+
if (this.enabled && token) this.open();
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
connect(token: string): void {
|
|
162
|
+
this.setToken(token);
|
|
163
|
+
this.setEnabled(true);
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
disconnect(): void {
|
|
167
|
+
this.enabled = false;
|
|
168
|
+
this.stop('disabled');
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
destroy(): void {
|
|
172
|
+
this.disconnect();
|
|
173
|
+
this.statusListeners.clear();
|
|
174
|
+
this.topicListeners.clear();
|
|
175
|
+
this.eventListeners.clear();
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
send(data: Record<string, unknown>): void {
|
|
179
|
+
if (this.lifecycle !== 'ready' || !this.socket) throw new Error('Realtime transport is not ready');
|
|
180
|
+
this.socket.send(JSON.stringify(data));
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
retainTopic(topic: string): () => void {
|
|
184
|
+
if (!topic || typeof topic !== 'string') throw new Error('Realtime topic is required');
|
|
185
|
+
const entry = this.topics.get(topic) ?? { refs: 0, status: 'idle' as const };
|
|
186
|
+
entry.refs += 1;
|
|
187
|
+
this.topics.set(topic, entry);
|
|
188
|
+
if (entry.refs === 1 && this.lifecycle === 'ready') this.enqueueTopic(topic, 'subscribe');
|
|
189
|
+
this.emitTopic(topic);
|
|
190
|
+
let released = false;
|
|
191
|
+
return () => {
|
|
192
|
+
if (released) return;
|
|
193
|
+
released = true;
|
|
194
|
+
const current = this.topics.get(topic);
|
|
195
|
+
if (!current) return;
|
|
196
|
+
current.refs = Math.max(0, current.refs - 1);
|
|
197
|
+
if (current.refs === 0) {
|
|
198
|
+
if (current.status === 'subscribed' && this.lifecycle === 'ready') this.enqueueTopic(topic, 'unsubscribe');
|
|
199
|
+
else if (current.status !== 'subscribing') this.topics.delete(topic);
|
|
200
|
+
}
|
|
201
|
+
this.emitTopic(topic);
|
|
202
|
+
};
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
topicStatus(topic: string): RealtimeTopicStatus {
|
|
206
|
+
return this.topics.get(topic)?.status ?? 'idle';
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
subscribeTopicStatus(topic: string, listener: () => void): () => void {
|
|
210
|
+
let listeners = this.topicListeners.get(topic);
|
|
211
|
+
if (!listeners) this.topicListeners.set(topic, (listeners = new Set()));
|
|
212
|
+
listeners.add(listener);
|
|
213
|
+
return () => {
|
|
214
|
+
listeners?.delete(listener);
|
|
215
|
+
if (listeners?.size === 0) this.topicListeners.delete(topic);
|
|
216
|
+
};
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
on<T>(definition: RealtimeEventDefinition<T>, listener: (event: RealtimeEvent<T>) => void): () => void {
|
|
220
|
+
const wrapped = (event: RealtimeEvent) => {
|
|
221
|
+
const projected = definition.project(event.data);
|
|
222
|
+
if (projected != null) listener({ ...event, data: projected });
|
|
223
|
+
};
|
|
224
|
+
let listeners = this.eventListeners.get(definition.type);
|
|
225
|
+
if (!listeners) this.eventListeners.set(definition.type, (listeners = new Set()));
|
|
226
|
+
listeners.add(wrapped);
|
|
227
|
+
return () => {
|
|
228
|
+
listeners?.delete(wrapped);
|
|
229
|
+
if (listeners?.size === 0) this.eventListeners.delete(definition.type);
|
|
230
|
+
};
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
nudge(): void {
|
|
234
|
+
if (!this.enabled || !this.token || this.suspended || this.socket || this.retryTimer == null) return;
|
|
235
|
+
if (this.clock.now() < this.extendedBackoffUntil) return;
|
|
236
|
+
this.clearRetry();
|
|
237
|
+
this.open();
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
private open(): void {
|
|
241
|
+
if (!this.enabled || !this.token || this.suspended || this.socket) return;
|
|
242
|
+
const run = this.generation;
|
|
243
|
+
this.setLifecycle('connecting');
|
|
244
|
+
let socket: RealtimeSocket;
|
|
245
|
+
try {
|
|
246
|
+
socket = this.socketFactory(this.url);
|
|
247
|
+
} catch {
|
|
248
|
+
this.scheduleReconnect(run, 0);
|
|
249
|
+
return;
|
|
250
|
+
}
|
|
251
|
+
this.socket = socket;
|
|
252
|
+
socket.onopen = () => {
|
|
253
|
+
if (!this.isCurrent(run, socket)) return;
|
|
254
|
+
this.setLifecycle('authenticating');
|
|
255
|
+
};
|
|
256
|
+
socket.onmessage = (event) => {
|
|
257
|
+
if (!this.isCurrent(run, socket)) return;
|
|
258
|
+
this.handleFrame(event.data, run, socket);
|
|
259
|
+
};
|
|
260
|
+
socket.onerror = () => { /* close is the single retry path */ };
|
|
261
|
+
socket.onclose = (event) => {
|
|
262
|
+
if (!this.isCurrent(run, socket)) return;
|
|
263
|
+
this.socket = null;
|
|
264
|
+
this.clearHeartbeat();
|
|
265
|
+
this.resetTopicConnectionState();
|
|
266
|
+
if (event.code === 4429) this.extendedBackoffUntil = this.clock.now() + 60_000;
|
|
267
|
+
if (this.enabled && this.token && !this.suspended) this.scheduleReconnect(run, event.code);
|
|
268
|
+
};
|
|
269
|
+
}
|
|
270
|
+
|
|
271
|
+
private handleFrame(raw: unknown, run: number, socket: RealtimeSocket): void {
|
|
272
|
+
if (typeof raw !== 'string') return;
|
|
273
|
+
let parsed: unknown;
|
|
274
|
+
try { parsed = JSON.parse(raw); } catch { return; }
|
|
275
|
+
const frame = object(parsed);
|
|
276
|
+
if (!frame || typeof frame.type !== 'string') return;
|
|
277
|
+
|
|
278
|
+
if (frame.type === 'auth_required') {
|
|
279
|
+
if (this.lifecycle !== 'authenticating' || !this.token) return;
|
|
280
|
+
socket.send(JSON.stringify({ type: 'authenticate', token: this.token, prefix: 'bearer' }));
|
|
281
|
+
return;
|
|
282
|
+
}
|
|
283
|
+
if (frame.type === 'auth_success') {
|
|
284
|
+
if (this.lifecycle !== 'authenticating') return;
|
|
285
|
+
this.reconnectAttempt = 0;
|
|
286
|
+
this.extendedBackoffUntil = 0;
|
|
287
|
+
this.automaticUserTopic = (typeof frame.user_type === 'string' && (typeof frame.user_id === 'number' || typeof frame.user_id === 'string'))
|
|
288
|
+
? `${frame.user_type}:${frame.user_id}` : null;
|
|
289
|
+
this.setLifecycle('ready');
|
|
290
|
+
this.startHeartbeat(run, socket);
|
|
291
|
+
this.replayTopics();
|
|
292
|
+
return;
|
|
293
|
+
}
|
|
294
|
+
if (frame.type === 'pong') {
|
|
295
|
+
if (this.lifecycle === 'ready') this.clearPong();
|
|
296
|
+
return;
|
|
297
|
+
}
|
|
298
|
+
if (frame.type === 'subscribed' || frame.type === 'unsubscribed') {
|
|
299
|
+
if (typeof frame.topic === 'string') this.completeTopic(frame.type, frame.topic);
|
|
300
|
+
return;
|
|
301
|
+
}
|
|
302
|
+
if (frame.type === 'error') {
|
|
303
|
+
if (this.lifecycle === 'authenticating') {
|
|
304
|
+
this.suspend('auth-failed', 4003, 'Authentication failed');
|
|
305
|
+
} else if (this.topicOperation) {
|
|
306
|
+
this.denyCurrentTopic();
|
|
307
|
+
}
|
|
308
|
+
return;
|
|
309
|
+
}
|
|
310
|
+
|
|
311
|
+
if (frame.type === 'message') {
|
|
312
|
+
const data = object(frame.data);
|
|
313
|
+
if (!data || typeof data.type !== 'string') return;
|
|
314
|
+
if (this.isTrustedForcedDisconnect(frame, data)) {
|
|
315
|
+
this.suspend('forced-disconnect', 4003, 'Forced disconnect');
|
|
316
|
+
return;
|
|
317
|
+
}
|
|
318
|
+
this.dispatch(data.type, data, typeof frame.topic === 'string' ? frame.topic : undefined,
|
|
319
|
+
typeof frame.timestamp === 'number' && Number.isFinite(frame.timestamp) ? frame.timestamp : undefined);
|
|
320
|
+
return;
|
|
321
|
+
}
|
|
322
|
+
|
|
323
|
+
// Direct application frame. Framework frames above never leak here.
|
|
324
|
+
this.dispatch(frame.type, frame);
|
|
325
|
+
}
|
|
326
|
+
|
|
327
|
+
private isTrustedForcedDisconnect(wrapper: Record<string, unknown>, data: Record<string, unknown>): boolean {
|
|
328
|
+
return wrapper.type === 'message'
|
|
329
|
+
&& wrapper.topic === undefined
|
|
330
|
+
&& typeof wrapper.timestamp === 'number' && Number.isFinite(wrapper.timestamp)
|
|
331
|
+
&& Object.keys(data).length === 2
|
|
332
|
+
&& data.type === 'disconnect' && data.reason === 'forced_disconnect';
|
|
333
|
+
}
|
|
334
|
+
|
|
335
|
+
private dispatch(type: string, data: Record<string, unknown>, topic?: string, timestamp?: number): void {
|
|
336
|
+
const event: RealtimeEvent = { type, data, ...(topic ? { topic } : {}), ...(timestamp != null ? { timestamp } : {}) };
|
|
337
|
+
this.eventListeners.get(type)?.forEach((listener) => listener(event));
|
|
338
|
+
}
|
|
339
|
+
|
|
340
|
+
private enqueueTopic(topic: string, action: 'subscribe' | 'unsubscribe'): void {
|
|
341
|
+
if (this.topicQueue.some((op) => op.topic === topic && op.action === action)
|
|
342
|
+
|| (this.topicOperation?.topic === topic && this.topicOperation.action === action)) return;
|
|
343
|
+
this.topicQueue.push({ topic, action });
|
|
344
|
+
this.pumpTopicQueue();
|
|
345
|
+
}
|
|
346
|
+
|
|
347
|
+
private pumpTopicQueue(): void {
|
|
348
|
+
if (this.topicOperation || this.lifecycle !== 'ready' || !this.socket) return;
|
|
349
|
+
const next = this.topicQueue.shift();
|
|
350
|
+
if (!next) return;
|
|
351
|
+
const entry = this.topics.get(next.topic);
|
|
352
|
+
if (!entry || (next.action === 'subscribe' && entry.refs === 0)) {
|
|
353
|
+
this.pumpTopicQueue();
|
|
354
|
+
return;
|
|
355
|
+
}
|
|
356
|
+
entry.status = next.action === 'subscribe' ? 'subscribing' : 'unsubscribing';
|
|
357
|
+
this.emitTopic(next.topic);
|
|
358
|
+
const operation: TopicOperation = { ...next, generation: this.generation, timeout: null };
|
|
359
|
+
this.topicOperation = operation;
|
|
360
|
+
this.socket.send(JSON.stringify({ type: next.action, topic: next.topic }));
|
|
361
|
+
operation.timeout = this.clock.setTimeout(() => {
|
|
362
|
+
if (this.topicOperation !== operation) return;
|
|
363
|
+
if (entry) entry.status = next.action === 'subscribe' ? 'denied' : 'subscribed';
|
|
364
|
+
this.topicOperation = null;
|
|
365
|
+
this.emitTopic(next.topic);
|
|
366
|
+
this.pumpTopicQueue();
|
|
367
|
+
}, this.topicTimeoutMs);
|
|
368
|
+
}
|
|
369
|
+
|
|
370
|
+
private completeTopic(type: 'subscribed' | 'unsubscribed', topic: string): void {
|
|
371
|
+
const operation = this.topicOperation;
|
|
372
|
+
if (!operation || operation.topic !== topic || operation.action !== (type === 'subscribed' ? 'subscribe' : 'unsubscribe')) return;
|
|
373
|
+
if (operation.timeout != null) this.clock.clearTimeout(operation.timeout);
|
|
374
|
+
const entry = this.topics.get(topic);
|
|
375
|
+
if (entry) {
|
|
376
|
+
entry.status = type === 'subscribed' ? 'subscribed' : 'idle';
|
|
377
|
+
if (entry.refs === 0 && type === 'unsubscribed') this.topics.delete(topic);
|
|
378
|
+
}
|
|
379
|
+
this.topicOperation = null;
|
|
380
|
+
this.emitTopic(topic);
|
|
381
|
+
if (entry?.refs === 0 && type === 'subscribed') this.enqueueTopic(topic, 'unsubscribe');
|
|
382
|
+
this.pumpTopicQueue();
|
|
383
|
+
}
|
|
384
|
+
|
|
385
|
+
private denyCurrentTopic(): void {
|
|
386
|
+
const operation = this.topicOperation;
|
|
387
|
+
if (!operation) return;
|
|
388
|
+
if (operation.timeout != null) this.clock.clearTimeout(operation.timeout);
|
|
389
|
+
const entry = this.topics.get(operation.topic);
|
|
390
|
+
if (entry) entry.status = operation.action === 'subscribe' ? 'denied' : 'subscribed';
|
|
391
|
+
this.topicOperation = null;
|
|
392
|
+
this.emitTopic(operation.topic);
|
|
393
|
+
this.pumpTopicQueue();
|
|
394
|
+
}
|
|
395
|
+
|
|
396
|
+
private replayTopics(): void {
|
|
397
|
+
for (const [topic, entry] of this.topics) {
|
|
398
|
+
if (entry.refs > 0) {
|
|
399
|
+
entry.status = 'idle';
|
|
400
|
+
this.enqueueTopic(topic, 'subscribe');
|
|
401
|
+
}
|
|
402
|
+
}
|
|
403
|
+
}
|
|
404
|
+
|
|
405
|
+
private resetTopicConnectionState(): void {
|
|
406
|
+
if (this.topicOperation?.timeout != null) this.clock.clearTimeout(this.topicOperation.timeout);
|
|
407
|
+
this.topicOperation = null;
|
|
408
|
+
this.topicQueue.length = 0;
|
|
409
|
+
for (const [topic, entry] of this.topics) {
|
|
410
|
+
if (entry.refs > 0) entry.status = 'idle';
|
|
411
|
+
else this.topics.delete(topic);
|
|
412
|
+
this.emitTopic(topic);
|
|
413
|
+
}
|
|
414
|
+
}
|
|
415
|
+
|
|
416
|
+
private startHeartbeat(run: number, socket: RealtimeSocket): void {
|
|
417
|
+
this.clearHeartbeat();
|
|
418
|
+
const ping = () => {
|
|
419
|
+
if (!this.isCurrent(run, socket) || this.lifecycle !== 'ready') return;
|
|
420
|
+
socket.send(JSON.stringify({ type: 'ping' }));
|
|
421
|
+
this.clearPong();
|
|
422
|
+
this.pongTimer = this.clock.setTimeout(() => {
|
|
423
|
+
if (this.isCurrent(run, socket)) socket.close(4001, 'Pong timeout');
|
|
424
|
+
}, 10_000);
|
|
425
|
+
this.heartbeatTimer = this.clock.setTimeout(ping, 20_000);
|
|
426
|
+
};
|
|
427
|
+
this.heartbeatTimer = this.clock.setTimeout(ping, 20_000);
|
|
428
|
+
}
|
|
429
|
+
|
|
430
|
+
private scheduleReconnect(run: number, closeCode: number): void {
|
|
431
|
+
if (run !== this.generation || this.retryTimer != null || this.suspended) return;
|
|
432
|
+
this.reconnectAttempt += 1;
|
|
433
|
+
const normal = Math.min(2_000 * Math.pow(1.5, this.reconnectAttempt - 1), 30_000);
|
|
434
|
+
const jittered = Math.round(normal * (0.8 + this.clock.random() * 0.4));
|
|
435
|
+
const extended = closeCode === 4429 ? Math.max(jittered, 60_000) : jittered;
|
|
436
|
+
const delay = Math.max(extended, this.extendedBackoffUntil - this.clock.now());
|
|
437
|
+
this.retryAt = this.clock.now() + delay;
|
|
438
|
+
this.setLifecycle('backoff');
|
|
439
|
+
this.retryTimer = this.clock.setTimeout(() => {
|
|
440
|
+
this.retryTimer = null;
|
|
441
|
+
this.retryAt = null;
|
|
442
|
+
if (run === this.generation) this.open();
|
|
443
|
+
}, delay);
|
|
444
|
+
}
|
|
445
|
+
|
|
446
|
+
private suspend(reason: 'auth-failed' | 'forced-disconnect', code: number, message: string): void {
|
|
447
|
+
this.suspended = reason;
|
|
448
|
+
this.setLifecycle(reason);
|
|
449
|
+
const socket = this.socket;
|
|
450
|
+
this.socket = null;
|
|
451
|
+
this.clearHeartbeat();
|
|
452
|
+
this.resetTopicConnectionState();
|
|
453
|
+
if (socket) socket.close(code, message);
|
|
454
|
+
}
|
|
455
|
+
|
|
456
|
+
private stop(status: RealtimeLifecycleStatus): void {
|
|
457
|
+
this.generation += 1;
|
|
458
|
+
this.clearRetry();
|
|
459
|
+
this.clearHeartbeat();
|
|
460
|
+
this.resetTopicConnectionState();
|
|
461
|
+
this.automaticUserTopic = null;
|
|
462
|
+
const socket = this.socket;
|
|
463
|
+
this.socket = null;
|
|
464
|
+
if (socket) socket.close(1000, 'Client disconnect');
|
|
465
|
+
this.setLifecycle(status);
|
|
466
|
+
}
|
|
467
|
+
|
|
468
|
+
private clearRetry(): void {
|
|
469
|
+
if (this.retryTimer != null) this.clock.clearTimeout(this.retryTimer);
|
|
470
|
+
this.retryTimer = null;
|
|
471
|
+
this.retryAt = null;
|
|
472
|
+
}
|
|
473
|
+
|
|
474
|
+
private clearPong(): void {
|
|
475
|
+
if (this.pongTimer != null) this.clock.clearTimeout(this.pongTimer);
|
|
476
|
+
this.pongTimer = null;
|
|
477
|
+
}
|
|
478
|
+
|
|
479
|
+
private clearHeartbeat(): void {
|
|
480
|
+
if (this.heartbeatTimer != null) this.clock.clearTimeout(this.heartbeatTimer);
|
|
481
|
+
this.heartbeatTimer = null;
|
|
482
|
+
this.clearPong();
|
|
483
|
+
}
|
|
484
|
+
|
|
485
|
+
private isCurrent(run: number, socket: RealtimeSocket): boolean {
|
|
486
|
+
return run === this.generation && socket === this.socket;
|
|
487
|
+
}
|
|
488
|
+
|
|
489
|
+
private setLifecycle(status: RealtimeLifecycleStatus): void {
|
|
490
|
+
this.lifecycle = status;
|
|
491
|
+
this.statusSnapshot = {
|
|
492
|
+
status,
|
|
493
|
+
generation: this.generation,
|
|
494
|
+
reconnectAttempt: this.reconnectAttempt,
|
|
495
|
+
retryAt: this.retryAt,
|
|
496
|
+
automaticUserTopic: this.automaticUserTopic,
|
|
497
|
+
};
|
|
498
|
+
this.statusListeners.forEach((listener) => listener());
|
|
499
|
+
}
|
|
500
|
+
|
|
501
|
+
private emitTopic(topic: string): void {
|
|
502
|
+
this.topicListeners.get(topic)?.forEach((listener) => listener());
|
|
503
|
+
}
|
|
504
|
+
}
|
|
505
|
+
|
|
506
|
+
const RealtimeContext = createContext<RealtimeClient | null>(null);
|
|
507
|
+
|
|
508
|
+
export type RealtimeProviderProps = PropsWithChildren<{
|
|
509
|
+
enabled?: boolean;
|
|
510
|
+
client?: RealtimeClient;
|
|
511
|
+
socketFactory?: RealtimeSocketFactory;
|
|
512
|
+
origin?: string;
|
|
513
|
+
}>;
|
|
514
|
+
|
|
515
|
+
export function RealtimeProvider({ children, enabled = true, client, socketFactory, origin }: RealtimeProviderProps) {
|
|
516
|
+
const owned = useMemo(() => client ?? new RealtimeClient({ socketFactory, origin }), [client, socketFactory, origin]);
|
|
517
|
+
const token = useSyncExternalStore(subscribeAuth, getAccessToken, getAccessToken);
|
|
518
|
+
useEffect(() => { owned.setToken(token); }, [owned, token]);
|
|
519
|
+
useEffect(() => {
|
|
520
|
+
owned.setEnabled(enabled);
|
|
521
|
+
return () => owned.setEnabled(false);
|
|
522
|
+
}, [owned, enabled]);
|
|
523
|
+
useEffect(() => () => { if (!client) owned.destroy(); }, [client, owned]);
|
|
524
|
+
useEffect(() => {
|
|
525
|
+
const nudge = () => owned.nudge();
|
|
526
|
+
const visibility = () => { if (!document.hidden) owned.nudge(); };
|
|
527
|
+
window.addEventListener('focus', nudge);
|
|
528
|
+
document.addEventListener('visibilitychange', visibility);
|
|
529
|
+
return () => {
|
|
530
|
+
window.removeEventListener('focus', nudge);
|
|
531
|
+
document.removeEventListener('visibilitychange', visibility);
|
|
532
|
+
};
|
|
533
|
+
}, [owned]);
|
|
534
|
+
return createElement(RealtimeContext.Provider, { value: owned }, children);
|
|
535
|
+
}
|
|
536
|
+
|
|
537
|
+
export function useRealtime(): RealtimeClient {
|
|
538
|
+
const client = useContext(RealtimeContext);
|
|
539
|
+
if (!client) throw new Error('useRealtime must be used inside RealtimeProvider');
|
|
540
|
+
return client;
|
|
541
|
+
}
|
|
542
|
+
|
|
543
|
+
export function useRealtimeStatus(): RealtimeStatusSnapshot {
|
|
544
|
+
const client = useRealtime();
|
|
545
|
+
return useSyncExternalStore(client.subscribeStatus, client.getStatus, client.getStatus);
|
|
546
|
+
}
|
|
547
|
+
|
|
548
|
+
export function useRealtimeTopic(topic: string | null | undefined): RealtimeTopicStatus {
|
|
549
|
+
const client = useRealtime();
|
|
550
|
+
useEffect(() => topic ? client.retainTopic(topic) : undefined, [client, topic]);
|
|
551
|
+
return useSyncExternalStore(
|
|
552
|
+
useCallback((listener) => topic ? client.subscribeTopicStatus(topic, listener) : () => {}, [client, topic]),
|
|
553
|
+
useCallback(() => topic ? client.topicStatus(topic) : 'idle', [client, topic]),
|
|
554
|
+
() => 'idle',
|
|
555
|
+
);
|
|
556
|
+
}
|
|
557
|
+
|
|
558
|
+
export function useRealtimeEvent<T>(definition: RealtimeEventDefinition<T>, listener: (event: RealtimeEvent<T>) => void): void {
|
|
559
|
+
const client = useRealtime();
|
|
560
|
+
useEffect(() => client.on(definition, listener), [client, definition, listener]);
|
|
561
|
+
}
|