Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions apps/dashboard/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
},
"prettier": "@sanity/prettier-config",
"dependencies": {
"@sanity/sdk": "workspace:*",
"@sanity/sdk-react": "workspace:*",
"@sanity/ui": "^2.15.13",
"react": "^18.3.1",
Expand Down
79 changes: 75 additions & 4 deletions apps/dashboard/src/App.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
import {createSubscriptionRequest, registerSubscription, unregisterSubscription} from '@sanity/sdk'
import {SanityApp, SanityConfig} from '@sanity/sdk-react'
import {Spinner, ThemeProvider} from '@sanity/ui'
import {buildTheme} from '@sanity/ui/theme'
import {type JSX, Suspense} from 'react'
import {type JSX, Suspense, useState} from 'react'

const theme = buildTheme({})

Expand All @@ -20,6 +21,78 @@ const devConfigs: SanityConfig[] = [
},
]

// SharedWorker test component
function SharedWorkerTest() {
const [subscriptionId, setSubscriptionId] = useState<string | null>(null)
const [status, setStatus] = useState<string>('Ready to test')

const testSubscription = async () => {
// eslint-disable-next-line no-console
console.log('testSubscription')
try {
setStatus('Testing subscription...')

const subscription = createSubscriptionRequest({
storeName: 'query',
projectId: 'ppsg7ml5',
dataset: 'test',
params: {
query: '*[_type == "movie"]',
options: {},
},
appId: 'dashboard-app',
})

const id = await registerSubscription(subscription)
setSubscriptionId(id)
setStatus(`Subscription registered: ${id}`)
} catch (error) {
setStatus(`Error: ${error instanceof Error ? error.message : String(error)}`)
}
}

const testUnsubscription = async () => {
if (!subscriptionId) return

try {
setStatus('Testing unsubscription...')

await unregisterSubscription(subscriptionId)
setSubscriptionId(null)
setStatus('Subscription unregistered successfully')
} catch (error) {
setStatus(`Error: ${error instanceof Error ? error.message : String(error)}`)
}
}

return (
<div style={{padding: 12, borderBottom: '1px solid #eee'}}>
<div>Dashboard (iframes sdk-app below)</div>
<div style={{marginTop: 8, fontSize: '14px'}}>
<div>SharedWorker Test:</div>
<div style={{marginTop: 4}}>
<button onClick={testSubscription} disabled={!!subscriptionId}>
Test Subscription
</button>
{subscriptionId && (
<button onClick={testUnsubscription} style={{marginLeft: 8}}>
Test Unsubscription
</button>
)}
</div>
<div style={{marginTop: 4, fontFamily: 'monospace', fontSize: '12px'}}>
Status: {status}
</div>
{subscriptionId && (
<div style={{marginTop: 4, fontFamily: 'monospace', fontSize: '12px'}}>
Active Subscription: {subscriptionId}
</div>
)}
</div>
</div>
)
}

