@burdenoff/microfe-planmagnet 2026.930.18 → 2026.930.20
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/dist/index.js +2 -1
- package/dist/planmagnet/PlanMagnetRoutes.d.ts.map +1 -1
- package/dist/planmagnet/PlanMagnetRoutes.js +17 -5
- package/dist/planmagnet/PlanMagnetRoutes.js.map +1 -1
- package/dist/planmagnet/controls/SyncControls.d.ts +101 -0
- package/dist/planmagnet/controls/SyncControls.d.ts.map +1 -0
- package/dist/planmagnet/controls/SyncControls.js +616 -0
- package/dist/planmagnet/controls/SyncControls.js.map +1 -0
- package/dist/planmagnet/hooks/useLiveRefresh.d.ts.map +1 -1
- package/dist/planmagnet/hooks/useLiveRefresh.js +47 -46
- package/dist/planmagnet/hooks/useLiveRefresh.js.map +1 -1
- package/dist/planmagnet/index.d.ts +1 -0
- package/dist/planmagnet/index.d.ts.map +1 -1
- package/dist/planmagnet/index.js +1 -0
- package/dist/planmagnet/integrations/routes.d.ts +13 -0
- package/dist/planmagnet/integrations/routes.d.ts.map +1 -0
- package/dist/planmagnet/integrations/routes.js +9 -0
- package/dist/planmagnet/integrations/routes.js.map +1 -0
- package/dist/planmagnet/integrations/syncTypes.d.ts +143 -0
- package/dist/planmagnet/integrations/syncTypes.d.ts.map +1 -0
- package/dist/planmagnet/integrations/syncTypes.js +71 -0
- package/dist/planmagnet/integrations/syncTypes.js.map +1 -0
- package/dist/planmagnet/integrations/useSyncProviderCapabilities.d.ts +8 -0
- package/dist/planmagnet/integrations/useSyncProviderCapabilities.d.ts.map +1 -0
- package/dist/planmagnet/integrations/useSyncProviderCapabilities.js +27 -0
- package/dist/planmagnet/integrations/useSyncProviderCapabilities.js.map +1 -0
- package/dist/planmagnet/pages/DocsDocDetailPagePage.js +1 -1
- package/dist/planmagnet/pages/IntegrationsNewSyncPagePage.d.ts +2 -0
- package/dist/planmagnet/pages/IntegrationsNewSyncPagePage.d.ts.map +1 -0
- package/dist/planmagnet/pages/IntegrationsNewSyncPagePage.js +411 -0
- package/dist/planmagnet/pages/IntegrationsNewSyncPagePage.js.map +1 -0
- package/dist/planmagnet/pages/IntegrationsSyncDetailPagePage.d.ts +2 -0
- package/dist/planmagnet/pages/IntegrationsSyncDetailPagePage.d.ts.map +1 -0
- package/dist/planmagnet/pages/IntegrationsSyncDetailPagePage.js +593 -0
- package/dist/planmagnet/pages/IntegrationsSyncDetailPagePage.js.map +1 -0
- package/dist/planmagnet/pages/IntegrationsSyncsPagePage.d.ts +2 -0
- package/dist/planmagnet/pages/IntegrationsSyncsPagePage.d.ts.map +1 -0
- package/dist/planmagnet/pages/IntegrationsSyncsPagePage.js +267 -0
- package/dist/planmagnet/pages/IntegrationsSyncsPagePage.js.map +1 -0
- package/package.json +1 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"SyncControls.js","names":[],"sources":["../../../src/planmagnet/controls/SyncControls.tsx"],"sourcesContent":["import { useState } from 'react';\nimport { gql } from '@apollo/client';\nimport { useMutation, useQuery } from '@apollo/client/react';\nimport {\n Badge,\n Button,\n Input,\n Textarea,\n ResponsiveDialog,\n ResponsiveDialogContent,\n ResponsiveDialogDescription,\n ResponsiveDialogFooter,\n ResponsiveDialogHeader,\n ResponsiveDialogTitle,\n ResponsiveDialogTrigger,\n} from '@burdenoff/fe-libs/ui';\nimport {\n AlertTriangle,\n ChevronDown,\n ChevronUp,\n Loader2,\n Pause,\n Pencil,\n Play,\n PlugZap,\n X,\n} from 'lucide-react';\nimport { throwOnError } from '../utils/mutationResult';\nimport { isForbidden, mutationErrorMessage } from '../utils/graphqlErrors';\nimport { ConfirmButton, ErrorLine } from './ConfirmButton';\nimport { enumLabel } from './WorkItemControls';\nimport { useSyncProviderCapabilities } from '../integrations/useSyncProviderCapabilities';\nimport {\n CONFLICT_RESOLUTIONS,\n directionLabel,\n directionSupported,\n GITHUB_FIELD_MAPPING_DEFAULTS,\n isValidGithubOwner,\n isValidGithubRepo,\n parseGithubFieldMapping,\n SYNC_DIRECTIONS,\n type ConflictResolution,\n type RunHealth,\n type SyncConnectionTestResult,\n type SyncDirection,\n type SyncRunResult,\n type SyncStatus,\n} from '../integrations/syncTypes';\n\n/**\n * Shared row/detail controls for External Sync (AUT-09/10/24/40): status badges, health, run/pause/resume/test\n * actions and conflict resolution. Every write here follows the same two rules the rest of this MFE does\n * (`utils/mutationResult.ts`, `utils/graphqlErrors.ts`): a refused mutation is surfaced, never swallowed, and a\n * FORBIDDEN refusal reads as \"your role can view but not change this\" rather than a raw GraphQL error string —\n * this page cannot know ahead of time whether the viewer's role allows a given write, so it always offers the\n * action and reports the refusal if and when it happens, rather than guessing at a client-side role check.\n */\n\nexport const SYNC_LIST_QUERIES = ['SyncsList'];\nexport const SYNC_DETAIL_QUERIES = ['SyncDetail', 'SyncRuns', 'SyncConflicts'];\n\nconst STATUS_VARIANT: Record<\n SyncStatus,\n 'default' | 'success' | 'warning' | 'info' | 'secondary' | 'destructive' | 'outline'\n> = {\n IDLE: 'secondary',\n SYNCING: 'info',\n SUCCESS: 'success',\n FAILED: 'destructive',\n PAUSED: 'warning',\n DISABLED: 'outline',\n};\n\nexport function SyncStatusBadge({ status }: { status: string }) {\n return (\n <Badge variant={STATUS_VARIANT[status as SyncStatus] ?? 'outline'} className=\"text-xs\">\n {enumLabel(status)}\n </Badge>\n );\n}\n\nconst RUN_STATUS_VARIANT: Record<string, 'success' | 'destructive' | 'warning'> = {\n SUCCEEDED: 'success',\n FAILED: 'destructive',\n PARTIAL: 'warning',\n};\n\nexport function SyncRunStatusBadge({ status }: { status: string }) {\n return (\n <Badge variant={RUN_STATUS_VARIANT[status] ?? 'secondary'} className=\"text-xs\">\n {enumLabel(status)}\n </Badge>\n );\n}\n\nexport function ConflictStatusBadge({ status }: { status: string }) {\n return (\n <Badge variant={status === 'OPEN' ? 'warning' : 'secondary'} className=\"text-xs\">\n {enumLabel(status)}\n </Badge>\n );\n}\n\n/** A long string (a sync's `lastSyncError`, an issue body) collapsed to `max` chars with an expand toggle. */\nexport function TruncatedText({\n text,\n max = 140,\n className = 'text-muted-foreground',\n testId,\n}: {\n text: string;\n max?: number;\n className?: string;\n testId?: string;\n}) {\n const [expanded, setExpanded] = useState(false);\n if (text.length <= max) return <span className={className}>{text}</span>;\n return (\n <span data-testid={testId}>\n <span className={className}>{expanded ? text : `${text.slice(0, max)}…`}</span>{' '}\n <button\n type=\"button\"\n className=\"inline-flex items-center gap-0.5 text-xs font-medium text-primary hover:underline\"\n aria-expanded={expanded}\n onClick={() => setExpanded((v) => !v)}\n >\n {expanded ? (\n <>\n Show less <ChevronUp className=\"h-3 w-3\" aria-hidden=\"true\" />\n </>\n ) : (\n <>\n Show more <ChevronDown className=\"h-3 w-3\" aria-hidden=\"true\" />\n </>\n )}\n </button>\n </span>\n );\n}\n\n/**\n * Last run time/status + consecutive-failure streak (AUT-09/22). `consecutiveFailures` is 0 once the latest run\n * did not fail — highlighted only while it is actually nonzero, never merely because the last run failed once\n * and then recovered.\n */\nexport function SyncHealthSummary({ health }: { health: RunHealth }) {\n return (\n <div className=\"flex flex-wrap items-center gap-2 text-xs\" data-testid=\"sync-health\">\n {health.lastRunAt ? (\n <>\n <span className=\"text-muted-foreground\">\n Last run {new Date(health.lastRunAt).toLocaleString()}\n </span>\n {health.lastStatus && <SyncRunStatusBadge status={health.lastStatus} />}\n </>\n ) : (\n <span className=\"text-muted-foreground\">Never run</span>\n )}\n {health.consecutiveFailures > 0 && (\n <span className=\"inline-flex items-center gap-1 font-medium text-status-error-text\">\n <AlertTriangle className=\"h-3 w-3\" aria-hidden=\"true\" />\n {health.consecutiveFailures} run{health.consecutiveFailures === 1 ? '' : 's'} failed in a\n row\n </span>\n )}\n <span className=\"text-muted-foreground\">\n {health.runsLast7Days} run(s) in the last 7 days\n </span>\n </div>\n );\n}\n\nconst START_SYNC = gql`\n mutation SyncControlsStartSync($id: ID!) {\n planmagnetStartSync(id: $id) {\n syncId\n success\n itemsCreated\n itemsUpdated\n itemsSkipped\n errorCount\n errors\n conflictCount\n durationMs\n syncedAt\n }\n }\n`;\n\n/** \"Run now\" (AUT-40): starts a sync in the direction `ExternalSync.direction` already records, and reports the\n * real result — including an honest `NOT_IMPLEMENTED` outcome for a provider with no live connector, never a\n * fabricated success. */\nexport function RunNowButton({\n syncId,\n onResult,\n size = 'sm',\n}: {\n syncId: string;\n onResult?: (result: SyncRunResult) => void;\n size?: 'sm' | 'default';\n}) {\n const [start, state] = useMutation<{ planmagnetStartSync: SyncRunResult }>(START_SYNC, {\n refetchQueries: [...SYNC_LIST_QUERIES, ...SYNC_DETAIL_QUERIES],\n });\n const [error, setError] = useState<string | null>(null);\n\n const run = async () => {\n setError(null);\n try {\n const res = await throwOnError(start({ variables: { id: syncId } }));\n if (res.data) onResult?.(res.data.planmagnetStartSync);\n } catch (e) {\n setError(\n isForbidden(e)\n ? 'Your role can view integrations but not change them.'\n : mutationErrorMessage(e, 'The sync could not be started.')\n );\n }\n };\n\n return (\n <div className=\"flex flex-col items-start gap-1\">\n <Button\n size={size}\n variant=\"outline\"\n disabled={state.loading}\n onClick={() => void run()}\n data-testid=\"sync-run-now\"\n >\n {state.loading ? (\n <Loader2 className=\"mr-1 h-4 w-4 animate-spin\" />\n ) : (\n <PlugZap className=\"mr-1 h-4 w-4\" />\n )}\n Run now\n </Button>\n {error && <ErrorLine message={error} />}\n </div>\n );\n}\n\n/**\n * What `planmagnetStartSync` actually did (AUT-40). A completed run is a normal GraphQL success even when the\n * sync itself failed on every item — bad token, unreachable provider, a refused status transition, … — the\n * service records `success: false` with `errors` populated rather than throwing (see\n * `sync.service.ts`'s `runGithubImport`/`runGithubExport`). This is the one place that outcome is rendered, so\n * every `RunNowButton` call site wires its `onResult` here instead of relying on a delayed list/detail refetch.\n */\nexport function SyncRunResultSummary({ result }: { result: SyncRunResult }) {\n return (\n <div\n role=\"status\"\n className={`space-y-1 rounded-md border p-3 text-sm ${\n result.success\n ? 'border-border bg-muted text-status-success-text'\n : 'border-destructive/40 text-status-error-text'\n }`}\n data-testid=\"sync-run-result\"\n >\n <p className=\"font-medium\">{result.success ? 'Sync run succeeded.' : 'Sync run failed.'}</p>\n <p className=\"text-xs text-muted-foreground\">\n {result.itemsCreated} created · {result.itemsUpdated} updated · {result.itemsSkipped}{' '}\n skipped\n {result.conflictCount > 0\n ? ` · ${result.conflictCount} conflict${result.conflictCount === 1 ? '' : 's'}`\n : ''}\n </p>\n {result.errors && result.errors.length > 0 && (\n <ul className=\"list-disc space-y-0.5 pl-4 text-xs\">\n {result.errors.map((message, i) => (\n <li key={i}>{message}</li>\n ))}\n </ul>\n )}\n </div>\n );\n}\n\nconst PAUSE_SYNC = gql`\n mutation SyncControlsPause($id: ID!) {\n planmagnetPauseExternalSync(id: $id) {\n id\n status\n }\n }\n`;\nconst RESUME_SYNC = gql`\n mutation SyncControlsResume($id: ID!) {\n planmagnetResumeExternalSync(id: $id) {\n id\n status\n }\n }\n`;\n\n/** Pause when active, Resume when PAUSED — the only two states these two mutations move between. */\nexport function PauseResumeButton({ syncId, status }: { syncId: string; status: string }) {\n const [pause, pauseState] = useMutation(PAUSE_SYNC, { refetchQueries: SYNC_LIST_QUERIES });\n const [resume, resumeState] = useMutation(RESUME_SYNC, { refetchQueries: SYNC_LIST_QUERIES });\n const [error, setError] = useState<string | null>(null);\n const loading = pauseState.loading || resumeState.loading;\n const paused = status === 'PAUSED';\n\n const toggle = async () => {\n setError(null);\n try {\n if (paused) {\n await throwOnError(resume({ variables: { id: syncId } }));\n } else {\n await throwOnError(pause({ variables: { id: syncId } }));\n }\n } catch (e) {\n setError(\n isForbidden(e)\n ? 'Your role can view integrations but not change them.'\n : mutationErrorMessage(e, `The sync could not be ${paused ? 'resumed' : 'paused'}.`)\n );\n }\n };\n\n return (\n <div className=\"flex flex-col items-start gap-1\">\n <Button\n size=\"sm\"\n variant=\"outline\"\n disabled={loading}\n onClick={() => void toggle()}\n data-testid={paused ? 'sync-resume' : 'sync-pause'}\n >\n {loading ? (\n <Loader2 className=\"mr-1 h-4 w-4 animate-spin\" />\n ) : paused ? (\n <Play className=\"mr-1 h-4 w-4\" />\n ) : (\n <Pause className=\"mr-1 h-4 w-4\" />\n )}\n {paused ? 'Resume' : 'Pause'}\n </Button>\n {error && <ErrorLine message={error} />}\n </div>\n );\n}\n\nconst TEST_SYNC = gql`\n mutation SyncControlsTest($id: ID!) {\n planmagnetTestExternalSync(id: $id) {\n ok\n message\n rateLimitRemaining\n }\n }\n`;\n\n/** AUT-23/20 — probes the connection through the real connector, writing nothing. Offered whenever the page can\n * reach it; a provider with no live connector still answers, honestly, with `ok: false`. */\nexport function TestConnectionButton({ syncId }: { syncId: string }) {\n const [test, state] = useMutation<{ planmagnetTestExternalSync: SyncConnectionTestResult }>(\n TEST_SYNC\n );\n const [result, setResult] = useState<SyncConnectionTestResult | null>(null);\n const [error, setError] = useState<string | null>(null);\n\n const run = async () => {\n setError(null);\n setResult(null);\n try {\n const res = await throwOnError(test({ variables: { id: syncId } }));\n if (res.data) setResult(res.data.planmagnetTestExternalSync);\n } catch (e) {\n setError(\n isForbidden(e)\n ? 'Your role can view integrations but not change them.'\n : mutationErrorMessage(e, 'The connection could not be tested.')\n );\n }\n };\n\n return (\n <div className=\"flex flex-col items-start gap-1\">\n <Button\n size=\"sm\"\n variant=\"outline\"\n disabled={state.loading}\n onClick={() => void run()}\n data-testid=\"sync-test-connection\"\n >\n {state.loading ? <Loader2 className=\"mr-1 h-4 w-4 animate-spin\" /> : null}\n Test connection\n </Button>\n {result && (\n <p\n className={`text-sm ${result.ok ? 'text-status-success-text' : 'text-status-error-text'}`}\n data-testid=\"sync-test-result\"\n >\n {result.ok ? 'Connected: ' : 'Failed: '}\n {result.message}\n {result.rateLimitRemaining !== null && ` (${result.rateLimitRemaining} calls remaining)`}\n </p>\n )}\n {error && <ErrorLine message={error} />}\n </div>\n );\n}\n\nconst DELETE_SYNC = gql`\n mutation SyncControlsDelete($id: ID!) {\n planmagnetDeleteExternalSync(id: $id)\n }\n`;\n\nexport function DeleteSyncButton({\n syncId,\n label,\n /** Passed by the detail page, which leaves for the list afterward — see LEAVES_PAGE_CONTEXT's own doc. */\n onDeleted,\n}: {\n syncId: string;\n label: string;\n onDeleted?: () => void;\n}) {\n const [remove, { loading }] = useMutation(DELETE_SYNC, { refetchQueries: SYNC_LIST_QUERIES });\n const [error, setError] = useState<string | null>(null);\n\n const onDelete = async () => {\n setError(null);\n try {\n await throwOnError(remove({ variables: { id: syncId } }));\n onDeleted?.();\n } catch (e) {\n setError(\n isForbidden(e)\n ? 'Your role can view integrations but not change them.'\n : mutationErrorMessage(e, 'The sync could not be deleted.')\n );\n }\n };\n\n return (\n <div className=\"flex flex-col items-end gap-1\">\n <ConfirmButton\n label=\"Delete\"\n variant=\"outline\"\n icon={<X className=\"mr-1 h-4 w-4\" />}\n title={`Delete \"${label}\"?`}\n description=\"This stops the sync and removes its configuration and run/conflict history. Work items already created from it are kept.\"\n confirmLabel=\"Delete sync\"\n destructive\n disabled={loading}\n onConfirm={() => void onDelete()}\n testId=\"sync-delete\"\n />\n {error && <ErrorLine message={error} />}\n </div>\n );\n}\n\nconst RESOLVE_CONFLICT = gql`\n mutation SyncControlsResolveConflict($id: ID!, $resolution: PlanmagnetSyncConflictResolution!) {\n planmagnetResolveSyncConflict(id: $id, resolution: $resolution) {\n id\n status\n resolution\n resolvedAt\n resolvedBy\n }\n }\n`;\n\n/** AUT-10/24 — SOURCE_WINS/TARGET_WINS actually push/pull the winning side's data; MANUAL just closes the flag.\n * A refused or failed resolution (e.g. the provider call itself fails) throws server-side and leaves the\n * conflict OPEN rather than recording a resolution that never happened — so on error this shows the reason and\n * the conflict stays in the list exactly as it was. */\nexport function ConflictResolveActions({ conflictId }: { conflictId: string }) {\n const [resolve, state] = useMutation(RESOLVE_CONFLICT, { refetchQueries: SYNC_DETAIL_QUERIES });\n const [error, setError] = useState<string | null>(null);\n const [pending, setPending] = useState<ConflictResolution | null>(null);\n\n const act = async (resolution: ConflictResolution) => {\n setError(null);\n setPending(resolution);\n try {\n await throwOnError(resolve({ variables: { id: conflictId, resolution } }));\n } catch (e) {\n setError(\n isForbidden(e)\n ? 'Your role can view integrations but not change them.'\n : mutationErrorMessage(e, 'The conflict could not be resolved.')\n );\n } finally {\n setPending(null);\n }\n };\n\n return (\n <div className=\"flex flex-col items-start gap-1\" data-testid=\"sync-conflict-resolve\">\n <div className=\"flex flex-wrap gap-2\">\n <Button\n size=\"sm\"\n disabled={state.loading}\n onClick={() => void act('SOURCE_WINS')}\n data-testid=\"sync-conflict-keep-local\"\n >\n {pending === 'SOURCE_WINS' && <Loader2 className=\"mr-1 h-4 w-4 animate-spin\" />}\n Keep PlanMagnet\n </Button>\n <Button\n size=\"sm\"\n variant=\"outline\"\n disabled={state.loading}\n onClick={() => void act('TARGET_WINS')}\n data-testid=\"sync-conflict-take-provider\"\n >\n {pending === 'TARGET_WINS' && <Loader2 className=\"mr-1 h-4 w-4 animate-spin\" />}\n Take provider\n </Button>\n <Button\n size=\"sm\"\n variant=\"ghost\"\n disabled={state.loading}\n onClick={() => void act('MANUAL')}\n data-testid=\"sync-conflict-dismiss\"\n >\n {pending === 'MANUAL' && <Loader2 className=\"mr-1 h-4 w-4 animate-spin\" />}\n Dismiss (manual)\n </Button>\n </div>\n {error && <ErrorLine message={error} />}\n </div>\n );\n}\n\nexport const CONFLICT_STRATEGY_EXPLANATION: Record<ConflictResolution, string> = {\n SOURCE_WINS:\n 'PlanMagnet wins — the local work item overwrites the provider on a detected conflict.',\n TARGET_WINS: 'Provider wins — the external tool overwrites PlanMagnet on a detected conflict.',\n MANUAL: 'Flag and skip — a conflict is recorded and left alone until resolved here.',\n};\n\nconst FIELD = 'mt-1 w-full rounded-md border border-input bg-background px-3 py-2 text-sm';\n\nconst GET_SYNC_CONNECTION = gql`\n query SyncControlsConnection($id: ID!) {\n planmagnetExternalSync(id: $id) {\n id\n connectionConfig\n }\n }\n`;\n\nconst UPDATE_SYNC = gql`\n mutation SyncControlsUpdate($id: ID!, $input: PlanmagnetUpdateExternalSyncInput!) {\n planmagnetUpdateExternalSync(id: $id, input: $input) {\n id\n direction\n conflictStrategy\n fieldMapping\n syncFilters\n externalProjectId\n externalProjectUrl\n }\n }\n`;\n\nexport interface EditableSync {\n id: string;\n provider: string;\n direction: SyncDirection;\n conflictStrategy: ConflictResolution;\n fieldMapping: unknown;\n syncFilters: unknown;\n}\n\n/**\n * The one \"Edit settings\" surface for a sync: direction, conflict strategy, field mapping and sync filters, plus\n * — for GITHUB only, where `connectionConfig`'s shape is real and known (`{ token, owner, repo }`) — an explicit\n * \"Replace connection\" group. The token is never pre-filled (it reads back as `[REDACTED]`, which must never be\n * echoed into the input or resent as if it were real); owner/repo are not secret and DO read back real values, so\n * they pre-fill and stay editable. Because `PlanmagnetUpdateExternalSyncInput.connectionConfig` REPLACES the\n * whole stored config rather than merging, changing owner or repo without also supplying a fresh token would\n * discard the stored token — so the form requires all three together whenever any of the three changed, and\n * sends none of them (keeping the stored connection untouched) when none did.\n */\nexport function EditSyncDialog({ sync }: { sync: EditableSync }) {\n const [open, setOpen] = useState(false);\n const isGithub = sync.provider === 'GITHUB';\n const { capabilities } = useSyncProviderCapabilities();\n const capability = capabilities.find((c) => c.provider === sync.provider);\n const allowedDirections = capability\n ? SYNC_DIRECTIONS.filter((d) => directionSupported(capability, d))\n : SYNC_DIRECTIONS;\n\n const initialMapping = parseGithubFieldMapping(sync.fieldMapping);\n const initialFiltersText = sync.syncFilters ? JSON.stringify(sync.syncFilters, null, 2) : '';\n\n const [direction, setDirection] = useState<SyncDirection>(sync.direction);\n const [conflictStrategy, setConflictStrategy] = useState<ConflictResolution>(\n sync.conflictStrategy\n );\n const [priorityPrefix, setPriorityPrefix] = useState(initialMapping.priority);\n const [dueDatePrefix, setDueDatePrefix] = useState(initialMapping.dueDate);\n const [filtersText, setFiltersText] = useState(initialFiltersText);\n const [filtersError, setFiltersError] = useState<string | null>(null);\n // Raw user edits, '' meaning \"untouched\". `effectiveOwner`/`effectiveRepo` below fall back to the real,\n // non-secret value the query loads — no `useEffect` seeding required (and none of the cascading-render risk\n // it brings): until the user types, the field simply displays the loaded value; the moment they type anything,\n // their edit takes over, even if it round-trips to the same text.\n const [owner, setOwner] = useState('');\n const [repo, setRepo] = useState('');\n const [token, setToken] = useState('');\n const [error, setError] = useState<string | null>(null);\n\n const { data: connectionData } = useQuery<{\n planmagnetExternalSync: { id: string; connectionConfig: Record<string, unknown> } | null;\n }>(GET_SYNC_CONNECTION, { variables: { id: sync.id }, skip: !open || !isGithub });\n\n const config = connectionData?.planmagnetExternalSync?.connectionConfig;\n const loadedOwner = typeof config?.owner === 'string' ? config.owner : '';\n const loadedRepo = typeof config?.repo === 'string' ? config.repo : '';\n const effectiveOwner = owner || loadedOwner;\n const effectiveRepo = repo || loadedRepo;\n\n const resetForm = () => {\n setDirection(sync.direction);\n setConflictStrategy(sync.conflictStrategy);\n setPriorityPrefix(initialMapping.priority);\n setDueDatePrefix(initialMapping.dueDate);\n setFiltersText(initialFiltersText);\n setFiltersError(null);\n setOwner('');\n setRepo('');\n setToken('');\n setError(null);\n };\n\n const [update, state] = useMutation(UPDATE_SYNC, {\n refetchQueries: [...SYNC_LIST_QUERIES, ...SYNC_DETAIL_QUERIES],\n });\n\n const connectionChanged =\n isGithub &&\n !!config &&\n (effectiveOwner !== loadedOwner || effectiveRepo !== loadedRepo || token.trim() !== '');\n const mappingChanged =\n priorityPrefix.trim() !== initialMapping.priority ||\n dueDatePrefix.trim() !== initialMapping.dueDate;\n const filtersChanged = filtersText.trim() !== initialFiltersText.trim();\n\n const save = async () => {\n setError(null);\n setFiltersError(null);\n const input: Record<string, unknown> = {};\n if (direction !== sync.direction) input.direction = direction;\n if (conflictStrategy !== sync.conflictStrategy) input.conflictStrategy = conflictStrategy;\n if (mappingChanged) {\n input.fieldMapping = {\n ...(priorityPrefix.trim() ? { priority: priorityPrefix.trim() } : {}),\n ...(dueDatePrefix.trim() ? { dueDate: dueDatePrefix.trim() } : {}),\n };\n }\n if (filtersChanged) {\n const trimmed = filtersText.trim();\n if (!trimmed) {\n input.syncFilters = null;\n } else {\n try {\n input.syncFilters = JSON.parse(trimmed);\n } catch {\n setFiltersError('Sync filters must be valid JSON.');\n return;\n }\n }\n }\n if (connectionChanged) {\n if (!token.trim() || !effectiveOwner.trim() || !effectiveRepo.trim()) {\n setError('Changing the owner, repo or token requires all three — re-enter the token too.');\n return;\n }\n if (!isValidGithubOwner(effectiveOwner) || !isValidGithubRepo(effectiveRepo)) {\n setError(\n 'Owner and repo must look like real GitHub names (letters, digits, \"-\", \"_\", \".\").'\n );\n return;\n }\n input.connectionConfig = {\n token: token.trim(),\n owner: effectiveOwner.trim(),\n repo: effectiveRepo.trim(),\n };\n }\n if (Object.keys(input).length === 0) {\n setOpen(false);\n return;\n }\n try {\n await throwOnError(update({ variables: { id: sync.id, input } }));\n setOpen(false);\n } catch (e) {\n setError(\n isForbidden(e)\n ? 'Your role can view integrations but not change them.'\n : mutationErrorMessage(e, 'The sync could not be saved.')\n );\n }\n };\n\n return (\n <ResponsiveDialog\n open={open}\n onOpenChange={(next) => {\n setOpen(next);\n if (!next) resetForm();\n }}\n >\n <ResponsiveDialogTrigger asChild>\n <Button size=\"sm\" variant=\"outline\" data-testid=\"sync-edit-settings\">\n <Pencil className=\"mr-1 h-4 w-4\" />\n Edit settings\n </Button>\n </ResponsiveDialogTrigger>\n <ResponsiveDialogContent className=\"max-w-lg max-h-[85vh] overflow-y-auto\">\n <ResponsiveDialogHeader>\n <ResponsiveDialogTitle>Edit sync settings</ResponsiveDialogTitle>\n <ResponsiveDialogDescription>Only changed fields are saved.</ResponsiveDialogDescription>\n </ResponsiveDialogHeader>\n <div className=\"space-y-4\">\n <div>\n <span className=\"text-sm font-medium\">Direction</span>\n <div className=\"mt-1 flex flex-col gap-1\" role=\"radiogroup\" aria-label=\"Direction\">\n {allowedDirections.map((d) => (\n <label key={d} className=\"flex items-center gap-2 text-sm\">\n <input\n type=\"radio\"\n name=\"sync-edit-direction\"\n checked={direction === d}\n onChange={() => setDirection(d)}\n />\n {directionLabel(d)}\n </label>\n ))}\n </div>\n </div>\n <div>\n <label htmlFor=\"sync-edit-strategy\" className=\"text-sm font-medium\">\n Conflict strategy\n </label>\n <select\n id=\"sync-edit-strategy\"\n className={FIELD}\n value={conflictStrategy}\n onChange={(e) => setConflictStrategy(e.target.value as ConflictResolution)}\n >\n {CONFLICT_RESOLUTIONS.map((r) => (\n <option key={r} value={r}>\n {enumLabel(r)}\n </option>\n ))}\n </select>\n <p className=\"mt-1 text-xs text-muted-foreground\">\n {CONFLICT_STRATEGY_EXPLANATION[conflictStrategy]}\n </p>\n </div>\n {isGithub && (\n <div className=\"space-y-2 rounded-md border p-3\">\n <p className=\"text-sm font-medium\">Field mapping (GitHub labels)</p>\n <p className=\"text-xs text-muted-foreground\">\n GitHub issues have no native priority or due-date field — PlanMagnet encodes each as\n a label of the form <code>prefix+value</code> (e.g. <code>priority:HIGH</code>).\n Leave blank to use the built-in prefix.\n </p>\n <div>\n <label\n htmlFor=\"sync-edit-priority-prefix\"\n className=\"text-xs text-muted-foreground\"\n >\n Priority label prefix (default "{GITHUB_FIELD_MAPPING_DEFAULTS.priority}\n ")\n </label>\n <Input\n id=\"sync-edit-priority-prefix\"\n className=\"mt-1\"\n placeholder={GITHUB_FIELD_MAPPING_DEFAULTS.priority}\n value={priorityPrefix}\n onChange={(e) => setPriorityPrefix(e.target.value)}\n />\n </div>\n <div>\n <label htmlFor=\"sync-edit-duedate-prefix\" className=\"text-xs text-muted-foreground\">\n Due-date label prefix (default "{GITHUB_FIELD_MAPPING_DEFAULTS.dueDate}\n ")\n </label>\n <Input\n id=\"sync-edit-duedate-prefix\"\n className=\"mt-1\"\n placeholder={GITHUB_FIELD_MAPPING_DEFAULTS.dueDate}\n value={dueDatePrefix}\n onChange={(e) => setDueDatePrefix(e.target.value)}\n />\n </div>\n </div>\n )}\n <div>\n <label htmlFor=\"sync-edit-filters\" className=\"text-sm font-medium\">\n Sync filters (advanced, JSON)\n </label>\n <p className=\"text-xs text-muted-foreground\">\n Stored on the sync but not yet read by any run — reserved for a future filtering\n feature. Leave blank unless you know you need this.\n </p>\n <Textarea\n id=\"sync-edit-filters\"\n className=\"mt-1 font-mono text-xs min-h-[72px]\"\n value={filtersText}\n onChange={(e) => setFiltersText(e.target.value)}\n />\n {filtersError && <ErrorLine message={filtersError} />}\n </div>\n {isGithub && (\n <div className=\"space-y-2 rounded-md border p-3\">\n <p className=\"text-sm font-medium\">Replace connection</p>\n <p className=\"text-xs text-muted-foreground\">\n The token is never shown once saved. Changing the owner, repo or token requires\n re-entering all three — PlanMagnet cannot resend the stored token for you.\n </p>\n <div>\n <label htmlFor=\"sync-edit-owner\" className=\"text-xs text-muted-foreground\">\n Owner\n </label>\n <Input\n id=\"sync-edit-owner\"\n className=\"mt-1\"\n value={effectiveOwner}\n onChange={(e) => setOwner(e.target.value)}\n />\n </div>\n <div>\n <label htmlFor=\"sync-edit-repo\" className=\"text-xs text-muted-foreground\">\n Repository\n </label>\n <Input\n id=\"sync-edit-repo\"\n className=\"mt-1\"\n value={effectiveRepo}\n onChange={(e) => setRepo(e.target.value)}\n />\n </div>\n <div>\n <label htmlFor=\"sync-edit-token\" className=\"text-xs text-muted-foreground\">\n Replace token\n </label>\n <Input\n id=\"sync-edit-token\"\n type=\"password\"\n autoComplete=\"off\"\n className=\"mt-1\"\n placeholder=\"Leave blank to keep the current token\"\n value={token}\n onChange={(e) => setToken(e.target.value)}\n data-testid=\"sync-edit-token\"\n />\n </div>\n </div>\n )}\n {error && <ErrorLine message={error} />}\n </div>\n <ResponsiveDialogFooter>\n <Button\n variant=\"outline\"\n onClick={() => {\n resetForm();\n setOpen(false);\n }}\n >\n Cancel\n </Button>\n <Button\n onClick={() => void save()}\n disabled={state.loading}\n data-testid=\"sync-edit-submit\"\n >\n {state.loading ? 'Saving…' : 'Save'}\n </Button>\n </ResponsiveDialogFooter>\n </ResponsiveDialogContent>\n </ResponsiveD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AkB,WAAU;mBAAgC;SAEnE,CAAA,EACR,kBAAC,GAAD;SACE,IAAG;SACH,WAAU;SACV,OAAO;SACP,WAAW,MAAM,EAAS,EAAE,OAAO,MAAM;SACzC,CAAA,CACE,EAAA,CAAA;QACN,kBAAC,OAAD,EAAA,UAAA,CACE,kBAAC,SAAD;SAAO,SAAQ;SAAiB,WAAU;mBAAgC;SAElE,CAAA,EACR,kBAAC,GAAD;SACE,IAAG;SACH,WAAU;SACV,OAAO;SACP,WAAW,MAAM,EAAQ,EAAE,OAAO,MAAM;SACxC,CAAA,CACE,EAAA,CAAA;QACN,kBAAC,OAAD,EAAA,UAAA,CACE,kBAAC,SAAD;SAAO,SAAQ;SAAkB,WAAU;mBAAgC;SAEnE,CAAA,EACR,kBAAC,GAAD;SACE,IAAG;SACH,MAAK;SACL,cAAa;SACb,WAAU;SACV,aAAY;SACZ,OAAO;SACP,WAAW,MAAM,EAAS,EAAE,OAAO,MAAM;SACzC,eAAY;SACZ,CAAA,CACE,EAAA,CAAA;QACF;;MAEP,KAAS,kBAAC,GAAD,EAAW,SAAS,GAAS,CAAA;MACnC;;IACN,kBAAC,IAAD,EAAA,UAAA,CACE,kBAAC,GAAD;KACE,SAAQ;KACR,eAAe;AAEb,MADA,IAAW,EACX,EAAQ,GAAM;;eAEjB;KAEQ,CAAA,EACT,kBAAC,GAAD;KACE,eAAe,KAAK,IAAM;KAC1B,UAAU,EAAM;KAChB,eAAY;eAEX,EAAM,UAAU,YAAY;KACtB,CAAA,CACc,EAAA,CAAA;IACD;KACT"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"useLiveRefresh.d.ts","sourceRoot":"","sources":["../../../src/planmagnet/hooks/useLiveRefresh.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"useLiveRefresh.d.ts","sourceRoot":"","sources":["../../../src/planmagnet/hooks/useLiveRefresh.ts"],"names":[],"mappings":"AAMA;;;;;;;;;;;;;;;;;;;;;;;;;;;GA2BG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allback as t, useEffect as n, useRef as r, useState as i } from "react";
|
|
3
3
|
import { gql as a } from "@apollo/client";
|
|
4
4
|
import { useApolloClient as o, useSubscription as s } from "@apollo/client/react";
|
|
5
|
+
import { clearGraphqlFetchResponseCache as c } from "@burdenoff/fe-libs/shared/graphql";
|
|
5
6
|
//#region src/planmagnet/hooks/useLiveRefresh.ts
|
|
6
|
-
var
|
|
7
|
+
var l = a`
|
|
7
8
|
subscription PlanmagnetLiveProjectUpdated($workspaceId: ID!, $projectId: ID) {
|
|
8
9
|
planmagnetOnProjectUpdated(workspaceId: $workspaceId, projectId: $projectId) {
|
|
9
10
|
kind
|
|
@@ -14,7 +15,7 @@ var c = a`
|
|
|
14
15
|
at
|
|
15
16
|
}
|
|
16
17
|
}
|
|
17
|
-
`,
|
|
18
|
+
`, u = a`
|
|
18
19
|
subscription PlanmagnetLiveSprintUpdated($workspaceId: ID!, $sprintId: ID, $projectId: ID) {
|
|
19
20
|
planmagnetOnSprintUpdated(
|
|
20
21
|
workspaceId: $workspaceId
|
|
@@ -30,7 +31,7 @@ var c = a`
|
|
|
30
31
|
at
|
|
31
32
|
}
|
|
32
33
|
}
|
|
33
|
-
`,
|
|
34
|
+
`, d = a`
|
|
34
35
|
subscription PlanmagnetLiveWorkItemUpdated($workspaceId: ID!, $projectId: ID, $workItemId: ID) {
|
|
35
36
|
planmagnetOnWorkItemUpdated(
|
|
36
37
|
workspaceId: $workspaceId
|
|
@@ -47,15 +48,15 @@ var c = a`
|
|
|
47
48
|
}
|
|
48
49
|
}
|
|
49
50
|
`;
|
|
50
|
-
function
|
|
51
|
+
function f(...e) {
|
|
51
52
|
let t = e.filter((e) => e !== null);
|
|
52
53
|
return t.length === 0 ? null : t.includes("polling") ? "polling" : t.includes("connecting") ? "connecting" : "live";
|
|
53
54
|
}
|
|
54
|
-
var
|
|
55
|
-
function
|
|
56
|
-
return e === "project" ?
|
|
55
|
+
var p = 5e3, m = 3;
|
|
56
|
+
function h(e) {
|
|
57
|
+
return e === "project" ? l : e === "sprint" ? u : d;
|
|
57
58
|
}
|
|
58
|
-
function
|
|
59
|
+
function g(e, i, a) {
|
|
59
60
|
let o = r(null), s = r(null), c = r(0), l = r(!1), u = t(() => {
|
|
60
61
|
l.current = !1, c.current = Date.now(), e();
|
|
61
62
|
}, [e]), d = t(() => {
|
|
@@ -80,64 +81,64 @@ function h(e, i, a) {
|
|
|
80
81
|
o.current && clearTimeout(o.current), s.current && clearTimeout(s.current);
|
|
81
82
|
}, []), d;
|
|
82
83
|
}
|
|
83
|
-
function
|
|
84
|
-
let { workspaceId:
|
|
85
|
-
|
|
86
|
-
}, [
|
|
87
|
-
|
|
88
|
-
if (!
|
|
84
|
+
function _({ kind: a, projectId: l, sprintId: u, workItemId: d, queries: f, debounceMs: _ = 500, minIntervalMs: v, connectTimeoutMs: y = 8e3, pollIntervalMs: b = 3e4, enabled: x = !0 }) {
|
|
85
|
+
let { workspaceId: S } = e(), C = o(), w = !S || a === "sprint" && !u && !l || a === "project" && !l || !x, T = w ? null : `${a}:${S}:${l ?? ""}:${u ?? ""}:${d ?? ""}`, E = t(() => {
|
|
86
|
+
c(), C.refetchQueries({ include: [...f] });
|
|
87
|
+
}, [C, f]), D = g(E, _, v), [O, k] = i(T ? "connecting" : null), [A, j] = i(T);
|
|
88
|
+
T !== A && (j(T), k(T ? "connecting" : null)), n(() => {
|
|
89
|
+
if (!T) return;
|
|
89
90
|
let e = setTimeout(() => {
|
|
90
|
-
|
|
91
|
-
},
|
|
91
|
+
k((e) => e === "connecting" ? "live" : e);
|
|
92
|
+
}, y);
|
|
92
93
|
return () => clearTimeout(e);
|
|
93
|
-
}, [
|
|
94
|
-
let
|
|
95
|
-
n(() => (
|
|
96
|
-
|
|
97
|
-
}), [
|
|
98
|
-
let
|
|
99
|
-
if (
|
|
100
|
-
|
|
94
|
+
}, [T, y]);
|
|
95
|
+
let M = r(0), N = r(0), P = r(null);
|
|
96
|
+
n(() => (M.current = Date.now(), N.current = 0, () => {
|
|
97
|
+
P.current && clearTimeout(P.current), P.current = null;
|
|
98
|
+
}), [T]);
|
|
99
|
+
let F = r(null), I = t(() => {
|
|
100
|
+
if (N.current = Date.now() - M.current < p ? N.current + 1 : 0, N.current >= m) {
|
|
101
|
+
k("polling");
|
|
101
102
|
return;
|
|
102
103
|
}
|
|
103
|
-
|
|
104
|
-
|
|
104
|
+
P.current = setTimeout(() => {
|
|
105
|
+
P.current = null, M.current = Date.now(), F.current?.();
|
|
105
106
|
}, 0);
|
|
106
|
-
}, []), { restart:
|
|
107
|
+
}, []), { restart: L } = s(h(a), {
|
|
107
108
|
variables: {
|
|
108
|
-
workspaceId:
|
|
109
|
-
projectId:
|
|
110
|
-
sprintId:
|
|
111
|
-
workItemId:
|
|
109
|
+
workspaceId: S,
|
|
110
|
+
projectId: l ?? void 0,
|
|
111
|
+
sprintId: u ?? void 0,
|
|
112
|
+
workItemId: d ?? void 0
|
|
112
113
|
},
|
|
113
|
-
skip:
|
|
114
|
+
skip: w,
|
|
114
115
|
onData: () => {
|
|
115
|
-
|
|
116
|
+
k((e) => e === "connecting" ? "live" : e), D();
|
|
116
117
|
},
|
|
117
118
|
onError: (e) => {
|
|
118
119
|
console.debug("[useLiveRefresh] subscription unavailable, falling back to polling:", {
|
|
119
120
|
kind: a,
|
|
120
121
|
message: e instanceof Error ? e.message : String(e)
|
|
121
|
-
}),
|
|
122
|
+
}), k("polling");
|
|
122
123
|
},
|
|
123
|
-
onComplete:
|
|
124
|
+
onComplete: I
|
|
124
125
|
});
|
|
125
126
|
return n(() => {
|
|
126
|
-
|
|
127
|
-
}, [
|
|
128
|
-
if (
|
|
127
|
+
F.current = L;
|
|
128
|
+
}, [L]), n(() => {
|
|
129
|
+
if (w || O !== "polling") return;
|
|
129
130
|
let e = setInterval(() => {
|
|
130
|
-
typeof document < "u" && document.visibilityState === "hidden" ||
|
|
131
|
-
},
|
|
131
|
+
typeof document < "u" && document.visibilityState === "hidden" || E();
|
|
132
|
+
}, b);
|
|
132
133
|
return () => clearInterval(e);
|
|
133
134
|
}, [
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
]), { mode:
|
|
135
|
+
w,
|
|
136
|
+
O,
|
|
137
|
+
b,
|
|
138
|
+
E
|
|
139
|
+
]), { mode: w ? null : O };
|
|
139
140
|
}
|
|
140
141
|
//#endregion
|
|
141
|
-
export {
|
|
142
|
+
export { f as combineLiveRefreshModes, _ as useLiveRefresh };
|
|
142
143
|
|
|
143
144
|
//# sourceMappingURL=useLiveRefresh.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"useLiveRefresh.js","names":[],"sources":["../../../src/planmagnet/hooks/useLiveRefresh.ts"],"sourcesContent":["import { useCallback, useEffect, useRef, useState } from 'react';\nimport { gql } from '@apollo/client';\nimport { useApolloClient, useSubscription } from '@apollo/client/react';\nimport { usePlanMagnet } from '../providers/PlanMagnetProvider';\n\n/**\n * Live updates (PDM-05/11/21, ANR-23): a page subscribes to a thin, workspace-scoped event stream over the\n * gateway SSE path and re-reads its own named queries when something relevant changed — it never applies the\n * event payload as data (the payload carries identifiers and `changedFields` only, by server design, so a\n * subscriber re-reads under its own permissions instead of trusting something that bypassed RBAC and row-level\n * scoping). See `useDataSinkSubscription.ts` (microfe-bigconsole) for the sibling pattern this generalizes:\n * `skip` when the ids a subscription needs haven't loaded yet, and treat a transport/backend error as expected\n * degradation, not a page-breaking failure.\n *\n * Every event stream requires `workspaceId` server-side — a subscription whose `workspaceId` is not the\n * caller's own workspace is refused by the gateway, so this hook always reads it from `usePlanMagnet()` rather\n * than accepting it as a prop a caller could get wrong.\n *\n * Connection lifecycle. SSE has no connect acknowledgement: a refused subscription (bad variables, another\n * workspace, no auth) comes back at once as an error, while an accepted one simply stays open with nothing to\n * say until something changes. So a stream still open and error-free after `connectTimeoutMs` is treated as\n * live, and the first event proves it earlier. The server closes a stream after 60 s without events\n * (`REALTIME_SUBSCRIPTION_IDLE_TIMEOUT_MS` in the svc), which Apollo reports as completion — that is routine,\n * so the hook resubscribes rather than going quiet. A stream that keeps completing within seconds of opening is\n * not healthy and degrades to polling.\n *\n * Graceful fallback (this is the point of the hook, not an edge case): if the subscription errors, or keeps\n * closing as soon as it opens, `mode` becomes `'polling'` and a 30-second interval takes over, paused while the\n * tab is hidden (`document.visibilityState`). There is no reconnect-to-live attempt within one mount — once\n * degraded, a page stays on polling until it remounts. `standalone` dev/Storybook builds (no SSE link\n * configured — see `PlanMagnetProvider`) always take this path; that is expected, not a defect, and is why a\n * subscription error here is never surfaced as a page error.\n */\n\nexport type LiveRefreshKind = 'workItem' | 'project' | 'sprint';\nexport type LiveRefreshMode = 'connecting' | 'live' | 'polling';\n\ninterface LiveEvent {\n kind: string;\n id: string;\n workspaceId: string;\n projectId?: string | null;\n changedFields: string[];\n actorId: string;\n at: string;\n}\n\nconst ON_PROJECT_UPDATED = gql`\n subscription PlanmagnetLiveProjectUpdated($workspaceId: ID!, $projectId: ID) {\n planmagnetOnProjectUpdated(workspaceId: $workspaceId, projectId: $projectId) {\n kind\n id\n workspaceId\n changedFields\n actorId\n at\n }\n }\n`;\n\nconst ON_SPRINT_UPDATED = gql`\n subscription PlanmagnetLiveSprintUpdated($workspaceId: ID!, $sprintId: ID, $projectId: ID) {\n planmagnetOnSprintUpdated(\n workspaceId: $workspaceId\n sprintId: $sprintId\n projectId: $projectId\n ) {\n kind\n id\n projectId\n workspaceId\n changedFields\n actorId\n at\n }\n }\n`;\n\nconst ON_WORK_ITEM_UPDATED = gql`\n subscription PlanmagnetLiveWorkItemUpdated($workspaceId: ID!, $projectId: ID, $workItemId: ID) {\n planmagnetOnWorkItemUpdated(\n workspaceId: $workspaceId\n projectId: $projectId\n workItemId: $workItemId\n ) {\n kind\n id\n projectId\n workspaceId\n changedFields\n actorId\n at\n }\n }\n`;\n\nexport interface UseLiveRefreshOptions {\n /** Which event stream to subscribe to — see `PlanmagnetOn{Project,Sprint,WorkItem}Updated` in the schema. */\n kind: LiveRefreshKind;\n /** Narrows the stream server-side. Omitted on `workItem`/`project` this is a workspace-wide stream (the\n * Dashboard and role dashboards want every project's events); `sprint` needs `sprintId` to mean anything on a\n * single sprint's page, so the hook skips subscribing until it has one. */\n projectId?: string | null;\n /** For `kind: 'sprint'`, at least one of `sprintId`/`projectId` is required — one sprint's own events, or\n * every sprint in one project's. Neither means \"skip\" (every sprint workspace-wide has no current caller). */\n sprintId?: string | null;\n /** Narrows a `workItem`-kind stream to one item. Unused by every current caller (the board/dashboards want\n * every item's events for their scope) but supported for a future single-item page. */\n workItemId?: string | null;\n /** Apollo operation names this page's queries were declared with — refetched by name\n * (`client.refetchQueries({ include })`) on a (debounced, optionally throttled) event. Never the literal\n * query document, and never the event's own payload used as data. */\n queries: readonly string[];\n /** Coalesces a burst of events (e.g. a bulk update moving 20 cards) into one refetch. Default 500. */\n debounceMs?: number;\n /** A floor between refetches once debounced, for a page whose queries are expensive to re-run on every\n * change (ANR-23: the Dashboard and role dashboards, at most once per 15s). Unset: only the debounce window\n * applies. A pulse arriving inside the floor is never dropped — it runs at the floor's far edge (trailing). */\n minIntervalMs?: number;\n /** How long an open, error-free subscription stays \"Connecting…\" before it counts as live. Default 8000. */\n connectTimeoutMs?: number;\n /** Polling cadence once on the fallback path. Default 30000 (ANR-23/PDM-05: \"every 30s\"). */\n pollIntervalMs?: number;\n /** An extra gate beyond the kind's own required id(s) — e.g. a sprint page's `workItem`-kind stream (no id of\n * its own is required) should still wait for the sprint's `projectId` to resolve, and skip entirely for a\n * team-scoped sprint (no `projectId` at all) rather than falling back to a workspace-wide stream. Default\n * `true` (no extra gate). */\n enabled?: boolean;\n}\n\nexport interface UseLiveRefreshResult {\n /** `null` while a required id (e.g. a sprint page before `sprintId` resolves) hasn't loaded — there is\n * nothing to subscribe to yet, so `LiveStatus` renders nothing rather than a misleading \"Connecting…\". */\n mode: LiveRefreshMode | null;\n}\n\n/** Rolls up more than one `useLiveRefresh` result into the single indicator a page shows (e.g. the sprint\n * detail page subscribes to both sprint events and the sprint's project's work item events). Reports the least\n * favorable non-null mode present — `'polling'` beats `'connecting'` beats `'live'` — so the page never claims\n * \"Live\" while one of its own streams is actually degraded. `null` (nothing subscribed yet) only when every\n * input is `null`. */\nexport function combineLiveRefreshModes(\n ...modes: ReadonlyArray<LiveRefreshMode | null>\n): LiveRefreshMode | null {\n const present = modes.filter((mode): mode is LiveRefreshMode => mode !== null);\n if (present.length === 0) return null;\n if (present.includes('polling')) return 'polling';\n if (present.includes('connecting')) return 'connecting';\n return 'live';\n}\n\nconst RAPID_CLOSE_MS = 5000;\nconst RAPID_CLOSE_LIMIT = 3;\n\nfunction subscriptionDocumentFor(kind: LiveRefreshKind) {\n if (kind === 'project') return ON_PROJECT_UPDATED;\n if (kind === 'sprint') return ON_SPRINT_UPDATED;\n return ON_WORK_ITEM_UPDATED;\n}\n\n/** A debounced, optionally-throttled trigger: bursts inside `debounceMs` coalesce into one call; once debounced,\n * a call inside `minIntervalMs` of the last one is never dropped — it runs at the floor's far edge instead.\n * `run` is expected to be a `useCallback`-stable function (the hook below's `refetch` is, since it only depends\n * on `client` and `queries`) — accepted as a normal dependency rather than stashed in a ref, so it is never\n * read or written outside an effect/callback. */\nfunction useCoalescedTrigger(\n run: () => void,\n debounceMs: number,\n minIntervalMs: number | undefined\n) {\n const debounceTimer = useRef<ReturnType<typeof setTimeout> | null>(null);\n const floorTimer = useRef<ReturnType<typeof setTimeout> | null>(null);\n const lastRunAt = useRef(0);\n const floorPending = useRef(false);\n\n const runNow = useCallback(() => {\n floorPending.current = false;\n lastRunAt.current = Date.now();\n run();\n }, [run]);\n\n const trigger = useCallback(() => {\n if (debounceTimer.current) clearTimeout(debounceTimer.current);\n debounceTimer.current = setTimeout(() => {\n debounceTimer.current = null;\n if (!minIntervalMs) {\n runNow();\n return;\n }\n const elapsed = Date.now() - lastRunAt.current;\n if (elapsed >= minIntervalMs) {\n runNow();\n return;\n }\n if (floorPending.current) return; // a trailing run is already scheduled for this window\n floorPending.current = true;\n floorTimer.current = setTimeout(runNow, minIntervalMs - elapsed);\n }, debounceMs);\n }, [debounceMs, minIntervalMs, runNow]);\n\n useEffect(\n () => () => {\n if (debounceTimer.current) clearTimeout(debounceTimer.current);\n if (floorTimer.current) clearTimeout(floorTimer.current);\n },\n []\n );\n\n return trigger;\n}\n\nexport function useLiveRefresh({\n kind,\n projectId,\n sprintId,\n workItemId,\n queries,\n debounceMs = 500,\n minIntervalMs,\n connectTimeoutMs = 8000,\n pollIntervalMs = 30000,\n enabled = true,\n}: UseLiveRefreshOptions): UseLiveRefreshResult {\n const { workspaceId } = usePlanMagnet();\n const client = useApolloClient();\n\n // 'sprint' means something scoped to either one sprint (a sprint's own page) or every sprint in one project (a\n // project-scoped dashboard) — it needs at least one of the two ids, never neither (that would be every sprint\n // in the whole workspace, which no current caller wants). 'project' always needs its one id.\n const requiredIdMissing =\n (kind === 'sprint' && !sprintId && !projectId) || (kind === 'project' && !projectId);\n const skip = !workspaceId || requiredIdMissing || !enabled;\n\n // Identifies what we'd subscribe to right now — `null` when there's nothing to. `queries` is deliberately not\n // part of this: which QUERIES a page refetches changing (it never does, in practice — every caller passes a\n // module-level const array) shouldn't reset a live connection, only what STREAM we're on should.\n const subscriptionKey = skip\n ? null\n : `${kind}:${workspaceId}:${projectId ?? ''}:${sprintId ?? ''}:${workItemId ?? ''}`;\n\n const refetch = useCallback(() => {\n void client.refetchQueries({ include: [...queries] });\n }, [client, queries]);\n\n const trigger = useCoalescedTrigger(refetch, debounceMs, minIntervalMs);\n\n const [mode, setMode] = useState<LiveRefreshMode | null>(subscriptionKey ? 'connecting' : null);\n const [modeKey, setModeKey] = useState<string | null>(subscriptionKey);\n\n // Reset to \"connecting\" (or \"nothing to do\") the moment what we'd subscribe to changes — switching project,\n // sprint or page. This is the React-documented \"adjust state when a value changes\" pattern: a direct setState\n // call guarded by comparing against the last-seen key, during render, rather than in an effect — it lands in\n // the very render that changed, with no stale \"still connecting to the OLD target\" frame first.\n if (subscriptionKey !== modeKey) {\n setModeKey(subscriptionKey);\n setMode(subscriptionKey ? 'connecting' : null);\n }\n\n // The connect window needs a real timer; its only setState call lives inside the timeout's own callback (an\n // update \"when external state changes\"), never synchronously in the effect body. A refused subscription has\n // already errored into 'polling' by now (errors arrive at once), so a still-\"connecting\" one is open and\n // accepted — see the lifecycle note above.\n useEffect(() => {\n if (!subscriptionKey) return;\n const timer = setTimeout(() => {\n setMode((current) => (current === 'connecting' ? 'live' : current));\n }, connectTimeoutMs);\n return () => clearTimeout(timer);\n }, [subscriptionKey, connectTimeoutMs]);\n\n // Rapid-completion guard for the resubscribe below: when each stream closes within RAPID_CLOSE_MS of opening,\n // RAPID_CLOSE_LIMIT times in a row, the transport is not holding the stream open and polling takes over.\n const openedAt = useRef(0);\n const rapidCloses = useRef(0);\n const resubscribeTimer = useRef<ReturnType<typeof setTimeout> | null>(null);\n useEffect(() => {\n openedAt.current = Date.now();\n rapidCloses.current = 0;\n return () => {\n if (resubscribeTimer.current) clearTimeout(resubscribeTimer.current);\n resubscribeTimer.current = null;\n };\n }, [subscriptionKey]);\n\n // The server's idle close (60 s without events), or the ALB ending a long-lived response: routine, so open a\n // fresh stream. Deferred a tick so Apollo finishes tearing down the completed one first. `restart` comes back\n // from `useSubscription` below, so it is reached through a ref kept current by an effect.\n const restartRef = useRef<(() => void) | null>(null);\n const handleComplete = useCallback(() => {\n const lived = Date.now() - openedAt.current;\n rapidCloses.current = lived < RAPID_CLOSE_MS ? rapidCloses.current + 1 : 0;\n if (rapidCloses.current >= RAPID_CLOSE_LIMIT) {\n setMode('polling');\n return;\n }\n resubscribeTimer.current = setTimeout(() => {\n resubscribeTimer.current = null;\n openedAt.current = Date.now();\n restartRef.current?.();\n }, 0);\n }, []);\n\n const { restart } = useSubscription<{\n planmagnetOnProjectUpdated?: LiveEvent;\n planmagnetOnSprintUpdated?: LiveEvent;\n planmagnetOnWorkItemUpdated?: LiveEvent;\n }>(subscriptionDocumentFor(kind), {\n variables: {\n workspaceId,\n projectId: projectId ?? undefined,\n sprintId: sprintId ?? undefined,\n workItemId: workItemId ?? undefined,\n },\n skip,\n onData: () => {\n // Proof the subscription is live: the connect-timeout above only flips a still-\"connecting\" mode, so this\n // is a no-op once already 'live', and never resurrects a mode that errored into 'polling'.\n setMode((current) => (current === 'connecting' ? 'live' : current));\n trigger();\n },\n onError: (error) => {\n // Covers both a real backend/network failure and the expected \"no SSE transport configured\" case in a\n // standalone/Storybook build (see PlanMagnetProvider) — either way the correct behavior is the same:\n // degrade to polling rather than break the page. Logged at debug level only; this is not a user-facing\n // error state.\n console.debug('[useLiveRefresh] subscription unavailable, falling back to polling:', {\n kind,\n message: error instanceof Error ? error.message : String(error),\n });\n setMode('polling');\n },\n onComplete: handleComplete,\n });\n\n useEffect(() => {\n restartRef.current = restart;\n }, [restart]);\n\n // Polling fallback: the same queries, every `pollIntervalMs`, paused while the tab is hidden. No separate\n // throttle window here — the interval itself is the pacing (30s default, already above any ANR-23 floor).\n useEffect(() => {\n if (skip || mode !== 'polling') return;\n const id = setInterval(() => {\n if (typeof document !== 'undefined' && document.visibilityState === 'hidden') return;\n refetch();\n }, pollIntervalMs);\n return () => clearInterval(id);\n }, [skip, mode, pollIntervalMs, refetch]);\n\n return { mode: skip ? null : mode };\n}\n"],"mappings":";;;;;AA+CA,IAAM,IAAqB,CAAG;;;;;;;;;;;GAaxB,IAAoB,CAAG;;;;;;;;;;;;;;;;GAkBvB,IAAuB,CAAG;;;;;;;;;;;;;;;;;AA+DhC,SAAgB,EACd,GAAG,GACqB;CACxB,IAAM,IAAU,EAAM,QAAQ,MAAkC,MAAS,KAAK;AAI9E,QAHI,EAAQ,WAAW,IAAU,OAC7B,EAAQ,SAAS,UAAU,GAAS,YACpC,EAAQ,SAAS,aAAa,GAAS,eACpC;;AAGT,IAAM,IAAiB,KACjB,IAAoB;AAE1B,SAAS,EAAwB,GAAuB;AAGtD,QAFI,MAAS,YAAkB,IAC3B,MAAS,WAAiB,IACvB;;AAQT,SAAS,EACP,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AAU;;EAEpB,YAAY;EACb,CAAC;AAiBF,QAfA,QAAgB;AACd,IAAW,UAAU;IACpB,CAAC,EAAQ,CAAC,EAIb,QAAgB;AACd,MAAI,KAAQ,MAAS,UAAW;EAChC,IAAM,IAAK,kBAAkB;AACvB,UAAO,WAAa,OAAe,SAAS,oBAAoB,YACpE,GAAS;KACR,EAAe;AAClB,eAAa,cAAc,EAAG;IAC7B;EAAC;EAAM;EAAM;EAAgB;EAAQ,CAAC,EAElC,EAAE,MAAM,IAAO,OAAO,GAAM"}
|
|
1
|
+
{"version":3,"file":"useLiveRefresh.js","names":[],"sources":["../../../src/planmagnet/hooks/useLiveRefresh.ts"],"sourcesContent":["import { useCallback, useEffect, useRef, useState } from 'react';\nimport { gql } from '@apollo/client';\nimport { useApolloClient, useSubscription } from '@apollo/client/react';\nimport { clearGraphqlFetchResponseCache } from '@burdenoff/fe-libs/shared/graphql';\nimport { usePlanMagnet } from '../providers/PlanMagnetProvider';\n\n/**\n * Live updates (PDM-05/11/21, ANR-23): a page subscribes to a thin, workspace-scoped event stream over the\n * gateway SSE path and re-reads its own named queries when something relevant changed — it never applies the\n * event payload as data (the payload carries identifiers and `changedFields` only, by server design, so a\n * subscriber re-reads under its own permissions instead of trusting something that bypassed RBAC and row-level\n * scoping). See `useDataSinkSubscription.ts` (microfe-bigconsole) for the sibling pattern this generalizes:\n * `skip` when the ids a subscription needs haven't loaded yet, and treat a transport/backend error as expected\n * degradation, not a page-breaking failure.\n *\n * Every event stream requires `workspaceId` server-side — a subscription whose `workspaceId` is not the\n * caller's own workspace is refused by the gateway, so this hook always reads it from `usePlanMagnet()` rather\n * than accepting it as a prop a caller could get wrong.\n *\n * Connection lifecycle. SSE has no connect acknowledgement: a refused subscription (bad variables, another\n * workspace, no auth) comes back at once as an error, while an accepted one simply stays open with nothing to\n * say until something changes. So a stream still open and error-free after `connectTimeoutMs` is treated as\n * live, and the first event proves it earlier. The server closes a stream after 60 s without events\n * (`REALTIME_SUBSCRIPTION_IDLE_TIMEOUT_MS` in the svc), which Apollo reports as completion — that is routine,\n * so the hook resubscribes rather than going quiet. A stream that keeps completing within seconds of opening is\n * not healthy and degrades to polling.\n *\n * Graceful fallback (this is the point of the hook, not an edge case): if the subscription errors, or keeps\n * closing as soon as it opens, `mode` becomes `'polling'` and a 30-second interval takes over, paused while the\n * tab is hidden (`document.visibilityState`). There is no reconnect-to-live attempt within one mount — once\n * degraded, a page stays on polling until it remounts. `standalone` dev/Storybook builds (no SSE link\n * configured — see `PlanMagnetProvider`) always take this path; that is expected, not a defect, and is why a\n * subscription error here is never surfaced as a page error.\n */\n\nexport type LiveRefreshKind = 'workItem' | 'project' | 'sprint';\nexport type LiveRefreshMode = 'connecting' | 'live' | 'polling';\n\ninterface LiveEvent {\n kind: string;\n id: string;\n workspaceId: string;\n projectId?: string | null;\n changedFields: string[];\n actorId: string;\n at: string;\n}\n\nconst ON_PROJECT_UPDATED = gql`\n subscription PlanmagnetLiveProjectUpdated($workspaceId: ID!, $projectId: ID) {\n planmagnetOnProjectUpdated(workspaceId: $workspaceId, projectId: $projectId) {\n kind\n id\n workspaceId\n changedFields\n actorId\n at\n }\n }\n`;\n\nconst ON_SPRINT_UPDATED = gql`\n subscription PlanmagnetLiveSprintUpdated($workspaceId: ID!, $sprintId: ID, $projectId: ID) {\n planmagnetOnSprintUpdated(\n workspaceId: $workspaceId\n sprintId: $sprintId\n projectId: $projectId\n ) {\n kind\n id\n projectId\n workspaceId\n changedFields\n actorId\n at\n }\n }\n`;\n\nconst ON_WORK_ITEM_UPDATED = gql`\n subscription PlanmagnetLiveWorkItemUpdated($workspaceId: ID!, $projectId: ID, $workItemId: ID) {\n planmagnetOnWorkItemUpdated(\n workspaceId: $workspaceId\n projectId: $projectId\n workItemId: $workItemId\n ) {\n kind\n id\n projectId\n workspaceId\n changedFields\n actorId\n at\n }\n }\n`;\n\nexport interface UseLiveRefreshOptions {\n /** Which event stream to subscribe to — see `PlanmagnetOn{Project,Sprint,WorkItem}Updated` in the schema. */\n kind: LiveRefreshKind;\n /** Narrows the stream server-side. Omitted on `workItem`/`project` this is a workspace-wide stream (the\n * Dashboard and role dashboards want every project's events); `sprint` needs `sprintId` to mean anything on a\n * single sprint's page, so the hook skips subscribing until it has one. */\n projectId?: string | null;\n /** For `kind: 'sprint'`, at least one of `sprintId`/`projectId` is required — one sprint's own events, or\n * every sprint in one project's. Neither means \"skip\" (every sprint workspace-wide has no current caller). */\n sprintId?: string | null;\n /** Narrows a `workItem`-kind stream to one item. Unused by every current caller (the board/dashboards want\n * every item's events for their scope) but supported for a future single-item page. */\n workItemId?: string | null;\n /** Apollo operation names this page's queries were declared with — refetched by name\n * (`client.refetchQueries({ include })`) on a (debounced, optionally throttled) event. Never the literal\n * query document, and never the event's own payload used as data. */\n queries: readonly string[];\n /** Coalesces a burst of events (e.g. a bulk update moving 20 cards) into one refetch. Default 500. */\n debounceMs?: number;\n /** A floor between refetches once debounced, for a page whose queries are expensive to re-run on every\n * change (ANR-23: the Dashboard and role dashboards, at most once per 15s). Unset: only the debounce window\n * applies. A pulse arriving inside the floor is never dropped — it runs at the floor's far edge (trailing). */\n minIntervalMs?: number;\n /** How long an open, error-free subscription stays \"Connecting…\" before it counts as live. Default 8000. */\n connectTimeoutMs?: number;\n /** Polling cadence once on the fallback path. Default 30000 (ANR-23/PDM-05: \"every 30s\"). */\n pollIntervalMs?: number;\n /** An extra gate beyond the kind's own required id(s) — e.g. a sprint page's `workItem`-kind stream (no id of\n * its own is required) should still wait for the sprint's `projectId` to resolve, and skip entirely for a\n * team-scoped sprint (no `projectId` at all) rather than falling back to a workspace-wide stream. Default\n * `true` (no extra gate). */\n enabled?: boolean;\n}\n\nexport interface UseLiveRefreshResult {\n /** `null` while a required id (e.g. a sprint page before `sprintId` resolves) hasn't loaded — there is\n * nothing to subscribe to yet, so `LiveStatus` renders nothing rather than a misleading \"Connecting…\". */\n mode: LiveRefreshMode | null;\n}\n\n/** Rolls up more than one `useLiveRefresh` result into the single indicator a page shows (e.g. the sprint\n * detail page subscribes to both sprint events and the sprint's project's work item events). Reports the least\n * favorable non-null mode present — `'polling'` beats `'connecting'` beats `'live'` — so the page never claims\n * \"Live\" while one of its own streams is actually degraded. `null` (nothing subscribed yet) only when every\n * input is `null`. */\nexport function combineLiveRefreshModes(\n ...modes: ReadonlyArray<LiveRefreshMode | null>\n): LiveRefreshMode | null {\n const present = modes.filter((mode): mode is LiveRefreshMode => mode !== null);\n if (present.length === 0) return null;\n if (present.includes('polling')) return 'polling';\n if (present.includes('connecting')) return 'connecting';\n return 'live';\n}\n\nconst RAPID_CLOSE_MS = 5000;\nconst RAPID_CLOSE_LIMIT = 3;\n\nfunction subscriptionDocumentFor(kind: LiveRefreshKind) {\n if (kind === 'project') return ON_PROJECT_UPDATED;\n if (kind === 'sprint') return ON_SPRINT_UPDATED;\n return ON_WORK_ITEM_UPDATED;\n}\n\n/** A debounced, optionally-throttled trigger: bursts inside `debounceMs` coalesce into one call; once debounced,\n * a call inside `minIntervalMs` of the last one is never dropped — it runs at the floor's far edge instead.\n * `run` is expected to be a `useCallback`-stable function (the hook below's `refetch` is, since it only depends\n * on `client` and `queries`) — accepted as a normal dependency rather than stashed in a ref, so it is never\n * read or written outside an effect/callback. */\nfunction useCoalescedTrigger(\n run: () => void,\n debounceMs: number,\n minIntervalMs: number | undefined\n) {\n const debounceTimer = useRef<ReturnType<typeof setTimeout> | null>(null);\n const floorTimer = useRef<ReturnType<typeof setTimeout> | null>(null);\n const lastRunAt = useRef(0);\n const floorPending = useRef(false);\n\n const runNow = useCallback(() => {\n floorPending.current = false;\n lastRunAt.current = Date.now();\n run();\n }, [run]);\n\n const trigger = useCallback(() => {\n if (debounceTimer.current) clearTimeout(debounceTimer.current);\n debounceTimer.current = setTimeout(() => {\n debounceTimer.current = null;\n if (!minIntervalMs) {\n runNow();\n return;\n }\n const elapsed = Date.now() - lastRunAt.current;\n if (elapsed >= minIntervalMs) {\n runNow();\n return;\n }\n if (floorPending.current) return; // a trailing run is already scheduled for this window\n floorPending.current = true;\n floorTimer.current = setTimeout(runNow, minIntervalMs - elapsed);\n }, debounceMs);\n }, [debounceMs, minIntervalMs, runNow]);\n\n useEffect(\n () => () => {\n if (debounceTimer.current) clearTimeout(debounceTimer.current);\n if (floorTimer.current) clearTimeout(floorTimer.current);\n },\n []\n );\n\n return trigger;\n}\n\nexport function useLiveRefresh({\n kind,\n projectId,\n sprintId,\n workItemId,\n queries,\n debounceMs = 500,\n minIntervalMs,\n connectTimeoutMs = 8000,\n pollIntervalMs = 30000,\n enabled = true,\n}: UseLiveRefreshOptions): UseLiveRefreshResult {\n const { workspaceId } = usePlanMagnet();\n const client = useApolloClient();\n\n // 'sprint' means something scoped to either one sprint (a sprint's own page) or every sprint in one project (a\n // project-scoped dashboard) — it needs at least one of the two ids, never neither (that would be every sprint\n // in the whole workspace, which no current caller wants). 'project' always needs its one id.\n const requiredIdMissing =\n (kind === 'sprint' && !sprintId && !projectId) || (kind === 'project' && !projectId);\n const skip = !workspaceId || requiredIdMissing || !enabled;\n\n // Identifies what we'd subscribe to right now — `null` when there's nothing to. `queries` is deliberately not\n // part of this: which QUERIES a page refetches changing (it never does, in practice — every caller passes a\n // module-level const array) shouldn't reset a live connection, only what STREAM we're on should.\n const subscriptionKey = skip\n ? null\n : `${kind}:${workspaceId}:${projectId ?? ''}:${sprintId ?? ''}:${workItemId ?? ''}`;\n\n // fe-libs replays an identical query from its 15 s fetch-layer cache (shared/graphql/fetch.ts), and Apollo's\n // refetchQueries goes through it — so an event arriving within 15 s of the page's last read would re-read the\n // stale copy and the change would not show. Measured in prod: a card created ~12 s after the board loaded never\n // appeared. The cache is dropped first, exactly as a successful mutation does.\n const refetch = useCallback(() => {\n clearGraphqlFetchResponseCache();\n void client.refetchQueries({ include: [...queries] });\n }, [client, queries]);\n\n const trigger = useCoalescedTrigger(refetch, debounceMs, minIntervalMs);\n\n const [mode, setMode] = useState<LiveRefreshMode | null>(subscriptionKey ? 'connecting' : null);\n const [modeKey, setModeKey] = useState<string | null>(subscriptionKey);\n\n // Reset to \"connecting\" (or \"nothing to do\") the moment what we'd subscribe to changes — switching project,\n // sprint or page. This is the React-documented \"adjust state when a value changes\" pattern: a direct setState\n // call guarded by comparing against the last-seen key, during render, rather than in an effect — it lands in\n // the very render that changed, with no stale \"still connecting to the OLD target\" frame first.\n if (subscriptionKey !== modeKey) {\n setModeKey(subscriptionKey);\n setMode(subscriptionKey ? 'connecting' : null);\n }\n\n // The connect window needs a real timer; its only setState call lives inside the timeout's own callback (an\n // update \"when external state changes\"), never synchronously in the effect body. A refused subscription has\n // already errored into 'polling' by now (errors arrive at once), so a still-\"connecting\" one is open and\n // accepted — see the lifecycle note above.\n useEffect(() => {\n if (!subscriptionKey) return;\n const timer = setTimeout(() => {\n setMode((current) => (current === 'connecting' ? 'live' : current));\n }, connectTimeoutMs);\n return () => clearTimeout(timer);\n }, [subscriptionKey, connectTimeoutMs]);\n\n // Rapid-completion guard for the resubscribe below: when each stream closes within RAPID_CLOSE_MS of opening,\n // RAPID_CLOSE_LIMIT times in a row, the transport is not holding the stream open and polling takes over.\n const openedAt = useRef(0);\n const rapidCloses = useRef(0);\n const resubscribeTimer = useRef<ReturnType<typeof setTimeout> | null>(null);\n useEffect(() => {\n openedAt.current = Date.now();\n rapidCloses.current = 0;\n return () => {\n if (resubscribeTimer.current) clearTimeout(resubscribeTimer.current);\n resubscribeTimer.current = null;\n };\n }, [subscriptionKey]);\n\n // The server's idle close (60 s without events), or the ALB ending a long-lived response: routine, so open a\n // fresh stream. Deferred a tick so Apollo finishes tearing down the completed one first. `restart` comes back\n // from `useSubscription` below, so it is reached through a ref kept current by an effect.\n const restartRef = useRef<(() => void) | null>(null);\n const handleComplete = useCallback(() => {\n const lived = Date.now() - openedAt.current;\n rapidCloses.current = lived < RAPID_CLOSE_MS ? rapidCloses.current + 1 : 0;\n if (rapidCloses.current >= RAPID_CLOSE_LIMIT) {\n setMode('polling');\n return;\n }\n resubscribeTimer.current = setTimeout(() => {\n resubscribeTimer.current = null;\n openedAt.current = Date.now();\n restartRef.current?.();\n }, 0);\n }, []);\n\n const { restart } = useSubscription<{\n planmagnetOnProjectUpdated?: LiveEvent;\n planmagnetOnSprintUpdated?: LiveEvent;\n planmagnetOnWorkItemUpdated?: LiveEvent;\n }>(subscriptionDocumentFor(kind), {\n variables: {\n workspaceId,\n projectId: projectId ?? undefined,\n sprintId: sprintId ?? undefined,\n workItemId: workItemId ?? undefined,\n },\n skip,\n onData: () => {\n // Proof the subscription is live: the connect-timeout above only flips a still-\"connecting\" mode, so this\n // is a no-op once already 'live', and never resurrects a mode that errored into 'polling'.\n setMode((current) => (current === 'connecting' ? 'live' : current));\n trigger();\n },\n onError: (error) => {\n // Covers both a real backend/network failure and the expected \"no SSE transport configured\" case in a\n // standalone/Storybook build (see PlanMagnetProvider) — either way the correct behavior is the same:\n // degrade to polling rather than break the page. Logged at debug level only; this is not a user-facing\n // error state.\n console.debug('[useLiveRefresh] subscription unavailable, falling back to polling:', {\n kind,\n message: error instanceof Error ? error.message : String(error),\n });\n setMode('polling');\n },\n onComplete: handleComplete,\n });\n\n useEffect(() => {\n restartRef.current = restart;\n }, [restart]);\n\n // Polling fallback: the same queries, every `pollIntervalMs`, paused while the tab is hidden. No separate\n // throttle window here — the interval itself is the pacing (30s default, already above any ANR-23 floor).\n useEffect(() => {\n if (skip || mode !== 'polling') return;\n const id = setInterval(() => {\n if (typeof document !== 'undefined' && document.visibilityState === 'hidden') return;\n refetch();\n }, pollIntervalMs);\n return () => clearInterval(id);\n }, [skip, mode, pollIntervalMs, refetch]);\n\n return { mode: skip ? null : mode };\n}\n"],"mappings":";;;;;;AAgDA,IAAM,IAAqB,CAAG;;;;;;;;;;;GAaxB,IAAoB,CAAG;;;;;;;;;;;;;;;;GAkBvB,IAAuB,CAAG;;;;;;;;;;;;;;;;;AA+DhC,SAAgB,EACd,GAAG,GACqB;CACxB,IAAM,IAAU,EAAM,QAAQ,MAAkC,MAAS,KAAK;AAI9E,QAH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A;GACtB,YAAY,KAAc,KAAA;GAC3B;EACD;EACA,cAAc;AAIZ,GADA,GAAS,MAAa,MAAY,eAAe,SAAS,EAAS,EACnE,GAAS;;EAEX,UAAU,MAAU;AASlB,GAJA,QAAQ,MAAM,uEAAuE;IACnF;IACA,SAAS,aAAiB,QAAQ,EAAM,UAAU,OAAO,EAAM;IAChE,CAAC,EACF,EAAQ,UAAU;;EAEpB,YAAY;EACb,CAAC;AAiBF,QAfA,QAAgB;AACd,IAAW,UAAU;IACpB,CAAC,EAAQ,CAAC,EAIb,QAAgB;AACd,MAAI,KAAQ,MAAS,UAAW;EAChC,IAAM,IAAK,kBAAkB;AACvB,UAAO,WAAa,OAAe,SAAS,oBAAoB,YACpE,GAAS;KACR,EAAe;AAClB,eAAa,cAAc,EAAG;IAC7B;EAAC;EAAM;EAAM;EAAgB;EAAQ,CAAC,EAElC,EAAE,MAAM,IAAO,OAAO,GAAM"}
|
|
@@ -3,4 +3,5 @@ export { PlanMagnetAdminRoot } from './admin/PlanMagnetAdminRoot';
|
|
|
3
3
|
export type { PlanMagnetRootProps, NavItem, FooterItem } from './types';
|
|
4
4
|
export { usePlanMagnet, usePlanMagnetNavigate } from './providers/PlanMagnetProvider';
|
|
5
5
|
export { usePlanMagnetStore } from './store/planmagnetStore';
|
|
6
|
+
export { INTEGRATIONS_SYNCS_PATH, INTEGRATIONS_NEW_SYNC_PATH, INTEGRATIONS_SYNC_DETAIL_PATH, integrationsSyncDetailPath, } from './integrations/routes';
|
|
6
7
|
//# sourceMappingURL=index.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/planmagnet/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,cAAc,EAAE,MAAM,kBAAkB,CAAC;AAClD,OAAO,EAAE,mBAAmB,EAAE,MAAM,6BAA6B,CAAC;AAClE,YAAY,EAAE,mBAAmB,EAAE,OAAO,EAAE,UAAU,EAAE,MAAM,SAAS,CAAC;AACxE,OAAO,EAAE,aAAa,EAAE,qBAAqB,EAAE,MAAM,gCAAgC,CAAC;AACtF,OAAO,EAAE,kBAAkB,EAAE,MAAM,yBAAyB,CAAC"}
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/planmagnet/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,cAAc,EAAE,MAAM,kBAAkB,CAAC;AAClD,OAAO,EAAE,mBAAmB,EAAE,MAAM,6BAA6B,CAAC;AAClE,YAAY,EAAE,mBAAmB,EAAE,OAAO,EAAE,UAAU,EAAE,MAAM,SAAS,CAAC;AACxE,OAAO,EAAE,aAAa,EAAE,qBAAqB,EAAE,MAAM,gCAAgC,CAAC;AACtF,OAAO,EAAE,kBAAkB,EAAE,MAAM,yBAAyB,CAAC;AAG7D,OAAO,EACL,uBAAuB,EACvB,0BAA0B,EAC1B,6BAA6B,EAC7B,0BAA0B,GAC3B,MAAM,uBAAuB,CAAC"}
|
package/dist/planmagnet/index.js
CHANGED
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Integrations (sync) route targets (AUT-08/40/09/06/10/24), exported so the host shell (`planmagnet-app`, where
|
|
3
|
+
* the "Integrations" sidebar entry itself lives) can build a `NavItem` against real, routed paths instead of a
|
|
4
|
+
* hand-typed string that can drift from `PlanMagnetRoutes.tsx`. Relative, no leading slash — the same form
|
|
5
|
+
* `PlanMagnetRoot.tsx` passes through `joinPath(basePath, ...)` for every other nav entry in this package, and
|
|
6
|
+
* the same form `path="…"` carries in `PlanMagnetRoutes.tsx`.
|
|
7
|
+
*/
|
|
8
|
+
export declare const INTEGRATIONS_SYNCS_PATH = "integrations/syncs-page";
|
|
9
|
+
export declare const INTEGRATIONS_NEW_SYNC_PATH = "integrations/new-sync-page";
|
|
10
|
+
export declare const INTEGRATIONS_SYNC_DETAIL_PATH = "integrations/sync-detail-page";
|
|
11
|
+
/** `integrations/sync-detail-page/<id>` for a specific sync, or the bare list path with no id yet. */
|
|
12
|
+
export declare function integrationsSyncDetailPath(id: string | null | undefined): string;
|
|
13
|
+
//# sourceMappingURL=routes.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"routes.d.ts","sourceRoot":"","sources":["../../../src/planmagnet/integrations/routes.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AACH,eAAO,MAAM,uBAAuB,4BAA4B,CAAC;AACjE,eAAO,MAAM,0BAA0B,+BAA+B,CAAC;AACvE,eAAO,MAAM,6BAA6B,kCAAkC,CAAC;AAE7E,sGAAsG;AACtG,wBAAgB,0BAA0B,CAAC,EAAE,EAAE,MAAM,GAAG,IAAI,GAAG,SAAS,GAAG,MAAM,CAIhF"}
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
//#region src/planmagnet/integrations/routes.ts
|
|
2
|
+
var e = "integrations/syncs-page", t = "integrations/new-sync-page", n = "integrations/sync-detail-page";
|
|
3
|
+
function r(t) {
|
|
4
|
+
return t ? `${n}/${encodeURIComponent(t)}` : e;
|
|
5
|
+
}
|
|
6
|
+
//#endregion
|
|
7
|
+
export { t as INTEGRATIONS_NEW_SYNC_PATH, e as INTEGRATIONS_SYNCS_PATH, n as INTEGRATIONS_SYNC_DETAIL_PATH, r as integrationsSyncDetailPath };
|
|
8
|
+
|
|
9
|
+
//# sourceMappingURL=routes.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"routes.js","names":[],"sources":["../../../src/planmagnet/integrations/routes.ts"],"sourcesContent":["/**\n * Integrations (sync) route targets (AUT-08/40/09/06/10/24), exported so the host shell (`planmagnet-app`, where\n * the \"Integrations\" sidebar entry itself lives) can build a `NavItem` against real, routed paths instead of a\n * hand-typed string that can drift from `PlanMagnetRoutes.tsx`. Relative, no leading slash — the same form\n * `PlanMagnetRoot.tsx` passes through `joinPath(basePath, ...)` for every other nav entry in this package, and\n * the same form `path=\"…\"` carries in `PlanMagnetRoutes.tsx`.\n */\nexport const INTEGRATIONS_SYNCS_PATH = 'integrations/syncs-page';\nexport const INTEGRATIONS_NEW_SYNC_PATH = 'integrations/new-sync-page';\nexport const INTEGRATIONS_SYNC_DETAIL_PATH = 'integrations/sync-detail-page';\n\n/** `integrations/sync-detail-page/<id>` for a specific sync, or the bare list path with no id yet. */\nexport function integrationsSyncDetailPath(id: string | null | undefined): string {\n return id\n ? `${INTEGRATIONS_SYNC_DETAIL_PATH}/${encodeURIComponent(id)}`\n : INTEGRATIONS_SYNCS_PATH;\n}\n"],"mappings":";AAOA,IAAa,IAA0B,2BAC1B,IAA6B,8BAC7B,IAAgC;AAG7C,SAAgB,EAA2B,GAAuC;AAChF,QAAO,IACH,GAAG,EAA8B,GAAG,mBAAmB,EAAG,KAC1D"}
|
|
@@ -0,0 +1,143 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Shared shapes and constants for External Sync (AUT-06/08/09/10/20/22/23/24/40) — GraphQL Hive doc comments and
|
|
3
|
+
* `wspace-planmagnet-svc#63` are the source of truth for all of this, not guesswork:
|
|
4
|
+
*
|
|
5
|
+
* - GITHUB is the one provider with a real, live connector today (`github-connector.ts`); every other
|
|
6
|
+
* `PlanmagnetSyncProvider` is accepted by `planmagnetCreateExternalSync` (a customer can configure it ahead of
|
|
7
|
+
* time) but has no live connector, which `planmagnetSupportedSyncProviders` reports honestly (every capability
|
|
8
|
+
* flag false except `supportsFileImport`, which is the unrelated `planmagnetImportExternalIssues` CSV/JSON
|
|
9
|
+
* upload path, not an `ExternalSync` live run). The wizard reads that capability list rather than hard-coding
|
|
10
|
+
* "GitHub only" — if a second connector ships, this UI lights up for it automatically.
|
|
11
|
+
* - `ExternalSync.connectionConfig` for GITHUB is `{ token, owner, repo }` and is REDACTED server-side on every
|
|
12
|
+
* read (`token` -> `[REDACTED]`; `owner`/`repo` are not secret and pass through). It must never be displayed as
|
|
13
|
+
* if it still held the token, and never round-tripped back to the server as if `[REDACTED]` were a real value.
|
|
14
|
+
* - `ExternalSync.fieldMapping` for GITHUB is exactly two optional label-prefix strings —
|
|
15
|
+
* `{ priority?: string; dueDate?: string }` (default `"priority:"` / `"due:"`) — because GitHub Issues have no
|
|
16
|
+
* native priority or due-date column; the connector encodes/decodes them as a label of the form
|
|
17
|
+
* `{prefix}{value}` (e.g. `priority:HIGH`, `due:2026-10-01`). This is the only field-mapping shape the live
|
|
18
|
+
* connector reads; it is NOT the (unrelated) CSV/JSON import's column-name mapping.
|
|
19
|
+
* - `PlanmagnetUpdateExternalSyncInput.connectionConfig` REPLACES the whole stored config — it does not merge —
|
|
20
|
+
* so an edit that changes only the token must resend `owner`/`repo` too (read back from the redacted
|
|
21
|
+
* `connectionConfig`, which is safe since only `token` is masked), and an edit that changes owner/repo without a
|
|
22
|
+
* new token cannot be sent at all (the real token can never be read back to resend it). See
|
|
23
|
+
* `controls/SyncControls.tsx`'s `EditSyncConnectionDialog`.
|
|
24
|
+
*/
|
|
25
|
+
export declare const SYNC_PROVIDERS: readonly ["JIRA", "GITHUB", "GITLAB", "AZURE_DEVOPS", "ASANA", "TRELLO", "LINEAR", "SHORTCUT", "CLICKUP", "CUSTOM"];
|
|
26
|
+
export type SyncProvider = (typeof SYNC_PROVIDERS)[number];
|
|
27
|
+
export declare const SYNC_DIRECTIONS: readonly ["INBOUND", "OUTBOUND", "BIDIRECTIONAL"];
|
|
28
|
+
export type SyncDirection = (typeof SYNC_DIRECTIONS)[number];
|
|
29
|
+
export declare const SYNC_STATUSES: readonly ["IDLE", "SYNCING", "SUCCESS", "FAILED", "PAUSED", "DISABLED"];
|
|
30
|
+
export type SyncStatus = (typeof SYNC_STATUSES)[number];
|
|
31
|
+
export declare const CONFLICT_RESOLUTIONS: readonly ["SOURCE_WINS", "TARGET_WINS", "MANUAL"];
|
|
32
|
+
export type ConflictResolution = (typeof CONFLICT_RESOLUTIONS)[number];
|
|
33
|
+
export declare const CONFLICT_STATUSES: readonly ["OPEN", "RESOLVED"];
|
|
34
|
+
export type ConflictStatus = (typeof CONFLICT_STATUSES)[number];
|
|
35
|
+
export declare const SYNC_RUN_STATUSES: readonly ["SUCCEEDED", "FAILED", "PARTIAL"];
|
|
36
|
+
export type SyncRunStatus = (typeof SYNC_RUN_STATUSES)[number];
|
|
37
|
+
/** The two GitHub label-prefix keys `ExternalSync.fieldMapping` actually understands (github-connector.ts). */
|
|
38
|
+
export declare const GITHUB_FIELD_MAPPING_KEYS: readonly ["priority", "dueDate"];
|
|
39
|
+
export type GithubFieldMappingKey = (typeof GITHUB_FIELD_MAPPING_KEYS)[number];
|
|
40
|
+
/** The connector's own built-in defaults, used only as placeholder copy — never assumed server-side. */
|
|
41
|
+
export declare const GITHUB_FIELD_MAPPING_DEFAULTS: Record<GithubFieldMappingKey, string>;
|
|
42
|
+
export interface ProjectRef {
|
|
43
|
+
id: string;
|
|
44
|
+
name: string;
|
|
45
|
+
}
|
|
46
|
+
export interface RunHealth {
|
|
47
|
+
lastRunAt: string | null;
|
|
48
|
+
lastStatus: SyncRunStatus | null;
|
|
49
|
+
consecutiveFailures: number;
|
|
50
|
+
runsLast7Days: number;
|
|
51
|
+
}
|
|
52
|
+
export interface ExternalSyncRow {
|
|
53
|
+
id: string;
|
|
54
|
+
provider: SyncProvider;
|
|
55
|
+
direction: SyncDirection;
|
|
56
|
+
status: SyncStatus;
|
|
57
|
+
projectId: string;
|
|
58
|
+
project: ProjectRef | null;
|
|
59
|
+
externalProjectId: string;
|
|
60
|
+
externalProjectUrl: string | null;
|
|
61
|
+
conflictStrategy: ConflictResolution;
|
|
62
|
+
fieldMapping: unknown;
|
|
63
|
+
/** Stored but not yet read by any run (sync.service.ts) — surfaced honestly in the edit form, not hidden. */
|
|
64
|
+
syncFilters: unknown;
|
|
65
|
+
lastSyncedAt: string | null;
|
|
66
|
+
lastSyncError: string | null;
|
|
67
|
+
totalItemsSynced: number;
|
|
68
|
+
createdAt: string;
|
|
69
|
+
updatedAt: string;
|
|
70
|
+
runHealth: RunHealth;
|
|
71
|
+
}
|
|
72
|
+
export interface SyncProviderCapability {
|
|
73
|
+
provider: SyncProvider;
|
|
74
|
+
supportsImport: boolean;
|
|
75
|
+
supportsExport: boolean;
|
|
76
|
+
supportsBidirectional: boolean;
|
|
77
|
+
supportsFileImport: boolean;
|
|
78
|
+
supportsConnectionTest: boolean;
|
|
79
|
+
}
|
|
80
|
+
export interface SyncRunRow {
|
|
81
|
+
id: string;
|
|
82
|
+
direction: SyncDirection;
|
|
83
|
+
status: SyncRunStatus;
|
|
84
|
+
startedAt: string;
|
|
85
|
+
finishedAt: string;
|
|
86
|
+
itemsCreated: number;
|
|
87
|
+
itemsUpdated: number;
|
|
88
|
+
itemsSkipped: number;
|
|
89
|
+
errorCount: number;
|
|
90
|
+
conflictCount: number;
|
|
91
|
+
errorMessage: string | null;
|
|
92
|
+
triggeredBy: string;
|
|
93
|
+
}
|
|
94
|
+
export interface ExternalMappingRef {
|
|
95
|
+
id: string;
|
|
96
|
+
internalId: string;
|
|
97
|
+
internalType: string;
|
|
98
|
+
externalId: string;
|
|
99
|
+
externalType: string;
|
|
100
|
+
externalUrl: string | null;
|
|
101
|
+
}
|
|
102
|
+
export interface SyncConflictRow {
|
|
103
|
+
id: string;
|
|
104
|
+
createdAt: string;
|
|
105
|
+
fields: string[];
|
|
106
|
+
localUpdatedAt: string;
|
|
107
|
+
remoteUpdatedAt: string;
|
|
108
|
+
resolution: ConflictResolution | null;
|
|
109
|
+
resolvedAt: string | null;
|
|
110
|
+
resolvedBy: string | null;
|
|
111
|
+
status: ConflictStatus;
|
|
112
|
+
mapping: ExternalMappingRef | null;
|
|
113
|
+
mappingId: string;
|
|
114
|
+
}
|
|
115
|
+
/** `PlanmagnetSyncResult` — what `planmagnetStartSync` returns. */
|
|
116
|
+
export interface SyncRunResult {
|
|
117
|
+
syncId: string;
|
|
118
|
+
success: boolean;
|
|
119
|
+
itemsCreated: number;
|
|
120
|
+
itemsUpdated: number;
|
|
121
|
+
itemsSkipped: number;
|
|
122
|
+
errorCount: number;
|
|
123
|
+
errors: string[] | null;
|
|
124
|
+
conflictCount: number;
|
|
125
|
+
durationMs: number | null;
|
|
126
|
+
syncedAt: string;
|
|
127
|
+
}
|
|
128
|
+
/** `PlanmagnetSyncConnectionTestResult` — what `planmagnetTestExternalSync` returns. */
|
|
129
|
+
export interface SyncConnectionTestResult {
|
|
130
|
+
ok: boolean;
|
|
131
|
+
message: string;
|
|
132
|
+
rateLimitRemaining: number | null;
|
|
133
|
+
}
|
|
134
|
+
export declare function providerLabel(provider: string): string;
|
|
135
|
+
export declare function directionLabel(direction: string): string;
|
|
136
|
+
/** Whether a capability supports a given direction at all — the single gate the wizard and the edit form both use. */
|
|
137
|
+
export declare function directionSupported(capability: Pick<SyncProviderCapability, 'supportsImport' | 'supportsExport' | 'supportsBidirectional'>, direction: SyncDirection): boolean;
|
|
138
|
+
/** True once a provider can run at least one live direction — the gate for selecting it in the wizard at all. */
|
|
139
|
+
export declare function providerIsLive(capability: Pick<SyncProviderCapability, 'supportsImport' | 'supportsExport' | 'supportsBidirectional'>): boolean;
|
|
140
|
+
export declare function isValidGithubOwner(value: string): boolean;
|
|
141
|
+
export declare function isValidGithubRepo(value: string): boolean;
|
|
142
|
+
export declare function parseGithubFieldMapping(value: unknown): Record<GithubFieldMappingKey, string>;
|
|
143
|
+
//# sourceMappingURL=syncTypes.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"syncTypes.d.ts","sourceRoot":"","sources":["../../../src/planmagnet/integrations/syncTypes.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;GAuBG;AAEH,eAAO,MAAM,cAAc,qHAWjB,CAAC;AACX,MAAM,MAAM,YAAY,GAAG,CAAC,OAAO,cAAc,CAAC,CAAC,MAAM,CAAC,CAAC;AAE3D,eAAO,MAAM,eAAe,mDAAoD,CAAC;AACjF,MAAM,MAAM,aAAa,GAAG,CAAC,OAAO,eAAe,CAAC,CAAC,MAAM,CAAC,CAAC;AAE7D,eAAO,MAA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