export default function App(): JSX.Element {
return (
<ThemeProvider theme={theme}>
Expand All @@ -33,9 +106,7 @@ export default function App(): JSX.Element {
flexDirection: 'column',
}}
>
<div style={{padding: 12, borderBottom: '1px solid #eee'}}>
Dashboard (iframes sdk-app below)
</div>
<SharedWorkerTest />
<iframe
title="sdk-app"
src="http://localhost:3341/"
Expand Down
25 changes: 25 additions & 0 deletions apps/dashboard/src/main.tsx
Original file line number Diff line number Diff line change
@@ -1,8 +1,33 @@
import {addStatusListener, getSdkWorker, type WorkerStatus} from '@sanity/sdk'
import sdkWorker from '@sanity/sdk/worker?worker&url'
import {StrictMode} from 'react'
import {createRoot} from 'react-dom/client'

import App from './App'

// Initialize SharedWorker for subscription management
async function initializeSharedWorker() {
try {
// Get the SDK worker instance - use direct URL
const workerUrl = new URL(sdkWorker, import.meta.url).href

getSdkWorker(workerUrl)

// Add status listener for debugging
addStatusListener((status: WorkerStatus) => {
// eslint-disable-next-line no-console
console.log('[Dashboard] Worker status changed:', status)
})
} catch (error) {
// eslint-disable-next-line no-console
console.warn('Failed to initialize SharedWorker:', error)
// Fallback to local subscription management
}
}

// Initialize SharedWorker when the app starts
initializeSharedWorker()

createRoot(document.getElementById('root')!).render(
<StrictMode>
<App />
Expand Down
2 changes: 1 addition & 1 deletion knip.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -80,14 +80,14 @@
entry: ['src/index.ts', 'src/setup/**/*.ts', 'src/teardown/**/*.ts'],
ignoreDependencies: ['@repo/tsconfig'],
},
// TODO: Remove this once we have presence fully implemented in the SDK

Check warning on line 83 in knip.config.ts

View workflow job for this annotation

GitHub Actions / lint

Unexpected 'todo' comment: 'TODO: Remove this once we have presence...'

Check warning on line 83 in knip.config.ts

View workflow job for this annotation

GitHub Actions / lint

Unexpected 'todo' comment: 'TODO: Remove this once we have presence...'
'packages/core': {
typescript: {
config: 'tsconfig.settings.json',
},
project,
entry: ['package.bundle.ts'],
ignore: ['src/presence/bifurTransport.ts', 'src/presence/types.ts'],
ignore: ['src/presence/bifurTransport.ts', 'src/presence/types.ts', 'src/_exports/worker.ts'],
ignoreDependencies: ['@sanity/bifur-client', '@sanity/browserslist-config'],
},
},
Expand Down
22 changes: 22 additions & 0 deletions packages/core/src/_exports/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -132,6 +132,28 @@ export {
export {getPerspectiveState} from '../releases/getPerspectiveState'
export type {ReleaseDocument} from '../releases/releasesStore'
export {getActiveReleasesState} from '../releases/releasesStore'
export {
addStatusListener,
disconnectWorker,
getSdkWorker,
registerSubscription,
sendMessage,
unregisterSubscription,
type WorkerStatus,
} from '../sharedWorkerStore/sharedWorkerClient'
export {type SharedWorkerStore, sharedWorkerStore} from '../sharedWorkerStore/sharedWorkerStore'
export {
type ActiveSubscription,
type SharedWorkerStoreActions,
type SharedWorkerStoreState,
type SubscriptionRequest,
} from '../sharedWorkerStore/types'
export {
areSubscriptionsEquivalent,
createSubscriptionId,
createSubscriptionRequest,
groupSubscriptionsByParams,
} from '../sharedWorkerStore/utils/subscriptionManager'
export {createSanityInstance, type SanityInstance} from '../store/createSanityInstance'
export {type Selector, type StateSource} from '../store/createStateSourceAction'
export {getUsersKey, parseUsersKey} from '../users/reducers'
Expand Down
158 changes: 158 additions & 0 deletions packages/core/src/_exports/worker.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,158 @@
/// <reference lib="webworker" />
/* eslint-disable no-console */

/**
* @internal
* SharedWorker for managing subscriptions across SDK apps
*/

import {sharedWorkerStore} from '../sharedWorkerStore/sharedWorkerStore'
import {type SubscriptionRequest} from '../sharedWorkerStore/types'

declare const self: SharedWorkerGlobalScope

console.log('[SharedWorker] Worker script loaded')

// Handle new connections
self.onconnect = (event: MessageEvent) => {
const port = event.ports[0]

console.log('[SharedWorker] New connection established')

// Set up message handling for this port
port.onmessage = async (e: MessageEvent) => {
const {type, data} = e.data

console.log('[SharedWorker] Received message:', type, data)

try {
switch (type) {
case 'REGISTER_SUBSCRIPTION':
handleRegisterSubscription(data, port)
break
case 'UNREGISTER_SUBSCRIPTION':
handleUnregisterSubscription(data.subscriptionId, port)
break
case 'GET_SUBSCRIPTION_COUNT':
handleGetSubscriptionCount(port)
break
case 'GET_ALL_SUBSCRIPTIONS':
handleGetAllSubscriptions(port)
break
default:
console.warn('[SharedWorker] Unknown message type:', type)
port.postMessage({
type: 'ERROR',
data: {error: `Unknown message type: ${type}`},
})
}
} catch (error) {
console.error('[SharedWorker] Error handling message:', error)
port.postMessage({
type: 'ERROR',
data: {error: (error as Error).message},
})
}
}

// Start the port
port.start()
console.log('[SharedWorker] Port started, sending welcome message')
port.postMessage({type: 'welcome'})
}

/**
* @internal
* Handle the registration of a subscription
* @param subscription - The subscription to register
* @param port - The port to send the response to
*/
function handleRegisterSubscription(subscription: SubscriptionRequest, port: MessagePort): void {
try {
sharedWorkerStore.getState().registerSubscription(subscription)

// Send confirmation back to the client
port.postMessage({
type: 'SUBSCRIPTION_REGISTERED',
data: {subscriptionId: subscription.subscriptionId},
})

console.log('[SharedWorker] Registered subscription:', subscription.subscriptionId)
} catch (error) {
console.error('[SharedWorker] Failed to register subscription:', error)

// Send error back to the client
port.postMessage({
type: 'SUBSCRIPTION_ERROR',
data: {error: (error as Error).message, subscriptionId: subscription.subscriptionId},
})
}
}

/**
* @internal
* Handle the unregistration of a subscription
* @param subscriptionId - The ID of the subscription to unregister
* @param port - The port to send the response to
*/
function handleUnregisterSubscription(subscriptionId: string, port: MessagePort): void {
try {
sharedWorkerStore.getState().unregisterSubscription(subscriptionId)

// Send confirmation back to the client
port.postMessage({
type: 'SUBSCRIPTION_UNREGISTERED',
data: {subscriptionId},
})

console.log('[SharedWorker] Unregistered subscription:', subscriptionId)
} catch (error) {
console.error('[SharedWorker] Failed to unregister subscription:', error)

// Send error back to the client
port.postMessage({
type: 'SUBSCRIPTION_ERROR',
data: {error: (error as Error).message, subscriptionId},
})
}
}

function handleGetSubscriptionCount(port: MessagePort): void {
try {
const count = sharedWorkerStore.getState().getSubscriptionCount()

port.postMessage({
type: 'SUBSCRIPTION_COUNT',
data: {count},
})
} catch (error) {
console.error('[SharedWorker] Failed to get subscription count:', error)

port.postMessage({
type: 'SUBSCRIPTION_ERROR',
data: {error: (error as Error).message},
})
}
}

function handleGetAllSubscriptions(port: MessagePort): void {
try {
const subscriptions = sharedWorkerStore.getState().getAllSubscriptions()

port.postMessage({
type: 'ALL_SUBSCRIPTIONS',
data: {subscriptions},
})
} catch (error) {
console.error('[SharedWorker] Failed to get all subscriptions:', error)

port.postMessage({
type: 'SUBSCRIPTION_ERROR',
data: {error: (error as Error).message},
})
}
}

// Export for testing/development (this won't be used in the actual SharedWorker)
/** @internal */
export {handleRegisterSubscription, handleUnregisterSubscription}
Loading
Loading