{"version":3,"sources":["../src/types/config.ts","../src/types/step.ts","../src/types/target.ts","../src/types/state.ts","../src/context/tourkit-context.ts","../src/utils/position.ts","../src/context/tourkit-provider.tsx","../src/context/tour-context.ts","../src/utils/dom.ts","../src/utils/logger.ts","../src/hooks/use-advance-on.ts","../src/hooks/use-broadcast.ts","../src/lib/flow-session.ts","../src/utils/storage.ts","../src/utils/throttle.ts","../src/hooks/use-flow-session.ts","../src/hooks/use-persistence.ts","../src/hooks/use-route-persistence.ts","../src/lib/audience.ts","../src/lib/validate-tour.ts","../src/lib/diagnostic.ts","../src/utils/branch.ts","../src/lib/tour-engine/helpers.ts","../src/lib/tour-engine/handle-branch-target.ts","../src/lib/wait-for-step-target.ts","../src/lib/tour-engine/navigate-to-step.ts","../src/registry/tour-registry.tsx","../src/context/tour-provider.tsx","../src/hooks/use-tour.ts","../src/hooks/use-element-position.ts","../src/hooks/use-step.ts","../src/hooks/use-spotlight.ts","../src/hooks/use-keyboard.ts","../src/hooks/use-focus-trap.ts","../src/hooks/use-media-query.ts","../src/hooks/use-branch.ts","../src/utils/scroll.ts","../src/utils/a11y.ts","../src/utils/create-tour.ts","../src/utils/create-step.ts","../src/lib/utils.ts","../src/lib/unified-slot.tsx","../src/lib/ui-library-context.tsx","../src/lib/interpolate.ts","../src/lib/i18n/locale-context.tsx","../src/lib/i18n/plural.ts","../src/lib/i18n/use-t.ts","../src/hooks/use-tour-diagnostic.ts","../src/lib/frequency.ts","../src/lib/localized-text.ts","../src/lib/segmentation/segmentation-context.tsx","../src/lib/i18n/use-resolve-localized-text.ts","../src/lib/i18n/use-resolved-text.ts","../src/registry/use-tour-actions.ts","../src/lib/segmentation/use-segment.ts","../src/lib/segmentation/csv.ts"],"names":["defaultKeyboardConfig","defaultSpotlightConfig","defaultPersistenceConfig","defaultA11yConfig","defaultScrollConfig","isVisibleStep","step","resolveTarget","t","initialTourState","TourKitContext","createContext","useTourKitContext","context","useContext","useDirection","direction","isRTL","getDocumentDirection","mirrorSide","side","mirrorAlignment","alignment","mirrorPlacementForRTL","placement","parsePlacement","mirroredSide","mirroredAlignment","getElementRect","element","rect","getViewportDimensions","parts","getOppositeSide","resolveDirection","configDir","TourKitProvider","children","config","onTourStart","onTourComplete","onTourSkip","onStepView","setDirection","fe","resolved","observer","value","jsx","TourContext","useTourContext","useTourContextOptional","getElement","target","isElementVisible","windowHeight","windowWidth","isElementPartiallyVisible","waitForElement","selector","timeout","signal","resolve","reject","timeoutId","onAbort","cleanup","el","FOCUSABLE_SELECTOR","getFocusableElements","container","style","getScrollParent","parent","overflow","overflowX","overflowY","LOG_LEVELS","getDefaultLevel","shouldLog","level","logger","newConfig","args","useAdvanceOn","options","enabled","cleanupRef","useRef","isActive","currentStep","next","useEffect","event","handler","targetElement","isAdvancing","handleEvent","error","domEvent","dispatchAdvanceEvent","NOOP_RETURN","useBroadcast","channelName","isAvailable","channel","j","post","msg","subscribe","wrapped","e","isPlainObject","hasCommonFields","v","isFlowSessionV1","isFlowSessionV2","serialize","session","parse","raw","parsed","isExpired","ttlMs","createStorageAdapter","storageType","createNoopStorage","createCookieStorage","escapeRegex","s","expires","path","key","match","date","safeJSONParse","fallback","createPrefixedStorage","storage","prefix","prefixKey","createMemoryStorage","data","index","throttleRAF","callback","rafId","lastArgs","throttled","throttleTime","ms","lastCallTime","execute","now","remaining","throttleLeading","DEFAULT_TTL_MS_SESSION","DEFAULT_TTL_MS_LOCAL","SAVE_THROTTLE_MS","ACTIVE_KEY_SUFFIX","getDefaultTtl","useFlowSession","tourId","keyPrefix","D","storageKey","readSession","setSession","ready","setReady","latestRef","throttledSave","stepIndex","currentRoute","ctx","err","save","clear","usePersistence","mergedConfig","useMemo","adapter","getCompletedTours","useCallback","getSkippedTours","getDontShowAgain","getLastStep","markCompleted","completed","markSkipped","skipped","setDontShowAgain","saveStep","reset","id","DEFAULT_KEY","DEFAULT_EXPIRY_MS","memoryStorage","useRoutePersistence","expiryMs","getStorage","U","state","load","isStale","externalVersion","setExternalVersion","isSegmentAudience","audience","warnedUnknownSegments","evaluateAudience","segments","userContext","caller","matchesAudience","evaluateConditions","conditions","condition","matchesCondition","explainAudience","result","segment","userSegments","operator","contextValue","getNestedValue","obj","keys","current","validateConditions","errors","FORBIDDEN_HIDDEN_FIELDS","TourValidationError","validateTour","tour","field","BUILTIN_GATE_ORDER","gateStructure","detail","gateAudience","gatePersistence","gateRoute","matcher","mode","matches","firstVisibleStep","gateTarget","gateWhen","gateAutostart","finalize","reasons","evaluatedAt","firstFailingGate","r","explainTour","extensions","structure","gate","MAX_BRANCH_DEPTH","isBranchToTour","isBranchSkip","isBranchWait","isSpecialTarget","isBranchResolver","branch","resolveBranch","depth","resolveTargetToIndex","currentIndex","stepIdMap","totalSteps","newIndex","isLoopDetected","stepId","visitCount","maxVisits","isNavigationNeeded","router","matchMode","isOnRoute","buildCallbackContext","evaluateStepWhen","findNextVisibleStepIndex","startIndex","steps","stepContext","findNearestVisibleStepIndex","forwardIndex","handleBranchTargetImpl","branchContext","actionId","currentTour","currentStepId","firstStep","toTour","newStepIndex","newTourStepMap","i","targetIndex","targetStep","visibleIndex","TourRouteError","waitForStepTarget","opts","advancePastHiddenStep","cursor","stepIdLookup","stepCtx","branchCtx","navigateToStepImpl","localStepIdMap","chain","needed","strategy","stuckStep","entries","listeners","notify","listener","isNonProductionEnv","register","entry","ref","get","update","prev","fn","snapshot","live","prune","pruned","tourRegistry","MAX_HIDDEN_CHAIN","createStoppedState","handleStartTour","visitedSteps","stepVisitCount","handleStepNavigation","handleReset","findAutoStartTour","tours","completedTours","auto","tourReducer","action","skippedTours","newTours","updatedTour","newVisitedSteps","newStepVisitCount","diagnoseHintFired","TourProvider","routePersistence","autoNavigate","onNavigationRequired","onTourPaused","onStepError","diagnose","diagnosticGates","enableTestBridge","diagnostics","setDiagnostics","f","tourKitContext","persistenceConfig","resetPersistence","persistTerminalTours","setDataState","initialState","dispatch","userContextKey","diagnosticGatesKey","g","tourIdsKey","currentRouteKey","cancelled","gates","stepRoute","sel","pairs","flow","tabId","broadcast","onTourPausedRef","currentActiveRef","completedTourIdRef","skippedTourIdRef","flowRestoreAttemptedRef","restored","restoredTour","startTimer","timerEnded","endTimer","dispatchStart","route","persisted","autoStartAttemptedRef","abortControllerRef","wasActiveRef","announceTsRef","pausedTourId","myTs","setData","stateRef","currentTourLiveRef","dataRef","stepIdMapRef","engineContextRef","navigateToStep","map","buildBranchContext","actionPayload","completeTour","skipTour","handleBranchTarget","start","initialIndex","nextStepIndex","nextStep","prevStepIndex","prevStep","goTo","skip","complete","stop","_tourId","_value","goToStep","startTour","tourStepMap","triggerBranchAction","payload","controllerRef","ids","unregisters","unregister","u","isThisTourActive","progress","bridgeMethods","bridgeMethodsRef","testBridgeWarnedRef","bridge","jsxs","AdvanceOnEffect","useTour","activeTourId","isLoading","isTransitioning","currentStepIndex","contextStart","contextGoToStep","contextStartTour","tourIdOrStepIndex","isFirstStep","isLastStep","isStepActive","getStep","useElementPosition","setElement","useState","setRect","scrollParent","setScrollParent","observerRef","throttledUpdate","useStep","isVisible","setIsVisible","hasCompleted","setHasCompleted","targetRect","show","hide","useSpotlight","setTargetRect","setConfig","targetRef","updateRect","throttledUpdateRect","spotlightConfig","overlayStyle","cutoutStyle","padding","borderRadius","useKeyboardNavigation","handleKeyDown","active","inertRegistry","applyBackgroundInert","affected","child","existing","record","useFocusTrap","inertBackground","containerRef","previousActiveElement","isTrapping","restoreInert","focusable","first","last","activate","deactivate","useMediaQuery","query","onChange","mediaQuery","getSnapshot","useSyncExternalStore","usePrefersReducedMotion","useReducedMotion","reduce","setReduce","useBranch","availableActions","hasAction","triggerAction","previewAction","previewContext","scrollIntoView","duration","scrollTo","position","behavior","getScrollPosition","LOCK_KEY","lockScroll","body","released","announce","message","politeness","announcer","generateId","prefersReducedMotion","getStepAnnouncement","stepTitle","stepInfo","tourIdCounter","createTour","createNamedTour","stepIdCounter","createStep","content","createNamedStep","cn","inputs","twMerge","clsx","UnifiedSlot","xe","props","forwarded","childProps","childRef","getElementRef","mergedRef","mergeRefs","mergedProps","mergeProps","Fragment","elementWithRef","elementProps","refs","validRefs","slotProps","overrideProps","propName","slotValue","childValue","UILibraryContext","UILibraryProvider","library","useUILibrary","TEMPLATE_RE","interpolate","template","vars","defaultFallback","warnOnMissing","_match","rawKey","rawFallback","acc","k","LocaleContext","LocaleProvider","locale","messages","deriveDir","useLocale","RTL","pluralRulesCache","getPluralRules","rules","resolvePlural","ch","blockStart","c","blockEnd","blockBody","headerMatch","varName","rawCount","count","otherBranch","findPluralBranch","exactBranch","category","catBranch","nameStart","name","text","useT","useTourDiagnostic","canShowByFrequency","rule","daysBetween","canShowAfterDismissal","getViewLimit","a","b","isI18nKey","Ctx","SegmentationProvider","currentUserId","memo","useSegmentationContext","useResolveLocalizedText","useResolvedText","effectiveVars","FROZEN_NOOP","getServerSnapshot","useTourActions","St","evaluateSegment","seg","useSegment","useSegments","out","parseUserIdsFromCsv","csv","lines","line","startIdx","HEADER_RE","firstColumn","seen"],"mappings":"+eAyKO,IAAMA,EAAAA,CAAkD,CAC7D,OAAA,CAAS,IAAA,CACT,SAAU,CAAC,YAAA,CAAc,OAAO,CAAA,CAChC,QAAA,CAAU,CAAC,WAAW,CAAA,CACtB,SAAU,CAAC,QAAQ,EACnB,SAAA,CAAW,IACb,CAAA,CAEaC,EAAAA,CAAoD,CAC/D,OAAA,CAAS,KACT,KAAA,CAAO,oBAAA,CACP,QAAS,CAAA,CACT,YAAA,CAAc,EACd,OAAA,CAAS,IAAA,CACT,iBAAA,CAAmB,GAAA,CACnB,WAAA,CAAa,KACf,EAEaC,EAAAA,CAMT,CACF,QAAS,IAAA,CACT,OAAA,CAAS,eACT,SAAA,CAAW,SAAA,CACX,YAAA,CAAc,IAAA,CACd,cAAA,CAAgB,IAAA,CAChB,cAAe,KACjB,CAAA,CAEaC,GAA0C,CACrD,aAAA,CAAe,KACf,QAAA,CAAU,QAAA,CACV,SAAA,CAAW,IAAA,CACX,YAAA,CAAc,IAAA,CACd,cAAe,S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AOI,CAAAA,CAAK5V,CAAC,EACbA,CAAAA,EAAAA,CAEF,OAAOwV,CAAAA,CAAI,IAAA,EACb","file":"index.cjs","sourcesContent":["/**\n * Side of target element for positioning\n */\nexport type Side = 'top' | 'bottom' | 'left' | 'right'\n\n/**\n * Alignment along the side\n */\nexport type Alignment = 'start' | 'center' | 'end'\n\n/**\n * Combined placement (side + optional alignment)\n */\nexport type Placement = Side | `${Side}-${Alignment}`\n\n/**\n * Point coordinates\n */\nexport interface Position {\n  x: number\n  y: number\n}\n\n/**\n * Rectangle dimensions\n */\nexport interface Rect {\n  x: number\n  y: number\n  width: number\n  height: number\n}\n\n/**\n * Keyboard navigation configuration\n */\nexport interface KeyboardConfig {\n  enabled?: boolean\n  nextKeys?: string[]\n  prevKeys?: string[]\n  exitKeys?: string[]\n  trapFocus?: boolean\n}\n\n/**\n * Spotlight/overlay configuration\n */\nexport interface SpotlightConfig {\n  enabled?: boolean\n  color?: string\n  padding?: number\n  borderRadius?: number\n  animate?: boolean\n  animationDuration?: number\n  clickToExit?: boolean\n}\n\n/**\n * Storage interface for custom adapters\n */\nexport interface Storage {\n  getItem: (key: string) => string | null | Promise<string | null>\n  setItem: (key: string, value: string) => void | Promise<void>\n  removeItem: (key: string) => void | Promise<void>\n}\n\n/**\n * Active flow session configuration — single tour at a time, scoped to one tab.\n * Differs from `useRoutePersistence`, which is multi-tour cross-route state.\n *\n * @remarks\n * Opt-in: undefined by default. When set, `useFlowSession` will persist the\n * active tour's `(tourId, stepIndex)` so a hard reload resumes it in place.\n */\nexport interface FlowSessionConfig {\n  storage: 'sessionStorage' | 'localStorage'\n  /** TTL in ms. Default: 1h for sessionStorage, 24h for localStorage. */\n  ttlMs?: number\n  /**\n   * Storage key (under the configured `keyPrefix`).\n   * Default: `'flow:active'` — full key shape `${keyPrefix}:flow:active`.\n   * The persisted blob carries its own `tourId`, so a single fixed key is\n   * sufficient for the active-tour resume case (one active tour per tab).\n   */\n  key?: string\n}\n\n/**\n * Cross-tab pause/resume gate (BroadcastChannel-based).\n * Pauses the tour in this tab when another tab posts `tour:active`.\n *\n * @remarks\n * Opt-in: undefined by default. Recommended when using `flowSession.storage = 'localStorage'`\n * so a tour started in tab A doesn't double-show after the user closed it in tab B.\n */\nexport interface CrossTabConfig {\n  enabled: boolean\n  /** Channel name. Default: `'tourkit:active-flow'`. */\n  channel?: string\n}\n\n/**\n * Persistence configuration\n */\nexport interface PersistenceConfig {\n  enabled?: boolean\n  storage?: 'localStorage' | 'sessionStorage' | 'cookie' | Storage\n  keyPrefix?: string\n  rememberStep?: boolean\n  trackCompleted?: boolean\n  dontShowAgain?: boolean\n  /**\n   * Active flow session — single tour at a time, scoped to one tab.\n   * Differs from `useRoutePersistence`, which is multi-tour cross-route state.\n   */\n  flowSession?: FlowSessionConfig\n  /**\n   * Cross-tab pause/resume gate (BroadcastChannel-based).\n   * Pauses tour in this tab when another tab posts `tour:active`.\n   */\n  crossTab?: CrossTabConfig\n}\n\n/**\n * Accessibility configuration\n */\nexport interface A11yConfig {\n  announceSteps?: boolean\n  ariaLive?: 'polite' | 'assertive' | 'off'\n  focusTrap?: boolean\n  restoreFocus?: boolean\n  reducedMotion?: 'respect' | 'always-animate' | 'never-animate'\n}\n\n/**\n * Scroll behavior configuration\n */\nexport interface ScrollConfig {\n  enabled?: boolean\n  behavior?: 'auto' | 'smooth'\n  block?: 'start' | 'center' | 'end' | 'nearest'\n  offset?: number\n}\n\n/**\n * Text direction for RTL/LTR layouts\n */\nexport type Direction = 'ltr' | 'rtl' | 'auto'\n\n/**\n * Global TourKit configuration\n */\nexport interface TourKitConfig {\n  keyboard?: KeyboardConfig\n  spotlight?: SpotlightConfig\n  persistence?: PersistenceConfig\n  a11y?: A11yConfig\n  scroll?: ScrollConfig\n  /**\n   * Text direction for RTL/LTR support\n   * - 'ltr': Left-to-right (default)\n   * - 'rtl': Right-to-left (Arabic, Hebrew, Persian, etc.)\n   * - 'auto': Detect from document.dir\n   * @default 'auto'\n   */\n  dir?: Direction\n}\n\n// Default configurations\nexport const defaultKeyboardConfig: Required<KeyboardConfig> = {\n  enabled: true,\n  nextKeys: ['ArrowRight', 'Enter'],\n  prevKeys: ['ArrowLeft'],\n  exitKeys: ['Escape'],\n  trapFocus: true,\n}\n\nexport const defaultSpotlightConfig: Required<SpotlightConfig> = {\n  enabled: true,\n  color: 'rgba(0, 0, 0, 0.5)',\n  padding: 8,\n  borderRadius: 4,\n  animate: true,\n  animationDuration: 300,\n  clickToExit: false,\n}\n\nexport const defaultPersistenceConfig: Required<\n  Omit<PersistenceConfig, 'storage' | 'flowSession' | 'crossTab'>\n> & {\n  storage: 'localStorage'\n  flowSession?: FlowSessionConfig\n  crossTab?: CrossTabConfig\n} = {\n  enabled: true,\n  storage: 'localStorage',\n  keyPrefix: 'tourkit',\n  rememberStep: true,\n  trackCompleted: true,\n  dontShowAgain: false,\n}\n\nexport const defaultA11yConfig: Required<A11yConfig> = {\n  announceSteps: true,\n  ariaLive: 'polite',\n  focusTrap: true,\n  restoreFocus: true,\n  reducedMotion: 'respect',\n}\n\nexport const defaultScrollConfig: Required<ScrollConfig> = {\n  enabled: true,\n  behavior: 'smooth',\n  block: 'center',\n  offset: 20,\n}\n","import type React from 'react'\nimport type { LocalizedText } from '../lib/localized-text'\nimport type { AudienceCondition } from './audience'\nimport type { Branch } from './branch'\nimport type { Placement } from './config'\nimport type { TourCallbackContext } from './state'\nimport type { TourTarget } from './target'\n\n/**\n * Structural alias of `MediaSlotProps` from `@tour-kit/media`. Re-declared\n * inline here so `@tour-kit/core` does not take a (type-only or otherwise)\n * dependency on `@tour-kit/media` — core sits at the bottom of the dep graph.\n *\n * The shape MUST stay assignment-compatible with `MediaSlotProps`. Update both\n * sites if the public surface changes.\n */\nexport interface TourStepMedia {\n  src: string\n  type?: 'auto' | 'youtube' | 'vimeo' | 'loom' | 'wistia' | 'video' | 'gif' | 'lottie' | 'image'\n  poster?: string\n  aspectRatio?: '16/9' | '4/3' | '1/1' | '9/16' | '21/9' | 'auto'\n  className?: string\n  alt?: string\n  title?: string\n  autoplay?: boolean\n  loop?: boolean\n  muted?: boolean\n}\n\n/**\n * Audience prop shape — discriminated by `Array.isArray()`.\n *\n * - Array branch: legacy inline conditions evaluated via `matchesAudience`.\n * - Object branch: named segment lookup via `useSegment` / `useSegments`.\n *\n * Adding the object branch is a pure widening — pre-Phase-3 consumers using\n * `audience: AudienceCondition[]` keep compiling unchanged.\n */\nexport type AudienceProp = AudienceCondition[] | { segment: string }\n\n/**\n * Fields shared by both visible and hidden steps. Hidden steps run lifecycle\n * callbacks and branching without mounting any DOM — everything UI-rendering\n * lives on `VisibleTourStep` instead.\n */\ninterface BaseTourStep<TId extends string = string> {\n  id: TId\n  /**\n   * Filter this step out for users who don't match. Accepts the legacy\n   * `AudienceCondition[]` array (evaluated via `matchesAudience`) or the\n   * `{ segment: 'name' }` object (resolved via `useSegments`).\n   */\n  audience?: AudienceProp\n  // Multi-page support\n  route?: string\n  routeDelay?: number\n  /** Route matching mode (default: 'exact') */\n  routeMatch?: 'exact' | 'startsWith' | 'contains'\n  /**\n   * How to handle navigation when the step's `route` differs from the current\n   * route.\n   *\n   * - `'auto'` (default): provider calls `router.navigate(step.route)` and\n   *   awaits the target via `waitForStepTarget` before dispatching `GO_TO_STEP`.\n   *   On timeout, throws `TourRouteError({ code: 'TARGET_NOT_FOUND' })`.\n   * - `'prompt'`: provider raises `onNavigationRequired` for a\n   *   `<TourRoutePrompt>` UI; consumer drives the navigation.\n   * - `'manual'`: provider does nothing; consumer must call\n   *   `useTourRoute().goToStepRoute()` explicitly.\n   *\n   * @default 'auto'\n   */\n  routeChangeStrategy?: 'auto' | 'prompt' | 'manual'\n  when?: (context: TourCallbackContext) => boolean | Promise<boolean>\n  waitForTarget?: boolean\n  waitTimeout?: number\n  onBeforeShow?: (\n    context: TourCallbackContext\n  ) => boolean | undefined | Promise<boolean | undefined>\n  /** Runs before the step mounts (visible) or auto-advances (hidden). */\n  onEnter?: (context: TourCallbackContext) => void | Promise<void>\n  onShow?: (context: TourCallbackContext) => void\n  onBeforeHide?: (\n    context: TourCallbackContext\n  ) => boolean | undefined | Promise<boolean | undefined>\n  onHide?: (context: TourCallbackContext) => void\n  /**\n   * Override the next navigation behavior\n   * Determines where to go when the user clicks \"Next\" or the tour advances\n   */\n  onNext?: Branch\n  /**\n   * Override the previous navigation behavior\n   * Determines where to go when the user clicks \"Back\"\n   * Set to null to disable going back from this step\n   */\n  onPrev?: Branch\n  /**\n   * Named actions that can be triggered from step content\n   * Use with useBranch().triggerAction() from your step components\n   *\n   * @example\n   * ```tsx\n   * onAction: {\n   *   'select-developer': 'developer-path-step',\n   *   'select-designer': 'designer-path-step',\n   *   'skip-onboarding': 'complete'\n   * }\n   * ```\n   */\n  onAction?: Record<string, Branch>\n}\n\n/**\n * A step that mounts a tooltip / spotlight against a target element.\n *\n * `target` and `content` are required so authors get a compile-time error if\n * they forget either — `validateTour` enforces the same at runtime.\n */\nexport interface VisibleTourStep<TId extends string = string> extends BaseTourStep<TId> {\n  /** @default 'visible' */\n  kind?: 'visible'\n  target: TourTarget\n  /**\n   * Step title. Accepts a plain string (interpolated via `interpolate`),\n   * a `{ key: string }` dictionary lookup (resolved via `useT()`), or any\n   * `ReactNode` for arbitrary JSX. Strings without `{{var}}` tokens render\n   * unchanged — the widening is back-compat-safe.\n   */\n  title?: React.ReactNode | LocalizedText\n  /**\n   * Optional short description rendered above `content`. i18n-friendly:\n   * accepts string (interpolated) or `{ key }` (translated).\n   */\n  description?: LocalizedText\n  content: React.ReactNode\n  /**\n   * Optional media (video / GIF / Lottie / image) rendered above the step\n   * description by `<TourCard>`. Auto-detects the embed provider via URL\n   * pattern matching unless `type` is explicit.\n   */\n  media?: TourStepMedia\n  placement?: Placement\n  offset?: [number, number]\n  showNavigation?: boolean\n  showClose?: boolean\n  showProgress?: boolean\n  className?: string\n  spotlightPadding?: number\n  spotlightRadius?: number\n  interactive?: boolean\n  advanceOn?: {\n    event: 'click' | 'input' | 'custom'\n    selector?: string\n    handler?: () => boolean\n  }\n}\n\n/**\n * A step that runs lifecycle callbacks and branching without rendering UI.\n *\n * Useful for trait-based forks (`onEnter` reads context, `onNext` returns a\n * branch) and completion gates. Authoring a hidden step with any UI field\n * (`target`, `content`, `title`, `placement`, `advanceOn`) fails at compile\n * time via `?: never`, mirroring the runtime check in `validateTour`.\n */\nexport interface HiddenTourStep<TId extends string = string> extends BaseTourStep<TId> {\n  kind: 'hidden'\n  target?: never\n  content?: never\n  title?: never\n  placement?: never\n  advanceOn?: never\n}\n\n/**\n * Single step in a tour — `VisibleTourStep | HiddenTourStep` discriminated by\n * the `kind` field. Hidden steps run lifecycle callbacks (`onEnter`, `onShow`)\n * and branching logic (`onNext`) without mounting a DOM element.\n *\n * `TId` defaults to `string` so existing call sites (`TourStep`, `TourStep[]`)\n * keep working unchanged. Authors who want compile-time step-id narrowing pass\n * a literal-string union: `TourStep<'welcome' | 'pricing'>`. The canonical\n * inference pattern is `[...] as const satisfies ReadonlyArray<TourStep>`\n * combined with `StepIdOf<typeof steps>` (see below).\n */\nexport type TourStep<TId extends string = string> = VisibleTourStep<TId> | HiddenTourStep<TId>\n\nexport type StepOptions<TId extends string = string> = Omit<VisibleTourStep<TId>, 'id'>\n\n/**\n * Type guard narrowing a `TourStep` to the visible branch of the union.\n * Useful for `Array.find` / `filter` callbacks where TypeScript otherwise\n * keeps the result as the full union.\n */\nexport function isVisibleStep<TId extends string>(\n  step: TourStep<TId>\n): step is VisibleTourStep<TId> {\n  return step.kind !== 'hidden'\n}\n\n/**\n * Extract the literal-id union from a const-tuple of steps.\n *\n * @example\n * ```ts\n * const steps = [\n *   { id: 'welcome', target: '#a', content: 'a' },\n *   { id: 'pricing', target: '#b', content: 'b' },\n * ] as const satisfies ReadonlyArray<TourStep>\n *\n * type Ids = StepIdOf<typeof steps>  // 'welcome' | 'pricing'\n * ```\n */\nexport type StepIdOf<T extends ReadonlyArray<{ id: string }>> = T[number]['id']\n","import type * as React from 'react'\n\nexport type TourTargetRef = React.RefObject<HTMLElement | null>\nexport type TourTargetGetter = () => HTMLElement | null\n\n/**\n * Three accepted shapes for `target` on a `TourStep` / `HintConfig`:\n *\n *   - selector string (legacy; runs `document.querySelector` at resolve time)\n *   - `RefObject` (recommended; survives portals, CSS modules, dynamic ids)\n *   - getter function (escape hatch for lazily-mounted DOM)\n *\n * Backwards-compat: string form is documented as fallback only and emits NO\n * dev warning. Existing string selectors continue to resolve through\n * `document.querySelector` unchanged.\n */\nexport type TourTarget = string | TourTargetRef | TourTargetGetter\n\n/**\n * Resolve a `TourTarget` to a live `HTMLElement` (or `null` when missing).\n *\n * Branch order (closed, non-overlapping):\n *\n *   1. `typeof t === 'string'`                          → `document.querySelector(t)`\n *   2. `t && typeof t === 'object' && 'current' in t`   → `t.current`\n *   3. `typeof t === 'function'`                        → `t()`\n *\n * Strings can't carry `.current`, refs are objects with `.current`, thunks are\n * callables — no branch overlaps with another. Returns `HTMLElement | null`,\n * never `undefined`.\n *\n * SSR-safe: when `document` is not defined (Next.js RSC, Remix server render),\n * the string branch returns `null` without throwing.\n */\nexport function resolveTarget(t: TourTarget): HTMLElement | null {\n  if (typeof t === 'string') {\n    if (typeof document === 'undefined') return null\n    return document.querySelector<HTMLElement>(t)\n  }\n  if (t && typeof t === 'object' && 'current' in t) {\n    return t.current\n  }\n  if (typeof t === 'function') {\n    return t()\n  }\n  return null\n}\n","import type { EligibilityReport } from './diagnostic'\nimport type { TourStep } from './step'\nimport type { Tour } from './tour'\n\n/**\n * Current tour state\n */\nexport interface TourState<TStep extends TourStep = TourStep> {\n  tourId: string | null\n  isActive: boolean\n  currentStepIndex: number\n  currentStep: TStep | null\n  totalSteps: number\n  isLoading: boolean\n  isTransitioning: boolean\n  completedTours: string[]\n  skippedTours: string[]\n  /** List of step IDs visited in the current tour session */\n  visitedSteps: string[]\n  /** Map of step ID to number of times it has been visited */\n  stepVisitCount: Map<string, number>\n  /** ID of the previous step (for branch context) */\n  previousStepId: string | null\n}\n\n/**\n * Extended tour context data (passed to callbacks)\n */\nexport interface TourCallbackContext<TStep extends TourStep = TourStep> extends TourState<TStep> {\n  tour: Tour<TStep> | null\n  data: Record<string, unknown>\n}\n\n/**\n * Tour action methods.\n *\n * `goToStep` and `startTour`'s `stepId` are narrowed to `TStep['id']` when a\n * concrete step type is supplied, giving const-authored tours compile-time\n * misspelling errors. With the default `TStep = TourStep`, `id`/`stepId` widen\n * back to `string` — preserving every existing call site.\n */\nexport interface TourActions<TStep extends TourStep = TourStep> {\n  start: (tourId?: string, stepIndex?: number) => void\n  next: () => void\n  prev: () => void\n  goTo: (stepIndex: number) => void\n  skip: () => void\n  complete: () => void\n  stop: () => void\n  setDontShowAgain: (tourId: string, value: boolean) => void\n  reset: (tourId?: string) => void\n  setData: (key: string, value: unknown) => void\n  /**\n   * Navigate directly to a step by its ID.\n   *\n   * The `id` parameter is narrowed to `TStep['id']` — pass a literal-union\n   * step type (e.g., `TourStep<'welcome' | 'pricing'>`) to make misspellings\n   * fail at compile time.\n   */\n  goToStep: <TId extends TStep['id'] = TStep['id']>(stepId: TId) => Promise<void>\n  /**\n   * Start a different tour (for cross-tour branching).\n   *\n   * @param tourId - The tour to start\n   * @param stepId - Optional step ID (narrowed to `TStep['id']`) or numeric index\n   */\n  startTour: <TId extends TStep['id'] = TStep['id']>(\n    tourId: string,\n    stepId?: TId | number\n  ) => Promise<void>\n  /**\n   * Trigger a branch action defined in the current step's onAction\n   * @param actionId - The action ID to trigger\n   * @param payload - Optional data to pass to the branch resolver\n   */\n  triggerBranchAction: (actionId: string, payload?: unknown) => Promise<void>\n}\n\n/**\n * Combined context value\n */\nexport interface TourContextValue<TStep extends TourStep = TourStep>\n  extends TourState<TStep>,\n    TourActions<TStep> {\n  tour: Tour<TStep> | null\n  data: Record<string, unknown>\n  /**\n   * Per-tour diagnostic reports — populated only when the provider is mounted\n   * with `diagnose={true}`. Each key is a registered tour id; the value is the\n   * latest `EligibilityReport` produced by `explainTour`. `undefined` when\n   * diagnostics are off (the default in production builds).\n   */\n  diagnostics?: Record<string, EligibilityReport>\n}\n\n/**\n * Initial state\n */\nexport const initialTourState: TourState = {\n  tourId: null,\n  isActive: false,\n  currentStepIndex: 0,\n  currentStep: null,\n  totalSteps: 0,\n  isLoading: false,\n  isTransitioning: false,\n  completedTours: [],\n  skippedTours: [],\n  visitedSteps: [],\n  stepVisitCount: new Map(),\n  previousStepId: null,\n}\n","import { createContext, useContext } from 'react'\nimport type { BranchTarget, TourKitConfig } from '../types'\n\nexport interface TourKitContextValue {\n  config: TourKitConfig\n  /**\n   * Resolved text direction ('ltr' or 'rtl')\n   * Automatically resolved from config.dir or document.dir\n   */\n  direction: 'ltr' | 'rtl'\n  /**\n   * Whether the current direction is RTL\n   */\n  isRTL: boolean\n  // Global callbacks\n  onTourStart?: (tourId: string) => void\n  onTourComplete?: (tourId: string) => void\n  onTourSkip?: (tourId: string, stepIndex: number) => void\n  onStepView?: (tourId: string, stepId: string, stepIndex: number) => void\n  /**\n   * Called when a branch action is triggered from a step\n   * @param tourId - The current tour ID\n   * @param stepId - The step where the action was triggered\n   * @param actionId - The action ID that was triggered\n   * @param target - The resolved branch target\n   */\n  onBranchAction?: (tourId: string, stepId: string, actionId: string, target: BranchTarget) => void\n  /**\n   * Called when branching to a different tour\n   * @param fromTourId - The tour being navigated from\n   * @param toTourId - The tour being navigated to\n   * @param fromStepId - The step where the branch occurred\n   */\n  onTourBranch?: (fromTourId: string, toTourId: string, fromStepId: string) => void\n}\n\nexport const TourKitContext = createContext<TourKitContextValue | null>(null)\n\nTourKitContext.displayName = 'TourKitContext'\n\n/**\n * Hook to access TourKit context\n * Provides access to global config, direction (RTL/LTR), and callbacks\n *\n * @throws Error if used outside of TourKitProvider\n */\nexport function useTourKitContext(): TourKitContextValue {\n  const context = useContext(TourKitContext)\n\n  if (!context) {\n    throw new Error('useTourKitContext must be used within a TourKitProvider')\n  }\n\n  return context\n}\n\n/**\n * Hook to access RTL direction information\n * Returns direction ('ltr' | 'rtl') and isRTL boolean\n */\nexport function useDirection(): { direction: 'ltr' | 'rtl'; isRTL: boolean } {\n  const { direction, isRTL } = useTourKitContext()\n  return { direction, isRTL }\n}\n","import type { Alignment, Placement, Rect, Side } from '../types'\n\n/**\n * Detect document direction\n */\nexport function getDocumentDirection(): 'ltr' | 'rtl' {\n  if (typeof document === 'undefined') return 'ltr'\n  const dir = document.documentElement.dir || document.body.dir\n  return dir === 'rtl' ? 'rtl' : 'ltr'\n}\n\n/**\n * Mirror a side for RTL\n */\nexport function mirrorSide(side: Side, isRTL: boolean): Side {\n  if (!isRTL) return side\n  if (side === 'left') return 'right'\n  if (side === 'right') return 'left'\n  return side\n}\n\n/**\n * Mirror an alignment for RTL\n */\nexport function mirrorAlignment(alignment: Alignment, isRTL: boolean): Alignment {\n  if (!isRTL) return alignment\n  if (alignment === 'start') return 'end'\n  if (alignment === 'end') return 'start'\n  return alignment\n}\n\n/**\n * Mirror a placement for RTL layout\n * - left ↔ right\n * - start ↔ end\n */\nexport function mirrorPlacementForRTL(placement: Placement, isRTL: boolean): Placement {\n  if (!isRTL) return placement\n\n  const { side, alignment } = parsePlacement(placement)\n  const mirroredSide = mirrorSide(side, true)\n  const mirroredAlignment = mirrorAlignment(alignment, true)\n\n  if (mirroredAlignment === 'center') {\n    return mirroredSide as Placement\n  }\n\n  return `${mirroredSide}-${mirroredAlignment}` as Placement\n}\n\n/**\n * Get element's position including scroll offset\n */\nexport function getElementRect(element: HTMLElement): Rect {\n  const rect = element.getBoundingClientRect()\n\n  return {\n    x: rect.x + window.scrollX,\n    y: rect.y + window.scrollY,\n    width: rect.width,\n    height: rect.height,\n  }\n}\n\n/**\n * Get current viewport dimensions\n */\nexport function getViewportDimensions(): { width: number; height: number } {\n  return {\n    width: window.innerWidth || document.documentElement.clientWidth,\n    height: window.innerHeight || document.documentElement.clientHeight,\n  }\n}\n\n/**\n * Parse placement string into side and alignment\n */\nexport function parsePlacement(placement: Placement): {\n  side: Side\n  alignment: Alignment\n} {\n  const parts = placement.split('-') as [Side, Alignment?]\n\n  return {\n    side: parts[0],\n    alignment: parts[1] ?? 'center',\n  }\n}\n\n/**\n * Get the opposite side\n */\nexport function getOppositeSide(side: Side): Side {\n  const opposites: Record<Side, Side> = {\n    top: 'bottom',\n    bottom: 'top',\n    left: 'right',\n    right: 'left',\n  }\n\n  return opposites[side]\n}\n","import * as React from 'react'\nimport type { TourKitConfig } from '../types'\nimport { getDocumentDirection } from '../utils/position'\nimport { TourKitContext, type TourKitContextValue } from './tourkit-context'\n\nexport interface TourKitProviderProps {\n  children: React.ReactNode\n  config?: TourKitConfig\n  onTourStart?: (tourId: string) => void\n  onTourComplete?: (tourId: string) => void\n  onTourSkip?: (tourId: string, stepIndex: number) => void\n  onStepView?: (tourId: string, stepId: string, stepIndex: number) => void\n}\n\n/**\n * Resolve direction from config\n * - 'ltr' or 'rtl': Use as-is\n * - 'auto' or undefined: Detect from document.dir\n */\nfunction resolveDirection(configDir: TourKitConfig['dir']): 'ltr' | 'rtl' {\n  if (configDir === 'ltr' || configDir === 'rtl') {\n    return configDir\n  }\n  // 'auto' or undefined - detect from document\n  return getDocumentDirection()\n}\n\nexport function TourKitProvider({\n  children,\n  config = {},\n  onTourStart,\n  onTourComplete,\n  onTourSkip,\n  onStepView,\n}: TourKitProviderProps) {\n  // Hydration safety: only an explicit config.dir may influence the first\n  // render. 'auto' (or undefined) reads document.dir, which SSR can't see —\n  // seeding it in the initializer makes the first client render diverge from\n  // the server HTML on RTL pages. The effect below resolves the real\n  // direction immediately after mount.\n  const [direction, setDirection] = React.useState<'ltr' | 'rtl'>(() =>\n    config.dir === 'ltr' || config.dir === 'rtl' ? config.dir : 'ltr'\n  )\n\n  // Update direction when config changes or document dir changes\n  React.useEffect(() => {\n    const resolved = resolveDirection(config.dir)\n    setDirection(resolved)\n\n    // If auto-detecting, observe document dir changes\n    if (config.dir === 'auto' || config.dir === undefined) {\n      if (typeof MutationObserver !== 'undefined' && typeof document !== 'undefined') {\n        const observer = new MutationObserver(() => {\n          setDirection(getDocumentDirection())\n        })\n\n        observer.observe(document.documentElement, {\n          attributes: true,\n          attributeFilter: ['dir'],\n        })\n\n        return () => observer.disconnect()\n      }\n    }\n  }, [config.dir])\n\n  const isRTL = direction === 'rtl'\n\n  const value = React.useMemo<TourKitContextValue>(\n    () => ({\n      config,\n      direction,\n      isRTL,\n      onTourStart,\n      onTourComplete,\n      onTourSkip,\n      onStepView,\n    }),\n    [config, direction, isRTL, onTourStart, onTourComplete, onTourSkip, onStepView]\n  )\n\n  return <TourKitContext.Provider value={value}>{children}</TourKitContext.Provider>\n}\n","import { createContext, useContext } from 'react'\nimport type { TourContextValue, TourStep } from '../types'\n\nexport const TourContext = createContext<TourContextValue | null>(null)\n\nTourContext.displayName = 'TourContext'\n\nexport function useTourContext<TStep extends TourStep = TourStep>(): TourContextValue<TStep> {\n  const context = useContext(TourContext)\n\n  if (!context) {\n    throw new Error('useTourContext must be used within a TourProvider')\n  }\n\n  // `as unknown as` is intentional: the runtime context always carries the wide\n  // `TourContextValue<TourStep>`; the `<TStep>` generic is an opt-in narrowing\n  // the caller asserts. Same trade-off React's typed-context pattern accepts.\n  return context as unknown as TourContextValue<TStep>\n}\n\nexport function useTourContextOptional<\n  TStep extends TourStep = TourStep,\n>(): TourContextValue<TStep> | null {\n  // See `useTourContext` — same opt-in narrowing escape hatch.\n  return useContext(TourContext) as unknown as TourContextValue<TStep> | null\n}\n","import { type TourTarget, resolveTarget } from '../types/target'\n\n/**\n * Safely get an element from various target shapes.\n *\n * Accepts the full `TourTarget` union (string selector, `RefObject`, or\n * getter function), plus the legacy direct `HTMLElement` passthrough used by\n * internal callers that already hold the resolved node. Selector / ref / getter\n * branches delegate to `resolveTarget` so the resolver stays the single source\n * of truth.\n */\nexport function getElement(target: TourTarget | HTMLElement | null): HTMLElement | null {\n  if (!target) return null\n  // SSR-safe instanceof — `HTMLElement` is undefined on bare Node, and\n  // `instanceof undefined` throws TypeError. `resolveTarget` already\n  // SSR-guards its own string branch; this matches that contract. Under\n  // SSR no live `HTMLElement` instance can exist anyway, so the fall-through\n  // path is defensive only.\n  if (typeof HTMLElement !== 'undefined' && target instanceof HTMLElement) return target\n  return resolveTarget(target as TourTarget)\n}\n\n/**\n * Check if element is fully visible in viewport\n */\nexport function isElementVisible(element: HTMLElement): boolean {\n  const rect = element.getBoundingClientRect()\n  const windowHeight = window.innerHeight || document.documentElement.clientHeight\n  const windowWidth = window.innerWidth || document.documentElement.clientWidth\n\n  return rect.top >= 0 && rect.left >= 0 && rect.bottom <= windowHeight && rect.right <= windowWidth\n}\n\n/**\n * Check if element is at least partially visible\n */\nexport function isElementPartiallyVisible(element: HTMLElement): boolean {\n  const rect = element.getBoundingClientRect()\n  const windowHeight = window.innerHeight || document.documentElement.clientHeight\n  const windowWidth = window.innerWidth || document.documentElement.clientWidth\n\n  return rect.top < windowHeight && rect.bottom > 0 && rect.left < windowWidth && rect.right > 0\n}\n\n/**\n * Wait for element to appear in DOM.\n *\n * @param selector - CSS selector to query against `document`\n * @param timeout - Reject after this many ms (default 5000)\n * @param signal - Optional `AbortSignal`. When aborted, the observer is\n *   disconnected and the promise rejects with `Error('aborted')`. If the\n *   signal is already aborted when called, rejects synchronously without\n *   ever attaching the observer.\n */\nexport function waitForElement(\n  selector: string,\n  timeout = 5000,\n  signal?: AbortSignal\n): Promise<HTMLElement> {\n  return new Promise((resolve, reject) => {\n    if (signal?.aborted) {\n      reject(new Error('aborted'))\n      return\n    }\n\n    const element = document.querySelector<HTMLElement>(selector)\n    if (element) {\n      resolve(element)\n      return\n    }\n\n    let timeoutId: ReturnType<typeof setTimeout> | null = null\n    let observer: MutationObserver | null = null\n    let onAbort: (() => void) | null = null\n\n    const cleanup = () => {\n      if (timeoutId) {\n        clearTimeout(timeoutId)\n        timeoutId = null\n      }\n      if (observer) {\n        observer.disconnect()\n        observer = null\n      }\n      if (onAbort && signal) {\n        signal.removeEventListener('abort', onAbort)\n        onAbort = null\n      }\n    }\n\n    observer = new MutationObserver(() => {\n      const el = document.querySelector<HTMLElement>(selector)\n      if (el) {\n        cleanup()\n        resolve(el)\n      }\n    })\n\n    observer.observe(document.body, {\n      childList: true,\n      subtree: true,\n    })\n\n    timeoutId = setTimeout(() => {\n      cleanup()\n      reject(new Error(`Element \"${selector}\" not found within ${timeout}ms`))\n    }, timeout)\n\n    if (signal) {\n      onAbort = () => {\n        cleanup()\n        reject(new Error('aborted'))\n      }\n      signal.addEventListener('abort', onAbort, { once: true })\n    }\n  })\n}\n\nconst FOCUSABLE_SELECTOR = [\n  'a[href]:not([tabindex=\"-1\"])',\n  'button:not([disabled]):not([tabindex=\"-1\"])',\n  'textarea:not([disabled]):not([tabindex=\"-1\"])',\n  'input:not([disabled]):not([tabindex=\"-1\"])',\n  'select:not([disabled]):not([tabindex=\"-1\"])',\n  '[tabindex]:not([tabindex=\"-1\"])',\n].join(', ')\n\n/**\n * Get all focusable elements within a container\n *\n * Uses getComputedStyle rather than offsetParent so `position: fixed`\n * descendants (which have a null offsetParent) are still included.\n */\nexport function getFocusableElements(container: HTMLElement): HTMLElement[] {\n  return Array.from(container.querySelectorAll<HTMLElement>(FOCUSABLE_SELECTOR)).filter((el) => {\n    const style = getComputedStyle(el)\n    return style.display !== 'none' && style.visibility !== 'hidden'\n  })\n}\n\n/**\n * Find the scrollable parent of an element\n */\nexport function getScrollParent(element: HTMLElement): HTMLElement | Window {\n  let parent: HTMLElement | null = element.parentElement\n\n  while (parent) {\n    const { overflow, overflowX, overflowY } = getComputedStyle(parent)\n\n    if (/(auto|scroll)/.test(overflow + overflowX + overflowY)) {\n      return parent\n    }\n\n    parent = parent.parentElement\n  }\n\n  return window\n}\n","/**\n * Configurable logger utility for tour-kit\n *\n * Provides environment-aware logging with configurable levels.\n * In production, only errors are logged by default.\n * In development, warnings and errors are logged.\n *\n * @example\n * ```ts\n * import { logger } from '@tour-kit/core'\n *\n * // Configure logging level\n * logger.configure({ level: 'debug' })\n *\n * // Use logger\n * logger.debug('Debug info:', data)\n * logger.warn('Warning:', message)\n * logger.error('Error:', error)\n * ```\n */\n\nexport type LogLevel = 'debug' | 'info' | 'warn' | 'error' | 'silent'\n\nexport interface LoggerConfig {\n  level: LogLevel\n  prefix?: string\n}\n\nconst LOG_LEVELS: Record<LogLevel, number> = {\n  debug: 0,\n  info: 1,\n  warn: 2,\n  error: 3,\n  silent: 4,\n}\n\nfunction getDefaultLevel(): LogLevel {\n  // Check for production environment in a browser-safe way\n  try {\n    // Works in Node.js and bundlers that replace process.env.NODE_ENV\n    if (\n      typeof globalThis !== 'undefined' &&\n      // biome-ignore lint/suspicious/noExplicitAny: Checking for Node.js process object\n      (globalThis as any).process?.env?.NODE_ENV === 'production'\n    ) {\n      return 'error'\n    }\n  } catch {\n    // Ignore errors in environments where process is not defined\n  }\n  return 'warn'\n}\n\nlet config: LoggerConfig = {\n  level: getDefaultLevel(),\n  prefix: '[tour-kit]',\n}\n\nfunction shouldLog(level: LogLevel): boolean {\n  return LOG_LEVELS[level] >= LOG_LEVELS[config.level]\n}\n\nexport const logger = {\n  /**\n   * Configure the logger\n   */\n  configure: (newConfig: Partial<LoggerConfig>): void => {\n    config = { ...config, ...newConfig }\n  },\n\n  /**\n   * Get current logger configuration\n   */\n  getConfig: (): Readonly<LoggerConfig> => ({ ...config }),\n\n  /**\n   * Log debug messages (only in development with level='debug')\n   */\n  debug: (...args: unknown[]): void => {\n    if (shouldLog('debug')) {\n      console.log(config.prefix, ...args)\n    }\n  },\n\n  /**\n   * Log info messages\n   */\n  info: (...args: unknown[]): void => {\n    if (shouldLog('info')) {\n      console.info(config.prefix, ...args)\n    }\n  },\n\n  /**\n   * Log warning messages\n   */\n  warn: (...args: unknown[]): void => {\n    if (shouldLog('warn')) {\n      console.warn(config.prefix, ...args)\n    }\n  },\n\n  /**\n   * Log error messages\n   */\n  error: (...args: unknown[]): void => {\n    if (shouldLog('error')) {\n      console.error(config.prefix, ...args)\n    }\n  },\n}\n","import { useContext, useEffect, useRef } from 'react'\nimport { TourContext } from '../context/tour-context'\nimport { getElement } from '../utils/dom'\nimport { logger } from '../utils/logger'\n\nexport interface UseAdvanceOnOptions {\n  /** Enable/disable the advanceOn behavior (default: true) */\n  enabled?: boolean\n}\n\n/**\n * Hook to handle advanceOn behavior - automatically advances tour when\n * user performs specified action on target element\n */\nexport function useAdvanceOn(options: UseAdvanceOnOptions = {}): void {\n  const { enabled = true } = options\n  const context = useContext(TourContext)\n  const cleanupRef = useRef<(() => void) | null>(null)\n\n  if (!context) {\n    throw new Error('useAdvanceOn must be used within a TourProvider')\n  }\n\n  const { isActive, currentStep, next } = context\n\n  useEffect(() => {\n    // Clean up previous listeners\n    if (cleanupRef.current) {\n      cleanupRef.current()\n      cleanupRef.current = null\n    }\n\n    if (!enabled || !isActive || !currentStep?.advanceOn) {\n      return\n    }\n\n    const { event, selector, handler } = currentStep.advanceOn\n\n    // Get target element (defaults to document)\n    const targetElement: Element | Document = selector\n      ? (getElement(selector) ?? document)\n      : document\n\n    if (selector && targetElement === document) {\n      logger.warn(`advanceOn: Element \"${selector}\" not found for step \"${currentStep.id}\"`)\n    }\n\n    // Debounce flag to prevent multiple rapid advances\n    let isAdvancing = false\n\n    const handleEvent = () => {\n      if (isAdvancing) return\n\n      // If handler is provided, it must return true to advance\n      if (handler) {\n        try {\n          const shouldAdvance = handler()\n          if (!shouldAdvance) return\n        } catch (error) {\n          logger.warn(`advanceOn handler error for step \"${currentStep.id}\":`, error)\n          return\n        }\n      }\n\n      isAdvancing = true\n      next()\n\n      // Reset after a short delay to handle race conditions\n      setTimeout(() => {\n        isAdvancing = false\n      }, 100)\n    }\n\n    // Map event types to actual DOM events\n    const eventMap: Record<string, string> = {\n      click: 'click',\n      input: 'input',\n      custom: 'tourkit:advance', // Custom event for programmatic advance\n    }\n\n    const domEvent = eventMap[event] || event\n\n    targetElement.addEventListener(domEvent, handleEvent)\n\n    cleanupRef.current = () => {\n      targetElement.removeEventListener(domEvent, handleEvent)\n    }\n\n    return () => {\n      if (cleanupRef.current) {\n        cleanupRef.current()\n        cleanupRef.current = null\n      }\n    }\n  }, [enabled, isActive, currentStep, next])\n}\n\n/**\n * Dispatch a custom advance event (for 'custom' event type)\n * This allows programmatic advancement when the step has advanceOn: { event: 'custom' }\n *\n * @param selector - Optional CSS selector for the target element (defaults to document)\n */\nexport function dispatchAdvanceEvent(selector?: string): void {\n  const target = selector ? getElement(selector) : document\n  if (target) {\n    target.dispatchEvent(new CustomEvent('tourkit:advance', { bubbles: true }))\n  }\n}\n","import * as React from 'react'\n\nexport interface UseBroadcastReturn<TMsg> {\n  /** Post a message to all other tabs subscribing to the same channel name. */\n  post: (msg: TMsg) => void\n  /**\n   * Subscribe to messages on the channel.\n   * @returns Cleanup function — call on unmount to remove the listener.\n   */\n  subscribe: (handler: (msg: TMsg) => void) => () => void\n}\n\nconst NOOP_RETURN: UseBroadcastReturn<unknown> = {\n  post: () => {},\n  subscribe: () => () => {},\n}\n\n/**\n * Typed wrapper around `BroadcastChannel` for cross-tab pub/sub.\n *\n * Lazy-initializes the channel and closes it on unmount. When the runtime\n * does not provide `BroadcastChannel` (e.g. older Safari) or when\n * `options.enabled === false`, both `post` and `subscribe` are no-ops so\n * consumers do not need to branch.\n *\n * Self-message filtering is the consumer's responsibility — attach a\n * `tabId` to your messages and ignore matching ones.\n *\n * @typeParam TMsg - Discriminated union of message shapes for this channel.\n */\nexport function useBroadcast<TMsg>(\n  channelName: string,\n  options?: { enabled?: boolean }\n): UseBroadcastReturn<TMsg> {\n  const enabled = options?.enabled ?? true\n  const isAvailable = typeof BroadcastChannel !== 'undefined'\n\n  const channel = React.useMemo(() => {\n    if (!enabled || !isAvailable) return null\n    return new BroadcastChannel(channelName)\n  }, [enabled, isAvailable, channelName])\n\n  React.useEffect(() => {\n    return () => channel?.close()\n  }, [channel])\n\n  const post = React.useCallback(\n    (msg: TMsg) => {\n      channel?.postMessage(msg)\n    },\n    [channel]\n  )\n\n  const subscribe = React.useCallback(\n    (handler: (msg: TMsg) => void) => {\n      if (!channel) return () => {}\n      const wrapped = (e: MessageEvent) => handler(e.data as TMsg)\n      channel.addEventListener('message', wrapped)\n      return () => channel.removeEventListener('message', wrapped)\n    },\n    [channel]\n  )\n\n  // Memoize return value so consumers can safely use the hook result in\n  // effect dep arrays without re-running on every render.\n  const value = React.useMemo<UseBroadcastReturn<TMsg>>(\n    () => ({ post, subscribe }),\n    [post, subscribe]\n  )\n\n  if (!enabled || !isAvailable) {\n    return NOOP_RETURN as UseBroadcastReturn<TMsg>\n  }\n\n  return value\n}\n","/**\n * Flow session — represents the active tour's `(tourId, stepIndex, currentRoute?)`\n * so a hard reload can resume it. Stored as JSON in `sessionStorage` (default)\n * or `localStorage`.\n *\n * Validation strategy: hand-rolled type guard rather than Zod. `@tour-kit/core`\n * does not depend on Zod, and adding it for a 6-field plain-object schema\n * would add bundle weight + a runtime dep. The guards here are the single\n * source of truth for storage shape v1 and v2.\n *\n * Schema versions:\n * - V1 — original blob: `{ schemaVersion: 1, tourId, stepIndex, startedAt, lastUpdatedAt }`\n * - V2 — adds optional `currentRoute?: string` for cross-page resume.\n *\n * Migration is done in-flight by `parse()` (V1 blobs are accepted and\n * upgraded with `currentRoute: undefined`); writes always emit V2.\n */\n\nexport interface FlowSessionV1 {\n  schemaVersion: 1\n  tourId: string\n  stepIndex: number\n  /** epoch ms */\n  startedAt: number\n  /** epoch ms */\n  lastUpdatedAt: number\n}\n\nexport interface FlowSessionV2 {\n  schemaVersion: 2\n  tourId: string\n  stepIndex: number\n  /**\n   * Route the active tour was on at the last save. Used by the provider to\n   * resume on the correct URL after a hard refresh on cross-page tours.\n   * `undefined` for V1 → V2 migrated blobs and for tours without a router.\n   */\n  currentRoute?: string\n  /** epoch ms */\n  startedAt: number\n  /** epoch ms */\n  lastUpdatedAt: number\n}\n\n/**\n * Public alias — always points at the latest schema version. Internal callers\n * should use `FlowSessionV2` directly when they need to reason about wire shape.\n */\nexport type FlowSession = FlowSessionV2\n\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n  return typeof value === 'object' && value !== null\n}\n\nfunction hasCommonFields(v: Record<string, unknown>): boolean {\n  return (\n    typeof v.tourId === 'string' &&\n    v.tourId.length > 0 &&\n    typeof v.stepIndex === 'number' &&\n    Number.isInteger(v.stepIndex) &&\n    v.stepIndex >= 0 &&\n    typeof v.startedAt === 'number' &&\n    Number.isInteger(v.startedAt) &&\n    v.startedAt > 0 &&\n    typeof v.lastUpdatedAt === 'number' &&\n    Number.isInteger(v.lastUpdatedAt) &&\n    v.lastUpdatedAt > 0\n  )\n}\n\nfunction isFlowSessionV1(value: unknown): value is FlowSessionV1 {\n  if (!isPlainObject(value)) return false\n  return value.schemaVersion === 1 && hasCommonFields(value)\n}\n\nfunction isFlowSessionV2(value: unknown): value is FlowSessionV2 {\n  if (!isPlainObject(value)) return false\n  if (value.schemaVersion !== 2) return false\n  if (!hasCommonFields(value)) return false\n  // currentRoute is optional but must be a string when present\n  if (value.currentRoute !== undefined && typeof value.currentRoute !== 'string') {\n    return false\n  }\n  return true\n}\n\nexport function serialize(session: FlowSessionV2): string {\n  return JSON.stringify(session)\n}\n\n/**\n * Parse a raw storage value into a `FlowSessionV2`.\n *\n * Strategy: try V2 first, then fall back to V1 (migrating to V2 with\n * `currentRoute: undefined`). Returns `null` on any failure (null/empty input,\n * invalid JSON, wrong shape, unknown schemaVersion). Never throws.\n */\nexport function parse(raw: string | null): FlowSessionV2 | null {\n  if (!raw) return null\n  try {\n    const parsed: unknown = JSON.parse(raw)\n    if (isFlowSessionV2(parsed)) return parsed\n    if (isFlowSessionV1(parsed)) {\n      // Migrate in-flight. Write-back happens on next save() — readers should\n      // not assume the storage blob has been rewritten yet.\n      return {\n        schemaVersion: 2,\n        tourId: parsed.tourId,\n        stepIndex: parsed.stepIndex,\n        currentRoute: undefined,\n        startedAt: parsed.startedAt,\n        lastUpdatedAt: parsed.lastUpdatedAt,\n      }\n    }\n    return null\n  } catch {\n    return null\n  }\n}\n\n/**\n * Returns true when `session.lastUpdatedAt` is older than `ttlMs`.\n * `ttlMs <= 0` disables expiry (returns false).\n */\nexport function isExpired(session: FlowSessionV2, ttlMs: number): boolean {\n  if (ttlMs <= 0) return false\n  return Date.now() - session.lastUpdatedAt > ttlMs\n}\n","// Alias the project's narrow 3-method `Storage` adapter type so it doesn't\n// shadow the DOM `globalThis.Storage` shape used by `createMemoryStorage`.\nimport type { PersistenceConfig, Storage as StorageAdapter } from '../types'\n\n/**\n * Create storage adapter from config\n */\nexport function createStorageAdapter(storageType: PersistenceConfig['storage']): StorageAdapter {\n  if (typeof storageType === 'object') {\n    return storageType\n  }\n\n  if (typeof window === 'undefined') {\n    return createNoopStorage()\n  }\n\n  switch (storageType) {\n    case 'sessionStorage':\n      return window.sessionStorage\n    case 'cookie':\n      return createCookieStorage()\n    default:\n      return window.localStorage\n  }\n}\n\n/**\n * No-op storage for SSR\n */\nexport function createNoopStorage(): StorageAdapter {\n  return {\n    getItem: () => null,\n    setItem: () => {},\n    removeItem: () => {},\n  }\n}\n\n/**\n * Escape regex metacharacters so arbitrary cookie keys (which may include\n * `.`, `:`, `-`, etc. after prefixing) can be matched literally.\n */\nconst escapeRegex = (s: string): string => s.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&')\n\n/**\n * Cookie-based storage adapter\n */\nexport function createCookieStorage(\n  options: { expires?: number; path?: string } = {}\n): StorageAdapter {\n  const { expires = 365, path = '/' } = options\n\n  return {\n    getItem: (key: string) => {\n      if (typeof document === 'undefined') return null\n      const match = document.cookie.match(new RegExp(`(^| )${escapeRegex(key)}=([^;]+)`))\n      return match ? decodeURIComponent(match[2]) : null\n    },\n\n    setItem: (key: string, value: string) => {\n      if (typeof document === 'undefined') return\n      const date = new Date()\n      date.setTime(date.getTime() + expires * 24 * 60 * 60 * 1000)\n      document.cookie = `${key}=${encodeURIComponent(\n        value\n      )};expires=${date.toUTCString()};path=${path}`\n    },\n\n    removeItem: (key: string) => {\n      if (typeof document === 'undefined') return\n      document.cookie = `${key}=;expires=Thu, 01 Jan 1970 00:00:00 GMT;path=${path}`\n    },\n  }\n}\n\n/**\n * Safe JSON parse with fallback\n */\nexport function safeJSONParse<T>(value: string | null, fallback: T): T {\n  if (!value) return fallback\n\n  try {\n    return JSON.parse(value) as T\n  } catch {\n    return fallback\n  }\n}\n\n/**\n * Create storage with key prefix\n */\nexport function createPrefixedStorage(storage: StorageAdapter, prefix: string): StorageAdapter {\n  const prefixKey = (key: string) => `${prefix}:${key}`\n\n  return {\n    getItem: (key: string) => storage.getItem(prefixKey(key)),\n    setItem: (key: string, value: string) => storage.setItem(prefixKey(key), value),\n    removeItem: (key: string) => storage.removeItem(prefixKey(key)),\n  }\n}\n\n/**\n * Closure-backed in-memory implementation of the DOM `Storage` shape. Used\n * by `useRoutePersistence` and `useChecklistPersistence` as the SSR / private-\n * browsing fallback when `window.localStorage` is unavailable.\n *\n * Returns the full DOM shape (including `length` and `key(index)`) because\n * existing call sites read those properties — promoted from the\n * `_data` cast hack in `useChecklistPersistence` and the closure version in\n * `useRoutePersistence`, deduplicated in Phase 1 of the refactor train.\n *\n * Each call returns an isolated store — instances do NOT share state.\n */\nexport function createMemoryStorage(): globalThis.Storage {\n  const data: Record<string, string> = {}\n  return {\n    getItem(key: string): string | null {\n      return data[key] ?? null\n    },\n    setItem(key: string, value: string): void {\n      data[key] = value\n    },\n    removeItem(key: string): void {\n      delete data[key]\n    },\n    clear(): void {\n      for (const key of Object.keys(data)) {\n        delete data[key]\n      }\n    },\n    get length(): number {\n      return Object.keys(data).length\n    },\n    key(index: number): string | null {\n      return Object.keys(data)[index] ?? null\n    },\n  }\n}\n","/**\n * Throttle utilities for performance optimization\n * @module throttle\n */\n\ntype AnyFunction = (...args: unknown[]) => void\n\nexport interface ThrottledFunction<T extends AnyFunction> {\n  (...args: Parameters<T>): void\n  /** Cancel any pending execution */\n  cancel: () => void\n}\n\nexport interface ThrottledFunctionWithFlush<T extends AnyFunction> extends ThrottledFunction<T> {\n  /** Execute pending call immediately */\n  flush: () => void\n}\n\n/**\n * RAF-based throttling for smooth 60fps updates during scroll/resize.\n * Coalesces rapid calls to a single execution per animation frame.\n *\n * @example\n * ```ts\n * const throttledUpdate = throttleRAF(() => {\n *   element.getBoundingClientRect()\n * })\n *\n * window.addEventListener('scroll', throttledUpdate, { passive: true })\n *\n * // Cleanup\n * throttledUpdate.cancel()\n * ```\n */\nexport function throttleRAF<T extends AnyFunction>(callback: T): ThrottledFunction<T> {\n  let rafId: number | null = null\n  let lastArgs: Parameters<T> | null = null\n\n  const throttled = ((...args: Parameters<T>) => {\n    lastArgs = args\n\n    if (rafId === null) {\n      rafId = requestAnimationFrame(() => {\n        rafId = null\n        if (lastArgs) {\n          callback(...lastArgs)\n          lastArgs = null\n        }\n      })\n    }\n  }) as ThrottledFunction<T>\n\n  throttled.cancel = () => {\n    if (rafId !== null) {\n      cancelAnimationFrame(rafId)\n      rafId = null\n    }\n    lastArgs = null\n  }\n\n  return throttled\n}\n\n/**\n * Time-based throttling with trailing edge execution.\n * Queues the most recent call and executes after the interval.\n * Supports flush for immediate execution of pending call.\n *\n * @example\n * ```ts\n * const throttled = throttleTime(sendAnalytics, 1000)\n *\n * // Call multiple times - only fires once per second\n * throttled(event1)\n * throttled(event2)\n *\n * // Force immediate execution of pending call\n * throttled.flush()\n * ```\n */\nexport function throttleTime<T extends AnyFunction>(\n  callback: T,\n  ms: number\n): ThrottledFunctionWithFlush<T> {\n  let timeoutId: ReturnType<typeof setTimeout> | null = null\n  let lastArgs: Parameters<T> | null = null\n  let lastCallTime = 0\n\n  const execute = () => {\n    if (lastArgs) {\n      lastCallTime = Date.now()\n      callback(...lastArgs)\n      lastArgs = null\n    }\n  }\n\n  const throttled = ((...args: Parameters<T>) => {\n    lastArgs = args\n    const now = Date.now()\n    const remaining = ms - (now - lastCallTime)\n\n    if (remaining <= 0) {\n      if (timeoutId !== null) {\n        clearTimeout(timeoutId)\n        timeoutId = null\n      }\n      execute()\n    } else if (timeoutId === null) {\n      timeoutId = setTimeout(() => {\n        timeoutId = null\n        execute()\n      }, remaining)\n    }\n  }) as ThrottledFunctionWithFlush<T>\n\n  throttled.cancel = () => {\n    if (timeoutId !== null) {\n      clearTimeout(timeoutId)\n      timeoutId = null\n    }\n    lastArgs = null\n  }\n\n  throttled.flush = () => {\n    if (timeoutId !== null) {\n      clearTimeout(timeoutId)\n      timeoutId = null\n    }\n    execute()\n  }\n\n  return throttled\n}\n\n/**\n * Leading-edge throttle - fires immediately, then ignores calls for interval.\n * Useful for immediate user feedback while preventing rapid-fire events.\n *\n * @example\n * ```ts\n * const throttled = throttleLeading(onClick, 500)\n *\n * // First call fires immediately\n * // Subsequent calls within 500ms are ignored\n * throttled() // Executes\n * throttled() // Ignored\n * throttled() // Ignored\n * ```\n */\nexport function throttleLeading<T extends AnyFunction>(\n  callback: T,\n  ms: number\n): ThrottledFunction<T> {\n  let lastCallTime = 0\n\n  const throttled = ((...args: Parameters<T>) => {\n    const now = Date.now()\n\n    if (now - lastCallTime >= ms) {\n      lastCallTime = now\n      callback(...args)\n    }\n  }) as ThrottledFunction<T>\n\n  throttled.cancel = () => {\n    lastCallTime = 0\n  }\n\n  return throttled\n}\n","import * as React from 'react'\nimport { type FlowSessionV2, isExpired, parse, serialize } from '../lib/flow-session'\nimport type { FlowSessionConfig } from '../types/config'\nimport { logger } from '../utils/logger'\nimport { createPrefixedStorage, createStorageAdapter } from '../utils/storage'\nimport { throttleTime } from '../utils/throttle'\n\nconst DEFAULT_TTL_MS_SESSION = 60 * 60 * 1000 // 1 hour\nconst DEFAULT_TTL_MS_LOCAL = 24 * 60 * 60 * 1000 // 24 hours\nconst SAVE_THROTTLE_MS = 200\nconst ACTIVE_KEY_SUFFIX = 'flow:active'\n\nexport interface UseFlowSessionReturn {\n  session: FlowSessionV2 | null\n  /**\n   * Persist the active step. `currentRoute` is included so a hard-refresh\n   * during a multi-page tour resumes on the right URL — pass\n   * `router?.getCurrentRoute()` from the provider, or `undefined` for\n   * single-route tours.\n   */\n  save: (stepIndex: number, currentRoute?: string) => void\n  clear: () => void\n  isStale: boolean\n  /**\n   * `true` once the post-mount storage read has run (immediately when the\n   * hook is disabled). `session` is `null` until then — consumers that give\n   * the flow session precedence over other restore paths must wait for\n   * `ready` instead of treating the initial `null` as \"no session\".\n   */\n  ready: boolean\n}\n\nexport interface UseFlowSessionConfig extends FlowSessionConfig {\n  /** Storage key prefix (default: `tourkit`). Full key is `${keyPrefix}:flow:active`. */\n  keyPrefix?: string\n}\n\nconst NOOP_RETURN: UseFlowSessionReturn = {\n  session: null,\n  save: () => {},\n  clear: () => {},\n  isStale: false,\n  ready: true,\n}\n\nfunction getDefaultTtl(storage: FlowSessionConfig['storage']): number {\n  return storage === 'localStorage' ? DEFAULT_TTL_MS_LOCAL : DEFAULT_TTL_MS_SESSION\n}\n\n/**\n * Persist the active tour's session so a hard reload resumes it in place.\n *\n * Uses a single fixed storage key (`${keyPrefix}:flow:active` by default) — the\n * blob itself carries the `tourId`, so on a fresh mount the hook can discover\n * which tour was active without the caller needing to know it up front.\n *\n * The `tourId` argument identifies the tour for which `save()` writes new\n * snapshots; pass `''` to disable writes (loads still work).\n *\n * Throttle: `save()` is trailing-edge throttled at 200ms via the existing\n * `throttleTime` util — a burst of step changes coalesces into 1 storage write\n * per window.\n *\n * SSR-safe: returns no-op shape when `window` is undefined.\n * Quota-safe: `setItem` failures (`QuotaExceededError`) are logged and swallowed.\n */\nexport function useFlowSession(\n  tourId: string,\n  config?: UseFlowSessionConfig\n): UseFlowSessionReturn {\n  const isSSR = typeof window === 'undefined'\n  const enabled = !!config && !isSSR\n\n  const ttlMs = config?.ttlMs ?? (config ? getDefaultTtl(config.storage) : 0)\n  const keyPrefix = config?.keyPrefix ?? 'tourkit'\n  const storageType = config?.storage\n\n  const storage = React.useMemo(() => {\n    if (!enabled || !storageType) return null\n    return createPrefixedStorage(createStorageAdapter(storageType), keyPrefix)\n  }, [enabled, storageType, keyPrefix])\n\n  const storageKey = config?.key ?? ACTIVE_KEY_SUFFIX\n\n  const readSession = React.useCallback((): FlowSessionV2 | null => {\n    if (!storage) return null\n    try {\n      const raw = storage.getItem(storageKey)\n      if (typeof raw !== 'string' && raw !== null) return null\n      const parsed = parse(raw as string | null)\n      if (!parsed) {\n        if (raw) storage.removeItem(storageKey)\n        return null\n      }\n      if (isExpired(parsed, ttlMs)) {\n        storage.removeItem(storageKey)\n        return null\n      }\n      return parsed\n    } catch {\n      return null\n    }\n  }, [storage, storageKey, ttlMs])\n\n  // Hydration safety: the initial value must be `null` (matching SSR), never a\n  // render-time storage read. Seeding `session` in the useState initializer\n  // made the first client render differ from the server-rendered HTML, which\n  // shifts React's useId tree positions and surfaces as hydration mismatches\n  // in unrelated downstream useId consumers (e.g. the checklists launcher's\n  // aria-controls). The blob loads in the mount effect below instead.\n  const [session, setSession] = React.useState<FlowSessionV2 | null>(null)\n  const [ready, setReady] = React.useState(false)\n\n  // Load on mount and re-read when storage identity changes (e.g. config.storage swap)\n  // biome-ignore lint/correctness/useExhaustiveDependencies: only re-load on storage identity change\n  React.useEffect(() => {\n    setSession(readSession())\n    setReady(true)\n  }, [storage])\n\n  // Latest values ref — keeps the throttled callback identity stable while\n  // still writing the most recent tourId / startedAt.\n  const latestRef = React.useRef({\n    tourId,\n    storage,\n    storageKey,\n    enabled,\n    startedAt: session?.startedAt ?? null,\n  })\n  React.useEffect(() => {\n    latestRef.current = {\n      tourId,\n      storage,\n      storageKey,\n      enabled,\n      startedAt: session?.startedAt ?? null,\n    }\n  })\n\n  const throttledSave = React.useMemo(\n    () =>\n      throttleTime((...args: unknown[]) => {\n        const stepIndex = args[0] as number\n        const currentRoute = args[1] as string | undefined\n        const ctx = latestRef.current\n        if (!ctx.enabled || !ctx.storage || !ctx.tourId) return\n        const now = Date.now()\n        const next: FlowSessionV2 = {\n          schemaVersion: 2,\n          tourId: ctx.tourId,\n          stepIndex,\n          currentRoute,\n          startedAt: ctx.startedAt ?? now,\n          lastUpdatedAt: now,\n        }\n        try {\n          ctx.storage.setItem(ctx.storageKey, serialize(next))\n          setSession(next)\n        } catch (err) {\n          logger.warn('useFlowSession: setItem failed', err)\n        }\n      }, SAVE_THROTTLE_MS),\n    []\n  )\n\n  // On unmount, flush any pending throttled save so the most recent\n  // stepIndex is persisted before teardown (otherwise a fast unmount loses\n  // the trailing-edge write).\n  React.useEffect(() => () => throttledSave.flush(), [throttledSave])\n\n  const save = React.useCallback(\n    (stepIndex: number, currentRoute?: string) => {\n      throttledSave(stepIndex, currentRoute)\n    },\n    [throttledSave]\n  )\n\n  const clear = React.useCallback(() => {\n    if (!storage) return\n    try {\n      throttledSave.cancel()\n      storage.removeItem(storageKey)\n      setSession(null)\n    } catch (err) {\n      logger.warn('useFlowSession: clear failed', err)\n    }\n  }, [storage, storageKey, throttledSave])\n\n  if (!enabled) return NOOP_RETURN\n\n  return {\n    session,\n    save,\n    clear,\n    isStale: session ? isExpired(session, ttlMs) : false,\n    ready,\n  }\n}\n","import { useCallback, useMemo } from 'react'\nimport type { PersistenceConfig } from '../types'\nimport { defaultPersistenceConfig } from '../types/config'\nimport { createPrefixedStorage, createStorageAdapter, safeJSONParse } from '../utils/storage'\n\nexport interface UsePersistenceReturn {\n  getCompletedTours: () => string[]\n  getSkippedTours: () => string[]\n  getDontShowAgain: (tourId: string) => boolean\n  getLastStep: (tourId: string) => number | null\n  markCompleted: (tourId: string) => void\n  markSkipped: (tourId: string) => void\n  setDontShowAgain: (tourId: string, value: boolean) => void\n  saveStep: (tourId: string, stepIndex: number) => void\n  reset: (tourId?: string) => void\n}\n\nexport function usePersistence(config?: PersistenceConfig): UsePersistenceReturn {\n  const mergedConfig = { ...defaultPersistenceConfig, ...config }\n\n  const storage = useMemo(() => {\n    const adapter = createStorageAdapter(mergedConfig.storage)\n    return createPrefixedStorage(adapter, mergedConfig.keyPrefix ?? 'tourkit')\n  }, [mergedConfig.storage, mergedConfig.keyPrefix])\n\n  const getCompletedTours = useCallback(() => {\n    const data = storage.getItem('completed')\n    return safeJSONParse<string[]>(data as string | null, [])\n  }, [storage])\n\n  const getSkippedTours = useCallback(() => {\n    const data = storage.getItem('skipped')\n    return safeJSONParse<string[]>(data as string | null, [])\n  }, [storage])\n\n  const getDontShowAgain = useCallback(\n    (tourId: string) => {\n      const data = storage.getItem(`dontShow:${tourId}`)\n      return data === 'true'\n    },\n    [storage]\n  )\n\n  const getLastStep = useCallback(\n    (tourId: string) => {\n      const data = storage.getItem(`step:${tourId}`)\n      return data ? Number.parseInt(data as string, 10) : null\n    },\n    [storage]\n  )\n\n  const markCompleted = useCallback(\n    (tourId: string) => {\n      const completed = getCompletedTours()\n      if (!completed.includes(tourId)) {\n        completed.push(tourId)\n        storage.setItem('completed', JSON.stringify(completed))\n      }\n    },\n    [storage, getCompletedTours]\n  )\n\n  const markSkipped = useCallback(\n    (tourId: string) => {\n      const skipped = getSkippedTours()\n      if (!skipped.includes(tourId)) {\n        skipped.push(tourId)\n        storage.setItem('skipped', JSON.stringify(skipped))\n      }\n    },\n    [storage, getSkippedTours]\n  )\n\n  const setDontShowAgain = useCallback(\n    (tourId: string, value: boolean) => {\n      if (value) {\n        storage.setItem(`dontShow:${tourId}`, 'true')\n      } else {\n        storage.removeItem(`dontShow:${tourId}`)\n      }\n    },\n    [storage]\n  )\n\n  const saveStep = useCallback(\n    (tourId: string, stepIndex: number) => {\n      storage.setItem(`step:${tourId}`, String(stepIndex))\n    },\n    [storage]\n  )\n\n  const reset = useCallback(\n    (tourId?: string) => {\n      if (tourId) {\n        storage.removeItem(`step:${tourId}`)\n        storage.removeItem(`dontShow:${tourId}`)\n\n        const completed = getCompletedTours().filter((id) => id !== tourId)\n        storage.setItem('completed', JSON.stringify(completed))\n\n        const skipped = getSkippedTours().filter((id) => id !== tourId)\n        storage.setItem('skipped', JSON.stringify(skipped))\n      } else {\n        storage.removeItem('completed')\n        storage.removeItem('skipped')\n      }\n    },\n    [storage, getCompletedTours, getSkippedTours]\n  )\n\n  return {\n    getCompletedTours,\n    getSkippedTours,\n    getDontShowAgain,\n    getLastStep,\n    markCompleted,\n    markSkipped,\n    setDontShowAgain,\n    saveStep,\n    reset,\n  }\n}\n","import * as React from 'react'\nimport type { TourState } from '../types'\nimport type { MultiPagePersistenceConfig } from '../types/router'\nimport { logger } from '../utils/logger'\nimport { createMemoryStorage } from '../utils/storage'\n\ninterface PersistedRouteState {\n  tourId: string | null\n  stepIndex: number\n  completedTours: string[]\n  skippedTours: string[]\n  timestamp: number\n}\n\nconst DEFAULT_KEY = 'tourkit-route-state'\nconst DEFAULT_EXPIRY_MS = 24 * 60 * 60 * 1000 // 24 hours\n\nexport interface UseRoutePersistenceReturn {\n  /** Save current tour state */\n  save: (state: Partial<TourState>) => void\n  /** Load persisted state */\n  load: () => PersistedRouteState | null\n  /** Clear persisted state */\n  clear: () => void\n  /** Check if state is stale */\n  isStale: () => boolean\n  /**\n   * Increments whenever another tab writes to the same storage key while\n   * `syncTabs` is enabled. Subscribe to this value from a `useEffect` to\n   * re-hydrate state in response to cross-tab writes.\n   */\n  externalVersion: number\n}\n\n// Single module-scope memory store, used as SSR / `storage: 'memory'` fallback.\n// Promoted to `@tour-kit/core`'s `createMemoryStorage()` in Phase 1 of the\n// refactor train — single source of the DOM `Storage` shape across packages.\nconst memoryStorage = createMemoryStorage()\n\n/**\n * Hook for persisting tour state across page navigations.\n * Extends base persistence with route-specific handling.\n *\n * @remarks\n * Uses existing storage utilities from @tour-kit/core.\n * Handles SSR gracefully by checking for window availability.\n */\nexport function useRoutePersistence(config: MultiPagePersistenceConfig): UseRoutePersistenceReturn {\n  const storageKey = config.key ?? DEFAULT_KEY\n  const expiryMs = config.expiryMs ?? DEFAULT_EXPIRY_MS\n\n  const getStorage = React.useCallback(() => {\n    if (typeof window === 'undefined') return memoryStorage\n\n    switch (config.storage) {\n      case 'sessionStorage':\n        return window.sessionStorage\n      case 'memory':\n        return memoryStorage\n      default:\n        return window.localStorage\n    }\n  }, [config.storage])\n\n  const save = React.useCallback(\n    (state: Partial<TourState>) => {\n      if (!config.enabled) return\n\n      const storage = getStorage()\n\n      const data: PersistedRouteState = {\n        tourId: state.tourId ?? null,\n        stepIndex: state.currentStepIndex ?? 0,\n        completedTours: state.completedTours ?? [],\n        skippedTours: state.skippedTours ?? [],\n        timestamp: Date.now(),\n      }\n\n      try {\n        storage.setItem(storageKey, JSON.stringify(data))\n        // Browsers automatically fire `storage` events on other tabs when\n        // localStorage is written; no manual dispatch is needed (and firing\n        // one on the writing tab is a no-op in terms of real cross-tab sync).\n      } catch (e) {\n        logger.warn('Failed to save route state:', e)\n      }\n    },\n    [config.enabled, getStorage, storageKey]\n  )\n\n  const load = React.useCallback((): PersistedRouteState | null => {\n    if (!config.enabled) return null\n\n    const storage = getStorage()\n\n    try {\n      const raw = storage.getItem(storageKey)\n      if (!raw) return null\n\n      const data: PersistedRouteState = JSON.parse(raw)\n\n      // Check expiry\n      if (Date.now() - data.timestamp > expiryMs) {\n        storage.removeItem(storageKey)\n        return null\n      }\n\n      return data\n    } catch (e) {\n      logger.warn('Failed to load route state:', e)\n      return null\n    }\n  }, [config.enabled, getStorage, storageKey, expiryMs])\n\n  const clear = React.useCallback(() => {\n    const storage = getStorage()\n    storage.removeItem(storageKey)\n  }, [getStorage, storageKey])\n\n  const isStale = React.useCallback(() => {\n    const data = load()\n    if (!data) return true\n    return Date.now() - data.timestamp > expiryMs\n  }, [load, expiryMs])\n\n  // Listen for cross-tab sync — bump a version counter on writes to our key\n  // so consumers can subscribe via a useEffect dep and re-load().\n  const [externalVersion, setExternalVersion] = React.useState(0)\n\n  React.useEffect(() => {\n    if (!config.syncTabs || config.storage !== 'localStorage') return\n    if (typeof window === 'undefined') return\n\n    const handler = (e: StorageEvent) => {\n      if (e.key === storageKey) {\n        setExternalVersion((v) => v + 1)\n      }\n    }\n\n    window.addEventListener('storage', handler)\n    return () => window.removeEventListener('storage', handler)\n  }, [config.syncTabs, config.storage, storageKey])\n\n  return { save, load, clear, isStale, externalVersion }\n}\n","/**\n * Promoted from `@tour-kit/announcements` in Phase 1 of the UserGuiding parity\n * initiative. Re-exported there for backward compat — see `packages/announcements/src/core/audience.ts`.\n */\nimport type { AudienceCondition } from '../types/audience'\nimport type { GateReason } from '../types/diagnostic'\nimport type { AudienceProp } from '../types/step'\nimport { logger } from '../utils/logger'\n\n/**\n * Type guard narrowing `AudienceProp` to its segment-named branch. Previously\n * duplicated in `@tour-kit/react`, `@tour-kit/hints`, and `@tour-kit/announcements`.\n */\nexport function isSegmentAudience(audience: AudienceProp): audience is { segment: string } {\n  return (\n    !Array.isArray(audience) &&\n    typeof audience === 'object' &&\n    audience !== null &&\n    'segment' in audience\n  )\n}\n\n// Module-scope dedupe set: `evaluateAudience` runs inside `Array.filter`\n// inside a `useMemo`. Without this set, an unknown segment referenced by N\n// steps would emit N warnings on every memo recompute (e.g. on every\n// userContext change). Module-scope is fine — segment names are app-wide\n// stable. Test isolation: use unique segment names (see\n// `packages/core/src/__tests__/_helpers/unique-segment.ts`).\nconst warnedUnknownSegments = new Set<string>()\n\n/**\n * Pure boolean test: does the current user satisfy this audience? Single\n * source of truth shared by `useStepFilter` (react), `useHintFilter` (hints),\n * and the segment branch of `evaluateAnnouncementAudience` (announcements).\n *\n * - `undefined` audience → `true` (no filter)\n * - segment-shape `{ segment: 'x' }` → reads `segments[x] === true`; warns\n *   once per unknown segment in dev, naming the calling hook.\n * - array-shape `AudienceCondition[]` → delegates to `matchesAudience` with\n *   `userContext` (the legacy contract).\n */\nexport function evaluateAudience(\n  audience: AudienceProp | undefined,\n  segments: Record<string, boolean>,\n  userContext: Record<string, unknown> | undefined,\n  caller: string\n): boolean {\n  if (!audience) return true\n  if (isSegmentAudience(audience)) {\n    if (\n      !(audience.segment in segments) &&\n      process.env.NODE_ENV !== 'production' &&\n      !warnedUnknownSegments.has(audience.segment)\n    ) {\n      warnedUnknownSegments.add(audience.segment)\n      logger.warn(\n        `[tour-kit] ${caller} references segment \"${audience.segment}\" not registered in <SegmentationProvider>`\n      )\n    }\n    return segments[audience.segment] === true\n  }\n  return matchesAudience(audience, userContext)\n}\n\ninterface AudienceEvaluation {\n  matched: boolean\n  failingCondition?: AudienceCondition\n}\n\n/**\n * Internal shared helper: evaluate an array of conditions against a user\n * context, returning both the boolean outcome AND (on failure) the first\n * condition that did not match. `matchesAudience` projects `.matched`;\n * `explainAudience` reads `.failingCondition` to populate `detail`.\n */\nfunction evaluateConditions(\n  conditions: AudienceCondition[] | undefined,\n  userContext: Record<string, unknown> | undefined\n): AudienceEvaluation {\n  if (!conditions || conditions.length === 0) {\n    return { matched: true }\n  }\n\n  for (const condition of conditions) {\n    if (!userContext) {\n      if (condition.operator === 'not_exists') continue\n      return { matched: false, failingCondition: condition }\n    }\n    if (!matchesCondition(condition, userContext)) {\n      return { matched: false, failingCondition: condition }\n    }\n  }\n  return { matched: true }\n}\n\n/**\n * Check if user context matches audience conditions\n */\nexport function matchesAudience(\n  conditions: AudienceCondition[] | undefined,\n  userContext: Record<string, unknown> | undefined\n): boolean {\n  return evaluateConditions(conditions, userContext).matched\n}\n\n/**\n * Structured sibling of `matchesAudience` consumed by the diagnostic engine.\n * Returns a `GateReason` describing the audience-gate outcome — including the\n * first failing condition (or the failing segment) in `detail` so operators\n * see WHY the audience filter rejected the user.\n *\n * Segment-form audience (`{ segment: 'admins' }`) looks up\n * `userContext.segments` (a `string[]` listing the user's resolved segments).\n * If the segment is missing or absent, the gate fails with `AUDIENCE_MISMATCH`.\n */\nexport function explainAudience(\n  audience: AudienceProp | undefined,\n  userContext: Record<string, unknown> | undefined\n): GateReason {\n  if (!audience) {\n    return { ok: true, gate: 'audience' }\n  }\n\n  if (Array.isArray(audience)) {\n    const result = evaluateConditions(audience, userContext)\n    if (result.matched) return { ok: true, gate: 'audience' }\n    // `detail` deliberately omits `userContext` — diagnostic reports are\n    // often shipped to telemetry or rendered in dev panels, so the failing\n    // condition is enough to explain \"why\" without leaking unrelated PII.\n    return {\n      ok: false,\n      gate: 'audience',\n      code: 'AUDIENCE_MISMATCH',\n      message: 'User context did not satisfy audience filter',\n      detail: {\n        failingCondition: result.failingCondition,\n        audience,\n      },\n    }\n  }\n\n  // Segment-form: `{ segment: 'admins' }` — resolved against `userContext.segments`.\n  // The user's full segment membership is intentionally NOT echoed back in\n  // `detail` (PII / leak vector for telemetry); only the gating segment id is.\n  const segment = audience.segment\n  const userSegments = userContext?.segments\n  const segments = Array.isArray(userSegments) ? userSegments : []\n  if (segments.includes(segment)) {\n    return { ok: true, gate: 'audience' }\n  }\n  return {\n    ok: false,\n    gate: 'audience',\n    code: 'AUDIENCE_MISMATCH',\n    message: `User is not a member of segment '${segment}'`,\n    detail: {\n      segment,\n      audience,\n    },\n  }\n}\n\n/**\n * Check if a single condition matches\n */\n// biome-ignore lint/complexity/noExcessiveCognitiveComplexity: condition matching with multiple operators\nfunction matchesCondition(\n  condition: AudienceCondition,\n  userContext: Record<string, unknown>\n): boolean {\n  const { key, operator, value } = condition\n\n  // Get the value from user context using dot notation\n  const contextValue = getNestedValue(userContext, key)\n\n  switch (operator) {\n    case 'equals':\n      return contextValue === value\n\n    case 'not_equals':\n      return contextValue !== value\n\n    case 'contains':\n      if (typeof contextValue === 'string' && typeof value === 'string') {\n        return contextValue.includes(value)\n      }\n      if (Array.isArray(contextValue)) {\n        return contextValue.includes(value)\n      }\n      return false\n\n    case 'not_contains':\n      if (typeof contextValue === 'string' && typeof value === 'string') {\n        return !contextValue.includes(value)\n      }\n      if (Array.isArray(contextValue)) {\n        return !contextValue.includes(value)\n      }\n      return true\n\n    case 'in':\n      if (Array.isArray(value)) {\n        return value.includes(contextValue)\n      }\n      return false\n\n    case 'not_in':\n      if (Array.isArray(value)) {\n        return !value.includes(contextValue)\n      }\n      return true\n\n    case 'exists':\n      return contextValue !== undefined && contextValue !== null\n\n    case 'not_exists':\n      return contextValue === undefined || contextValue === null\n\n    default:\n      return false\n  }\n}\n\n/**\n * Get a nested value from an object using dot notation\n * Example: getNestedValue({ user: { plan: 'pro' } }, 'user.plan') => 'pro'\n */\nfunction getNestedValue(obj: Record<string, unknown>, path: string): unknown {\n  const keys = path.split('.')\n  let current: unknown = obj\n\n  for (const key of keys) {\n    if (current === null || current === undefined) {\n      return undefined\n    }\n    if (typeof current !== 'object') {\n      return undefined\n    }\n    current = (current as Record<string, unknown>)[key]\n  }\n\n  return current\n}\n\n/**\n * Validate audience conditions\n */\nexport function validateConditions(conditions: AudienceCondition[]): string[] {\n  const errors: string[] = []\n\n  for (const condition of conditions) {\n    if (!condition.key) {\n      errors.push('Condition key is required')\n    }\n\n    if (!condition.operator) {\n      errors.push('Condition operator is required')\n    }\n\n    // Value is required for most operators except exists/not_exists\n    if (!['exists', 'not_exists'].includes(condition.operator)) {\n      if (condition.value === undefined) {\n        errors.push(`Value is required for operator '${condition.operator}'`)\n      }\n    }\n\n    // 'in' and 'not_in' require array values\n    if (['in', 'not_in'].includes(condition.operator)) {\n      if (!Array.isArray(condition.value)) {\n        errors.push(`Value must be an array for operator '${condition.operator}'`)\n      }\n    }\n  }\n\n  return errors\n}\n","import type { Tour } from '../types'\n\nconst FORBIDDEN_HIDDEN_FIELDS = ['target', 'content', 'title', 'placement', 'advanceOn'] as const\n\ntype TourValidationCode = 'INVALID_HIDDEN_STEP' | 'HIDDEN_STEP_LOOP'\n\n/**\n * Thrown by `validateTour` (config-time) and by the provider's hidden-step\n * loop guard (runtime). Catch-site filtering uses the readonly `code` field.\n */\nexport class TourValidationError extends Error {\n  readonly code: TourValidationCode\n  readonly stepId: string\n\n  constructor(args: { code: TourValidationCode; stepId: string; message: string }) {\n    super(args.message)\n    this.name = 'TourValidationError'\n    this.code = args.code\n    this.stepId = args.stepId\n  }\n}\n\n/**\n * Validate a Tour at provider mount.\n *\n * Currently enforces: hidden steps must not declare UI fields. Throws a\n * `TourValidationError` whose message names the offending step id and field.\n *\n * Phase 3 (refactor train) — TS now rejects authored hidden steps with\n * `target`/`content`/`title`/`placement`/`advanceOn` via `?: never` on\n * `HiddenTourStep`, so this runtime pass exists to protect untyped JSON /\n * `as any` boundaries. The fields are typed as `never` on the narrowed\n * branch, so reading them returns `undefined` without needing a cast.\n */\nexport function validateTour(tour: Tour): void {\n  for (const step of tour.steps) {\n    if (step.kind !== 'hidden') continue\n    for (const field of FORBIDDEN_HIDDEN_FIELDS) {\n      if (step[field] != null) {\n        throw new TourValidationError({\n          code: 'INVALID_HIDDEN_STEP',\n          stepId: step.id,\n          message: `Hidden step \"${step.id}\" must not declare \\`${field}\\`.`,\n        })\n      }\n    }\n  }\n}\n","/**\n * Diagnostic engine — Phase 3.\n *\n * Wraps every reason a tour might not fire into a single structured\n * `EligibilityReport`. Runs seven built-in gates in a fixed order, then any\n * extension gates registered via `<TourProvider diagnosticGates>`. NEVER\n * throws: internal errors are captured as `ok: false` reasons.\n */\nimport type {\n  DiagnosticContext,\n  DiagnosticGate,\n  EligibilityReport,\n  GateReason,\n} from '../types/diagnostic'\nimport { type AudienceProp, type VisibleTourStep, isVisibleStep } from '../types/step'\nimport type { Tour } from '../types/tour'\nimport { explainAudience } from './audience'\nimport { TourValidationError, validateTour } from './validate-tour'\n\n/**\n * Canonical built-in evaluation order. Tests pin this tuple — the order is\n * part of the contract that consumers (and `<TourDebugger>`) rely on.\n */\nexport const BUILTIN_GATE_ORDER = [\n  'structure',\n  'audience',\n  'persistence',\n  'route',\n  'target',\n  'when',\n  'autostart',\n] as const\n\nfunction gateStructure(tour: Tour): GateReason {\n  try {\n    if (!Array.isArray(tour.steps) || tour.steps.length === 0) {\n      return {\n        ok: false,\n        gate: 'structure',\n        code: 'STRUCTURE_INVALID',\n        message: 'Tour has no steps',\n        detail: { tourId: tour.id, stepCount: Array.isArray(tour.steps) ? tour.steps.length : 0 },\n      }\n    }\n    validateTour(tour)\n    return { ok: true, gate: 'structure' }\n  } catch (e) {\n    const error = e as Error\n    // Preserve `TourValidationError`'s structured fields (the offending step\n    // id and the specific validation code) so operators can route on them.\n    const detail: Record<string, unknown> = { error: error.message }\n    if (error instanceof TourValidationError) {\n      detail.tourErrorCode = error.code\n      detail.stepId = error.stepId\n    }\n    return {\n      ok: false,\n      gate: 'structure',\n      code: 'STRUCTURE_INVALID',\n      message: error.message ?? 'Tour failed structural validation',\n      detail,\n    }\n  }\n}\n\nfunction gateAudience(audience: AudienceProp | undefined, ctx: DiagnosticContext): GateReason {\n  return explainAudience(audience, ctx.userContext)\n}\n\nfunction gatePersistence(tour: Tour, ctx: DiagnosticContext): GateReason {\n  if (ctx.completedTours.includes(tour.id)) {\n    return {\n      ok: false,\n      gate: 'persistence',\n      code: 'ALREADY_COMPLETED',\n      message: `Tour ${tour.id} already completed`,\n      detail: { tourId: tour.id },\n    }\n  }\n  if (ctx.skippedTours.includes(tour.id)) {\n    return {\n      ok: false,\n      gate: 'persistence',\n      code: 'ALREADY_SKIPPED',\n      message: `Tour ${tour.id} previously skipped`,\n      detail: { tourId: tour.id },\n    }\n  }\n  return { ok: true, gate: 'persistence' }\n}\n\nfunction gateRoute(tour: Tour, ctx: DiagnosticContext): GateReason {\n  if (!ctx.route) return { ok: true, gate: 'route' }\n  const { current, matcher, mode } = ctx.route\n  let matches = false\n  switch (mode) {\n    case 'exact':\n      matches = current === matcher\n      break\n    case 'startsWith':\n      matches = current.startsWith(matcher)\n      break\n    case 'contains':\n      matches = current.includes(matcher)\n      break\n    default:\n      matches = false\n  }\n  if (matches) return { ok: true, gate: 'route' }\n  return {\n    ok: false,\n    gate: 'route',\n    code: 'ROUTE_MISMATCH',\n    message: `Route ${current} does not match ${matcher} (${mode})`,\n    detail: { expected: matcher, actual: current, mode, tourId: tour.id },\n  }\n}\n\nfunction firstVisibleStep(tour: Tour): VisibleTourStep | undefined {\n  return tour.steps.find(isVisibleStep)\n}\n\nfunction gateTarget(tour: Tour, ctx: DiagnosticContext): GateReason {\n  if (!ctx.targetResolver) return { ok: true, gate: 'target' }\n  const step = firstVisibleStep(tour)\n  if (!step) return { ok: true, gate: 'target' }\n  // Refs (objects with `.current`) are not checked in diagnostic mode — runtime owns them.\n  if (typeof step.target !== 'string') return { ok: true, gate: 'target' }\n  const el = ctx.targetResolver(step.target)\n  if (el) return { ok: true, gate: 'target' }\n  return {\n    ok: false,\n    gate: 'target',\n    code: 'TARGET_NOT_FOUND',\n    message: `Selector ${step.target} did not resolve`,\n    detail: { selector: step.target, stepId: step.id, tourId: tour.id },\n  }\n}\n\nfunction gateWhen(tour: Tour): GateReason {\n  if (!tour.when) return { ok: true, gate: 'when' }\n  try {\n    const result = tour.when()\n    if (result instanceof Promise) {\n      // Async when() is owned by the runtime pipeline. Document the carveout.\n      return {\n        ok: true,\n        gate: 'when',\n        detail: {\n          note: 'Async when() callbacks are evaluated at runtime, not in diagnostic mode',\n        },\n      }\n    }\n    if (result === false) {\n      return {\n        ok: false,\n        gate: 'when',\n        code: 'WHEN_RETURNED_FALSE',\n        message: 'Tour-level when() returned false',\n        detail: { tourId: tour.id },\n      }\n    }\n    return { ok: true, gate: 'when' }\n  } catch (e) {\n    const error = e as Error\n    return {\n      ok: false,\n      gate: 'when',\n      code: 'WHEN_RETURNED_FALSE',\n      message: error.message ?? 'Tour-level when() threw',\n      detail: { error: error.message, tourId: tour.id },\n    }\n  }\n}\n\nfunction gateAutostart(tour: Tour): GateReason {\n  if (tour.autoStart === false) {\n    return {\n      ok: false,\n      gate: 'autostart',\n      code: 'AUTOSTART_DISABLED',\n      message: 'Tour has autoStart: false',\n      detail: { tourId: tour.id },\n    }\n  }\n  return { ok: true, gate: 'autostart' }\n}\n\nfunction finalize(tourId: string, reasons: GateReason[], evaluatedAt: number): EligibilityReport {\n  const firstFailingGate =\n    reasons.find((r): r is Extract<GateReason, { ok: false }> => !r.ok) ?? null\n  return {\n    tourId,\n    willFire: firstFailingGate === null,\n    reasons,\n    firstFailingGate,\n    evaluatedAt,\n  }\n}\n\n/**\n * Evaluate every built-in gate (in `BUILTIN_GATE_ORDER`) and any extension\n * gates (in registration order), then return the aggregated report.\n *\n * Built-in gates are sync; extension gates may be async. NEVER throws — a\n * throwing extension yields a synthetic `{ ok: false, code: '${ID}_THREW' }`.\n * A failing `structure` gate short-circuits the rest of the pipeline: nothing\n * else matters when the tour shape is invalid.\n */\nexport async function explainTour(\n  tour: Tour,\n  ctx: DiagnosticContext,\n  extensions: DiagnosticGate[] = []\n): Promise<EligibilityReport> {\n  const reasons: GateReason[] = []\n  const evaluatedAt = Date.now()\n\n  try {\n    const structure = gateStructure(tour)\n    reasons.push(structure)\n    if (!structure.ok) return finalize(tour.id, reasons, evaluatedAt)\n\n    reasons.push(gateAudience(tour.audience, ctx))\n    reasons.push(gatePersistence(tour, ctx))\n    reasons.push(gateRoute(tour, ctx))\n    reasons.push(gateTarget(tour, ctx))\n    reasons.push(gateWhen(tour))\n    reasons.push(gateAutostart(tour))\n\n    for (const gate of extensions) {\n      try {\n        const result = await gate.evaluate(ctx)\n        reasons.push(result)\n      } catch (e) {\n        const error = e as Error\n        reasons.push({\n          ok: false,\n          gate: gate.id,\n          code: `${gate.id.toUpperCase()}_THREW`,\n          message: error.message ?? 'Gate threw',\n          detail: { error: error.message },\n        })\n      }\n    }\n  } catch (e) {\n    // Defensive catch-all — diagnostic engine must never throw.\n    const error = e as Error\n    reasons.push({\n      ok: false,\n      gate: 'structure',\n      code: 'STRUCTURE_INVALID',\n      message: error.message ?? 'Diagnostic engine threw',\n      detail: { error: error.message },\n    })\n  }\n\n  return finalize(tour.id, reasons, evaluatedAt)\n}\n","import type {\n  Branch,\n  BranchContext,\n  BranchSkip,\n  BranchTarget,\n  BranchToTour,\n  BranchWait,\n} from '../types/branch'\nimport { logger } from './logger'\n\n/**\n * Maximum depth for recursive branch resolution\n * Prevents infinite loops from circular branch references\n */\nexport const MAX_BRANCH_DEPTH = 50\n\n/**\n * Type guard: Check if target is a BranchToTour object\n */\nexport function isBranchToTour(target: BranchTarget): target is BranchToTour {\n  return (\n    target !== null &&\n    typeof target === 'object' &&\n    'tour' in target &&\n    typeof target.tour === 'string'\n  )\n}\n\n/**\n * Type guard: Check if target is a BranchSkip object\n */\nexport function isBranchSkip(target: BranchTarget): target is BranchSkip {\n  return (\n    target !== null &&\n    typeof target === 'object' &&\n    'skip' in target &&\n    typeof target.skip === 'number'\n  )\n}\n\n/**\n * Type guard: Check if target is a BranchWait object\n */\nexport function isBranchWait(target: BranchTarget): target is BranchWait {\n  return (\n    target !== null &&\n    typeof target === 'object' &&\n    'wait' in target &&\n    typeof target.wait === 'number'\n  )\n}\n\n/**\n * Check if target is a special navigation keyword\n */\nexport function isSpecialTarget(\n  target: BranchTarget\n): target is 'next' | 'prev' | 'complete' | 'skip' | 'restart' {\n  return (\n    target === 'next' ||\n    target === 'prev' ||\n    target === 'complete' ||\n    target === 'skip' ||\n    target === 'restart'\n  )\n}\n\n/**\n * Check if a branch is a resolver function\n */\nexport function isBranchResolver(\n  branch: Branch\n): branch is (context: BranchContext) => BranchTarget | Promise<BranchTarget> {\n  return typeof branch === 'function'\n}\n\n/**\n * Resolve a branch to its target\n *\n * Handles both static targets and resolver functions.\n * Includes depth tracking to prevent infinite loops.\n *\n * @param branch - The branch to resolve (target or resolver)\n * @param context - The branch context for resolver functions\n * @param depth - Current resolution depth (for loop detection)\n * @returns The resolved branch target\n */\nexport async function resolveBranch(\n  branch: Branch,\n  context: BranchContext,\n  depth = 0\n): Promise<BranchTarget> {\n  // Check for infinite loop\n  if (depth > MAX_BRANCH_DEPTH) {\n    logger.warn(\n      `Branch resolution exceeded maximum depth (${MAX_BRANCH_DEPTH}). Possible circular reference detected. Falling back to \"next\".`\n    )\n    return 'next'\n  }\n\n  // Static target - return as-is\n  if (!isBranchResolver(branch)) {\n    return branch\n  }\n\n  // Resolver function - call it\n  try {\n    const result = await branch(context)\n    return result\n  } catch (error) {\n    logger.warn('Error resolving branch, falling back to \"next\":', error)\n    return 'next'\n  }\n}\n\n/**\n * Convert a branch target to a step index\n *\n * @param target - The branch target to convert\n * @param currentIndex - Current step index\n * @param stepIdMap - Map of step ID to index\n * @param totalSteps - Total number of steps in the tour\n * @returns Step index, or null for special targets that don't map to an index\n */\n// biome-ignore lint/complexity/noExcessiveCognitiveComplexity: branch resolution with multiple target types\nexport function resolveTargetToIndex(\n  target: BranchTarget,\n  currentIndex: number,\n  stepIdMap: Map<string, number>,\n  totalSteps: number\n): number | null {\n  // Null - stay on current step\n  if (target === null) {\n    return currentIndex\n  }\n\n  // Number - direct index\n  if (typeof target === 'number') {\n    // Clamp to valid range\n    if (target < 0) return 0\n    if (target >= totalSteps) return totalSteps - 1\n    return target\n  }\n\n  // String - could be step ID or special target\n  if (typeof target === 'string') {\n    // Check for special targets first\n    if (isSpecialTarget(target)) {\n      switch (target) {\n        case 'next':\n          return currentIndex + 1 < totalSteps ? currentIndex + 1 : null\n        case 'prev':\n          return currentIndex > 0 ? currentIndex - 1 : null\n        case 'complete':\n        case 'skip':\n        case 'restart':\n          return null // Special handling required\n      }\n    }\n\n    // Step ID lookup\n    const index = stepIdMap.get(target)\n    if (index !== undefined) {\n      return index\n    }\n\n    logger.warn(`Step ID \"${target}\" not found in tour`)\n    return null\n  }\n\n  // BranchToTour - requires special handling\n  if (isBranchToTour(target)) {\n    return null // Handled separately\n  }\n\n  // BranchSkip - relative jump\n  if (isBranchSkip(target)) {\n    const newIndex = currentIndex + target.skip\n    if (newIndex < 0) return 0\n    if (newIndex >= totalSteps) return totalSteps - 1\n    return newIndex\n  }\n\n  // BranchWait - requires special handling\n  if (isBranchWait(target)) {\n    return null // Handled separately\n  }\n\n  return null\n}\n\n/**\n * Check if a step has been visited too many times (potential loop)\n *\n * @param stepId - The step ID to check\n * @param visitCount - Map of step ID to visit count\n * @param maxVisits - Maximum allowed visits (default: 10)\n * @returns true if the step has been visited too many times\n */\nexport function isLoopDetected(\n  stepId: string,\n  visitCount: Map<string, number>,\n  maxVisits = 10\n): boolean {\n  const count = visitCount.get(stepId) ?? 0\n  return count >= maxVisits\n}\n","import type { RouterAdapter } from '../../types/router'\nimport type { TourCallbackContext, TourState } from '../../types/state'\nimport type { TourStep } from '../../types/step'\nimport type { Tour } from '../../types/tour'\nimport { logger } from '../../utils/logger'\n\n/**\n * Whether the step requires the router to navigate before mount.\n */\nexport function isNavigationNeeded(\n  step: TourStep | undefined,\n  router: RouterAdapter | undefined\n): { needed: boolean; isOnRoute: boolean } {\n  if (!step?.route || !router) {\n    return { needed: false, isOnRoute: true }\n  }\n  const matchMode = step.routeMatch ?? 'exact'\n  const isOnRoute = router.matchRoute(step.route, matchMode)\n  return { needed: !isOnRoute, isOnRoute }\n}\n\n/**\n * Build a `TourCallbackContext` from the reducer state, current tour, and\n * data slice. Shared by `navigateToStep` and `handleBranchTarget` for `when`\n * evaluation and lifecycle callbacks.\n */\nexport function buildCallbackContext(\n  state: TourState,\n  tour: Tour | null,\n  data: Record<string, unknown>\n): TourCallbackContext {\n  return {\n    tourId: state.tourId,\n    isActive: state.isActive,\n    currentStepIndex: state.currentStepIndex,\n    currentStep: state.currentStep,\n    totalSteps: state.totalSteps,\n    isLoading: state.isLoading,\n    isTransitioning: state.isTransitioning,\n    completedTours: state.completedTours,\n    skippedTours: state.skippedTours,\n    visitedSteps: state.visitedSteps,\n    stepVisitCount: state.stepVisitCount,\n    previousStepId: state.previousStepId,\n    tour,\n    data,\n  }\n}\n\n/**\n * Evaluate a step's `when` predicate. Defaults to true on undefined; any\n * thrown error is logged and treated as `false` (skip the step) so a buggy\n * predicate cannot brick the tour.\n */\nexport async function evaluateStepWhen(\n  step: TourStep,\n  context: TourCallbackContext\n): Promise<boolean> {\n  if (!step.when) return true\n  try {\n    return await step.when(context)\n  } catch (error) {\n    logger.warn(`Error evaluating when condition for step \"${step.id}\":`, error)\n    return false\n  }\n}\n\n/**\n * Walk steps in `direction` from `startIndex` (inclusive) until a step's\n * `when` predicate returns true or the array boundary is reached.\n *\n * @returns The matching index, or `-1` when no visible step exists.\n */\nexport async function findNextVisibleStepIndex(\n  startIndex: number,\n  direction: 1 | -1,\n  steps: TourStep[],\n  context: TourCallbackContext\n): Promise<number> {\n  let index = startIndex\n  while (index >= 0 && index < steps.length) {\n    const step = steps[index]\n    if (!step) break\n    const stepContext: TourCallbackContext = {\n      ...context,\n      currentStepIndex: index,\n      currentStep: step,\n    }\n    const shouldShow = await evaluateStepWhen(step, stepContext)\n    if (shouldShow) return index\n    index += direction\n  }\n  return -1\n}\n\n/**\n * Nearest visible step from `startIndex` — tries forward, then backward.\n */\nexport async function findNearestVisibleStepIndex(\n  startIndex: number,\n  steps: TourStep[],\n  context: TourCallbackContext\n): Promise<number> {\n  const forwardIndex = await findNextVisibleStepIndex(startIndex, 1, steps, context)\n  if (forwardIndex !== -1) return forwardIndex\n  return findNextVisibleStepIndex(startIndex - 1, -1, steps, context)\n}\n","import type { BranchContext, BranchTarget, TourCallbackContext } from '../../types'\nimport {\n  isBranchToTour,\n  isBranchWait,\n  isLoopDetected,\n  isSpecialTarget,\n  resolveTargetToIndex,\n} from '../../utils/branch'\nimport { logger } from '../../utils/logger'\nimport type { TourEngineContext } from './context'\nimport { buildCallbackContext, evaluateStepWhen, findNextVisibleStepIndex } from './helpers'\n\n/**\n * Resolve a `BranchTarget` to its effect on the active tour. Mirrors the\n * branch-handling matrix documented in the provider — terminal targets\n * (`'complete'` / `'skip'` / `'restart'`), cross-tour navigation, branch\n * delays, loop detection, `when`-filtered targets, and the success path that\n * tracks step view + fires `onStepChange`.\n *\n * Calls `ctx.navigateToStep` for actual route-aware navigation; never\n * imports `navigate-to-step` directly so swap-points and circular surface\n * stay clean.\n */\n// biome-ignore lint/complexity/noExcessiveCognitiveComplexity: branch navigation with multiple target types\nexport async function handleBranchTargetImpl(\n  ctx: TourEngineContext,\n  target: BranchTarget,\n  // `branchContext` and `actionId` are forwarded into the BranchWait recursion\n  // below; they're part of the public branching surface but are not consumed\n  // by this impl directly.\n  branchContext: BranchContext,\n  actionId?: string\n): Promise<void> {\n  const state = ctx.getState()\n  const currentTour = ctx.getCurrentTour()\n  const data = ctx.getData()\n\n  if (!currentTour || !state.currentStep) return\n\n  const currentStepId = state.currentStep.id\n\n  // null - stay on current step\n  if (target === null) {\n    ctx.dispatch({ type: 'SET_TRANSITIONING', isTransitioning: false })\n    return\n  }\n\n  // Special targets\n  if (isSpecialTarget(target)) {\n    switch (target) {\n      case 'complete':\n        ctx.completeTour()\n        return\n\n      case 'skip':\n        ctx.skipTour()\n        return\n\n      case 'restart': {\n        ctx.dispatch({ type: 'CLEAR_VISIT_TRACKING' })\n        ctx.dispatch({ type: 'GO_TO_STEP', stepIndex: 0 })\n        const firstStep = currentTour.steps[0]\n        if (firstStep) {\n          ctx.dispatch({\n            type: 'TRACK_STEP_VISIT',\n            stepId: firstStep.id,\n            previousStepId: currentStepId,\n          })\n          ctx.tourKitContext?.onStepView?.(currentTour.id, firstStep.id, 0)\n        }\n        return\n      }\n\n      case 'next':\n      case 'prev':\n        // Resolve to index and fall through to the resolveTargetToIndex path\n        break\n    }\n  }\n\n  // BranchToTour - cross-tour navigation\n  if (isBranchToTour(target)) {\n    const toTour = state.tours.get(target.tour)\n    if (!toTour) {\n      logger.warn(`Branch target tour \"${target.tour}\" not found`)\n      ctx.dispatch({ type: 'SET_TRANSITIONING', isTransitioning: false })\n      return\n    }\n\n    ctx.tourKitContext?.onTourBranch?.(currentTour.id, target.tour, currentStepId)\n    currentTour.onTourBranch?.(target.tour, currentStepId)\n\n    ctx.dispatch({ type: 'STOP_TOUR' })\n\n    let newStepIndex = 0\n    if (target.step !== undefined) {\n      if (typeof target.step === 'number') {\n        newStepIndex = target.step\n      } else {\n        const newTourStepMap = new Map<string, number>()\n        toTour.steps.forEach((s, i) => newTourStepMap.set(s.id, i))\n        newStepIndex = newTourStepMap.get(target.step) ?? 0\n      }\n    }\n\n    // Re-arm terminal-callback guards for the new tour\n    ctx.completedTourIdRef.current = null\n    ctx.skippedTourIdRef.current = null\n\n    ctx.dispatch({ type: 'START_TOUR', tourId: target.tour, stepIndex: newStepIndex })\n    ctx.tourKitContext?.onTourStart?.(target.tour)\n    toTour.onStart?.({ ...state, tour: toTour, data })\n    return\n  }\n\n  // BranchWait - delay before proceeding\n  if (isBranchWait(target)) {\n    await new Promise((resolve) => setTimeout(resolve, target.wait))\n    if (target.then) {\n      await handleBranchTargetImpl(ctx, target.then, branchContext, actionId)\n    }\n    return\n  }\n\n  // Resolve target to index\n  const targetIndex = resolveTargetToIndex(\n    target,\n    state.currentStepIndex,\n    ctx.getStepIdMap(),\n    currentTour.steps.length\n  )\n\n  if (targetIndex === null || targetIndex === state.currentStepIndex) {\n    ctx.dispatch({ type: 'SET_TRANSITIONING', isTransitioning: false })\n    return\n  }\n\n  // Check for loop detection\n  const targetStep = currentTour.steps[targetIndex]\n  if (targetStep && isLoopDetected(targetStep.id, state.stepVisitCount)) {\n    logger.warn(\n      `Loop detected: step \"${targetStep.id}\" visited too many times. Stopping navigation.`\n    )\n    ctx.dispatch({ type: 'SET_TRANSITIONING', isTransitioning: false })\n    return\n  }\n\n  // Apply `when` filter to the target step\n  const context = buildCallbackContext(state, currentTour, data)\n  const stepContext: TourCallbackContext = {\n    ...context,\n    currentStepIndex: targetIndex,\n    currentStep: targetStep ?? null,\n  }\n\n  if (targetStep) {\n    const shouldShow = await evaluateStepWhen(targetStep, stepContext)\n    if (!shouldShow) {\n      const direction = targetIndex > state.currentStepIndex ? 1 : -1\n      const visibleIndex = await findNextVisibleStepIndex(\n        targetIndex + direction,\n        direction as 1 | -1,\n        currentTour.steps,\n        context\n      )\n\n      if (visibleIndex === -1) {\n        ctx.completeTour()\n        return\n      }\n\n      const navigated = await ctx.navigateToStep(visibleIndex)\n      if (!navigated) {\n        ctx.dispatch({ type: 'SET_TRANSITIONING', isTransitioning: false })\n        return\n      }\n      const step = currentTour.steps[visibleIndex]\n      if (step) {\n        ctx.dispatch({\n          type: 'TRACK_STEP_VISIT',\n          stepId: step.id,\n          previousStepId: currentStepId,\n        })\n        ctx.tourKitContext?.onStepView?.(currentTour.id, step.id, visibleIndex)\n        currentTour.onStepChange?.(step, visibleIndex, {\n          ...state,\n          tour: currentTour,\n          data,\n        })\n      }\n      return\n    }\n  }\n\n  // Navigate to target step\n  const navigated = await ctx.navigateToStep(targetIndex)\n  if (!navigated) {\n    ctx.dispatch({ type: 'SET_TRANSITIONING', isTransitioning: false })\n    return\n  }\n  if (targetStep) {\n    ctx.dispatch({\n      type: 'TRACK_STEP_VISIT',\n      stepId: targetStep.id,\n      previousStepId: currentStepId,\n    })\n    ctx.tourKitContext?.onStepView?.(currentTour.id, targetStep.id, targetIndex)\n    currentTour.onStepChange?.(targetStep, targetIndex, {\n      ...state,\n      tour: currentTour,\n      data,\n    })\n  }\n}\n","/**\n * Cross-page navigation: post-navigate \"wait for the target to mount on the\n * new route, or surface a typed failure\". Thin wrapper over the existing\n * MutationObserver-based `waitForElement` — does NOT re-implement it.\n */\n\nimport type { VisibleTourStep } from '../types/step'\nimport { resolveTarget } from '../types/target'\nimport { waitForElement } from '../utils/dom'\n\n/**\n * Typed failure for cross-page tour navigation.\n *\n * Discriminated by `code`:\n * - `TARGET_NOT_FOUND`: target did not appear within the timeout on the new\n *   route. Most common on auto-strategy steps when the target component is\n *   gated by data fetching.\n * - `NAVIGATION_REJECTED`: router-level navigation refused (e.g. Pages Router\n *   `router.push()` resolved with `false`).\n * - `TIMEOUT`: reserved for non-target-related timeouts.\n */\nexport class TourRouteError extends Error {\n  readonly code: 'TARGET_NOT_FOUND' | 'NAVIGATION_REJECTED' | 'TIMEOUT'\n  readonly route: string\n  readonly selector?: string\n\n  constructor(args: {\n    code: TourRouteError['code']\n    route: string\n    selector?: string\n    message: string\n  }) {\n    super(args.message)\n    this.name = 'TourRouteError'\n    this.code = args.code\n    this.route = args.route\n    this.selector = args.selector\n  }\n}\n\nexport interface WaitForStepTargetOptions {\n  /** Route the navigation just landed on — included in the error for diagnostics. */\n  route: string\n  /** Reject after this many ms (default: 3000). */\n  timeoutMs?: number\n  /**\n   * Optional cancellation. When aborted, the wait rejects with\n   * `Error('aborted')` — NOT a `TourRouteError`. Distinct semantics so\n   * `onStepError` can stay scoped to \"target missing\" failures.\n   */\n  signal?: AbortSignal\n}\n\n/**\n * Resolve `step.target` after a route change.\n *\n * Behavior matrix:\n * - `target` is a string selector → defers to `waitForElement(selector, timeoutMs, signal)`.\n *   On timeout, the underlying `Error` is rethrown as\n *   `TourRouteError({ code: 'TARGET_NOT_FOUND' })`.\n *   On abort, the underlying `Error('aborted')` is rethrown unchanged so\n *   callers can distinguish user-initiated cancellation from missing targets.\n * - `target` is a `RefObject` already populated → resolves synchronously.\n * - `target` is a `RefObject` with `current === null` → throws\n *   `TourRouteError({ code: 'TARGET_NOT_FOUND' })` immediately. There's no\n *   selector to observe for.\n */\nexport async function waitForStepTarget(\n  step: VisibleTourStep,\n  opts: WaitForStepTargetOptions\n): Promise<HTMLElement> {\n  const timeout = opts.timeoutMs ?? 3000\n\n  // Ref / getter targets resolve synchronously through `resolveTarget`. There's\n  // no selector to observe for, so a null result is an immediate failure.\n  if (typeof step.target !== 'string') {\n    const el = resolveTarget(step.target)\n    if (el) return el\n    throw new TourRouteError({\n      code: 'TARGET_NOT_FOUND',\n      route: opts.route,\n      message: `Step \"${step.id}\" target ref/getter not populated on route \"${opts.route}\".`,\n    })\n  }\n\n  try {\n    return await waitForElement(step.target, timeout, opts.signal)\n  } catch (err) {\n    // User-initiated abort: pass through the plain Error('aborted') unchanged.\n    if (opts.signal?.aborted) throw err\n    throw new TourRouteError({\n      code: 'TARGET_NOT_FOUND',\n      route: opts.route,\n      selector: step.target,\n      message: `Target \"${step.target}\" not found on route \"${opts.route}\" within ${timeout}ms.`,\n    })\n  }\n}\n","import type { BranchContext, TourCallbackContext } from '../../types'\nimport type { TourStep } from '../../types/step'\nimport type { Tour } from '../../types/tour'\nimport { resolveBranch, resolveTargetToIndex } from '../../utils/branch'\nimport { TourValidationError } from '../validate-tour'\nimport { TourRouteError, waitForStepTarget } from '../wait-for-step-target'\nimport type { TourEngineContext } from './context'\nimport { buildCallbackContext, isNavigationNeeded } from './helpers'\n\n/**\n * Run a hidden step's lifecycle and return either the next cursor or\n * `'terminate'` if the step's `onNext` resolves to a terminal target.\n */\nasync function advancePastHiddenStep(\n  ctx: TourEngineContext,\n  step: TourStep,\n  cursor: number,\n  tour: Tour,\n  stepIdLookup: Map<string, number>\n): Promise<number | 'terminate'> {\n  const state = ctx.getState()\n  const data = ctx.getData()\n  const baseCtx = buildCallbackContext(state, tour, data)\n  const stepCtx: TourCallbackContext = {\n    ...baseCtx,\n    currentStepIndex: cursor,\n    currentStep: step,\n  }\n  await step.onEnter?.(stepCtx)\n  await step.onShow?.(stepCtx)\n\n  if (step.onNext === undefined || step.onNext === null) {\n    return cursor + 1\n  }\n\n  const branchCtx: BranchContext = { ...stepCtx, setData: ctx.setData }\n  const target = await resolveBranch(step.onNext, branchCtx)\n\n  if (target === 'complete' || target === 'skip') {\n    return 'terminate'\n  }\n\n  const idx = resolveTargetToIndex(target, cursor, stepIdLookup, tour.steps.length)\n  return idx ?? cursor + 1\n}\n\n/**\n * Route-aware step navigation.\n *\n * Walks past hidden steps (firing their `onEnter` / `onShow` lifecycle) until\n * a mountable step is reached, then dispatches `GO_TO_STEP`. Throws\n * `TourValidationError({ code: 'HIDDEN_STEP_LOOP' })` when the hidden chain\n * exceeds `ctx.maxHiddenChain`.\n *\n * Per-step `routeChangeStrategy`:\n * - `'auto'` (default): navigate, await target via `waitForStepTarget`,\n *   dispatch. On `TourRouteError`: fire `onStepError`, `STOP_TOUR`.\n * - `'prompt'`: fire `onNavigationRequired(route, stepId)`, do not dispatch.\n * - `'manual'`: do nothing — consumer drives navigation explicitly.\n *\n * `autoNavigate: false` (legacy) is equivalent to per-step `'prompt'`.\n *\n * @returns `true` on a successful synchronous-or-route-based dispatch, `false`\n *   when navigation is deferred to the consumer or aborted, throws on a\n *   hidden-step loop.\n */\n// biome-ignore lint/complexity/noExcessiveCognitiveComplexity: hidden-traversal + route navigation in one orchestrator\nexport async function navigateToStepImpl(\n  ctx: TourEngineContext,\n  stepIndex: number\n): Promise<boolean> {\n  const currentTour = ctx.getCurrentTour()\n  if (!currentTour) {\n    ctx.dispatch({ type: 'GO_TO_STEP', stepIndex })\n    return true\n  }\n\n  const localStepIdMap = new Map<string, number>()\n  currentTour.steps.forEach((s, i) => localStepIdMap.set(s.id, i))\n\n  let cursor = stepIndex\n  for (let chain = 0; chain <= ctx.maxHiddenChain; chain++) {\n    const step = currentTour.steps[cursor]\n    if (!step) {\n      ctx.dispatch({ type: 'GO_TO_STEP', stepIndex: cursor })\n      return false\n    }\n\n    if (step.kind !== 'hidden') {\n      const { needed } = isNavigationNeeded(step, ctx.router)\n      if (!needed || !step.route || !ctx.router) {\n        ctx.dispatch({ type: 'GO_TO_STEP', stepIndex: cursor })\n        return true\n      }\n\n      if (!ctx.autoNavigate) {\n        ctx.onNavigationRequired?.(step.route, step.id)\n        return false\n      }\n\n      const strategy = step.routeChangeStrategy ?? 'auto'\n\n      if (strategy === 'manual') {\n        return false\n      }\n\n      if (strategy === 'prompt') {\n        ctx.onNavigationRequired?.(step.route, step.id)\n        return false\n      }\n\n      // strategy === 'auto'\n      try {\n        const navResult = await ctx.router.navigate(step.route)\n        if (navResult === false) {\n          throw new TourRouteError({\n            code: 'NAVIGATION_REJECTED',\n            route: step.route,\n            message: `Router rejected navigation to \"${step.route}\".`,\n          })\n        }\n\n        if (step.routeDelay && step.routeDelay > 0) {\n          await new Promise((resolve) => setTimeout(resolve, step.routeDelay))\n        }\n\n        await waitForStepTarget(step, {\n          route: step.route,\n          timeoutMs: step.waitTimeout ?? 3000,\n          signal: ctx.abortControllerRef.current?.signal,\n        })\n      } catch (err) {\n        if (ctx.abortControllerRef.current?.signal.aborted) return false\n        if (err instanceof TourRouteError) {\n          ctx.onStepError?.(err)\n          ctx.dispatch({ type: 'STOP_TOUR' })\n          return false\n        }\n        throw err\n      }\n\n      ctx.dispatch({ type: 'GO_TO_STEP', stepIndex: cursor })\n      return true\n    }\n\n    const next = await advancePastHiddenStep(ctx, step, cursor, currentTour, localStepIdMap)\n    if (next === 'terminate') {\n      ctx.dispatch({ type: 'GO_TO_STEP', stepIndex: currentTour.steps.length })\n      return false\n    }\n    cursor = next\n  }\n\n  const stuckStep = currentTour.steps[cursor]\n  throw new TourValidationError({\n    code: 'HIDDEN_STEP_LOOP',\n    stepId: stuckStep?.id ?? '?',\n    message: `Hidden-step chain exceeded ${ctx.maxHiddenChain} iterations${stuckStep ? ` at step \"${stuckStep.id}\"` : ''}. Likely an infinite loop.`,\n  })\n}\n","/**\n * Module-level tour registry.\n *\n * `<TourProvider>` and standalone `<Tour id=\"...\">` register themselves here on\n * mount so any sibling subtree can read tour state / call imperative actions\n * via `useTourActions(id)`. This eliminates window-event workarounds (e.g., the\n * old `tour-replay` CustomEvent dispatch dance) and the LS-clear + unregister +\n * register choreography users wrote to force a tour to restart.\n *\n * Design notes (do not change without re-reading Phase 1):\n *   - **Module-level singleton, not React Context.** A Context would re-create\n *     the workaround Phase 1 is killing: `useTourActions` must work from a\n *     sibling subtree, which a Context dependency can't reach without lifting\n *     the provider.\n *   - **`WeakRef` values, string keys.** Keys are tour ids (interned strings\n *     that never need to be GC-tracked). Values hold the controller surface;\n *     wrapping them in `WeakRef` plus an explicit `unregister()` on unmount\n *     survives StrictMode double-mount without leaks.\n *   - **Mutable `state` field, immutable replacement.** Each tour's state slice\n *     is replaced wholesale on every reducer transition (`entry.state = next`),\n *     producing a fresh reference that `useSyncExternalStore` will compare via\n *     `Object.is` and rerender consumers on changes only.\n *   - **Dev double-id is logged, not thrown.** HMR remounts and accidental\n *     double-mounts must not tank DX — log via `logger.error`, keep the latest\n *     registration, and document the behaviour in `imperative-control.mdx`.\n */\n\nimport { logger } from '../utils/logger'\n\n/**\n * Live state mirror for a registered tour.\n *\n * Every field reflects whether THIS tour (matching the entry's id) is the\n * currently active tour. A provider managing multiple tours will register one\n * entry per tour and only the active tour's entry will report `isActive: true`.\n */\ninterface RegistryEntryState {\n  isActive: boolean\n  currentStepId: string | null\n  progress: number\n}\n\n/**\n * Internal shape held by the registry. NOT exported — consumers always go\n * through the `tourRegistry` facade or `useTourActions` hook.\n */\ninterface RegistryEntry {\n  id: string\n  /**\n   * Live state mirror. Replaced wholesale on every transition by the owning\n   * provider so `useSyncExternalStore` sees a new reference and rerenders.\n   */\n  state: RegistryEntryState\n  /**\n   * Imperative controllers wired from the owning provider's reducer dispatch\n   * path. Reference identity is stable for the lifetime of the entry; the\n   * provider routes through internal refs so the closures stay live without\n   * re-publishing the registry entry.\n   */\n  actions: {\n    start: () => void\n    stop: () => void\n    restart: () => void\n    next: () => void\n    prev: () => void\n    goToStep: (stepId: string) => void\n  }\n}\n\nconst entries = new Map<string, WeakRef<RegistryEntry>>()\nconst listeners = new Set<() => void>()\n\nfunction notify(): void {\n  for (const listener of listeners) {\n    listener()\n  }\n}\n\n/**\n * Single env predicate. Gates both:\n *   - `console.error` on duplicate-id registration (dev DX signal)\n *   - `__reset__` test-only helper (so production never carries it)\n *\n * Vitest leaves `NODE_ENV` as `development` by default — gating on\n * `!== 'production'` covers both `vitest run` and Storybook-style dev\n * harnesses without explicit env-var plumbing.\n */\nfunction isNonProductionEnv(): boolean {\n  return typeof process !== 'undefined' && process.env?.NODE_ENV !== 'production'\n}\n\n/**\n * Register a tour entry. Returns an unregister fn that the owning provider\n * MUST call in its effect cleanup to drop the entry deterministically.\n *\n * If a live entry already exists under the same id (HMR remount, accidental\n * duplicate `<Tour>`), the latest registration wins and a dev-only\n * `console.error` warns. The unregister fn returned by the FIRST registration\n * is intentionally a safe no-op once the entry has been replaced — it\n * compares the captured WeakRef against the current Map slot and only deletes\n * if they're still the same, so the dead first registration never tears down\n * the live second one.\n */\nfunction register(entry: RegistryEntry): () => void {\n  const ref = new WeakRef(entry)\n  const existing = entries.get(entry.id)?.deref()\n  if (existing && isNonProductionEnv()) {\n    logger.error(`Tour \"${entry.id}\" registered twice. Keeping the latest registration.`)\n  }\n  entries.set(entry.id, ref)\n  notify()\n\n  return () => {\n    const current = entries.get(entry.id)\n    if (current === ref) {\n      entries.delete(entry.id)\n      notify()\n    }\n  }\n}\n\n/**\n * Read an entry by id. Prunes dead WeakRefs (entries whose owning provider\n * unmounted without calling unregister — rare, but possible if React crashes\n * mid-commit) and returns `null` on miss.\n *\n * When a dead WeakRef is pruned, listeners are notified so any\n * `useSyncExternalStore` consumer still subscribed to the GC'd entry\n * re-renders with the frozen no-op instead of holding stale state forever.\n */\nfunction get(id: string): RegistryEntry | null {\n  const ref = entries.get(id)\n  if (!ref) return null\n  const entry = ref.deref()\n  if (!entry) {\n    entries.delete(id)\n    notify()\n    return null\n  }\n  return entry\n}\n\n/**\n * Update an entry's state slice. Replaces the `state` field wholesale and\n * notifies subscribers ONLY when at least one field actually changed —\n * Object.is comparison on the existing slice avoids redundant rerenders.\n */\nfunction update(id: string, next: RegistryEntryState): void {\n  const entry = get(id)\n  if (!entry) return\n  const prev = entry.state\n  if (\n    prev.isActive === next.isActive &&\n    prev.currentStepId === next.currentStepId &&\n    prev.progress === next.progress\n  ) {\n    return\n  }\n  entry.state = next\n  notify()\n}\n\nfunction subscribe(fn: () => void): () => void {\n  listeners.add(fn)\n  return () => {\n    listeners.delete(fn)\n  }\n}\n\n/**\n * Resolve every WeakRef and return a Map of live entries. Used by tests to\n * assert post-unmount cleanup (`snapshot().size === 0`). Reads, but does not\n * write, so calling this from a hot path won't trigger notifications.\n */\nfunction snapshot(): ReadonlyMap<string, RegistryEntry> {\n  const live = new Map<string, RegistryEntry>()\n  for (const [id, ref] of entries) {\n    const entry = ref.deref()\n    if (entry) live.set(id, entry)\n  }\n  return live\n}\n\n/**\n * Drop any WeakRef slots whose target was GC'd without an explicit unregister.\n * Safe to call eagerly from `get()` on miss; also exposed for tests that want\n * to verify the StrictMode leak invariant after `globalThis.gc?.()`.\n */\nfunction prune(): void {\n  let pruned = false\n  for (const [id, ref] of entries) {\n    if (!ref.deref()) {\n      entries.delete(id)\n      pruned = true\n    }\n  }\n  if (pruned) notify()\n}\n\ninterface TourRegistry {\n  register: typeof register\n  get: typeof get\n  update: typeof update\n  subscribe: typeof subscribe\n  snapshot: typeof snapshot\n  prune: typeof prune\n  /**\n   * Test-only escape hatch — clears the singleton between tests. Exposed only\n   * under `NODE_ENV === 'test'` so production never carries the helper.\n   */\n  __reset__?: () => void\n}\n\nexport const tourRegistry: TourRegistry = {\n  register,\n  get,\n  update,\n  subscribe,\n  snapshot,\n  prune,\n  __reset__: isNonProductionEnv()\n    ? () => {\n        entries.clear()\n        listeners.clear()\n      }\n    : undefined,\n}\n\nexport type { RegistryEntry, RegistryEntryState }\n","import * as React from 'react'\nimport { useAdvanceOn } from '../hooks/use-advance-on'\nimport { useBroadcast } from '../hooks/use-broadcast'\nimport { useFlowSession } from '../hooks/use-flow-session'\nimport { usePersistence } from '../hooks/use-persistence'\nimport { useRoutePersistence } from '../hooks/use-route-persistence'\nimport { explainTour } from '../lib/diagnostic'\nimport type { TourEngineAnalytics, TourEngineContext } from '../lib/tour-engine/context'\nimport { handleBranchTargetImpl } from '../lib/tour-engine/handle-branch-target'\nimport {\n  buildCallbackContext,\n  evaluateStepWhen,\n  findNearestVisibleStepIndex,\n  findNextVisibleStepIndex,\n} from '../lib/tour-engine/helpers'\nimport { navigateToStepImpl } from '../lib/tour-engine/navigate-to-step'\nimport { validateTour } from '../lib/validate-tour'\nimport { waitForStepTarget } from '../lib/wait-for-step-target'\nimport type { TourRouteError } from '../lib/wait-for-step-target'\nimport { tourRegistry } from '../registry/tour-registry'\nimport type {\n  BranchContext,\n  BranchTarget,\n  Tour,\n  TourCallbackContext,\n  TourContextValue,\n} from '../types'\nimport { defaultPersistenceConfig } from '../types/config'\nimport type { DiagnosticContext, DiagnosticGate, EligibilityReport } from '../types/diagnostic'\nimport type { MultiPagePersistenceConfig, RouterAdapter } from '../types/router'\nimport { isVisibleStep } from '../types/step'\nimport type { TestBridge } from '../types/test-bridge'\nimport type { TourAction, TourReducerState } from '../types/tour-reducer'\nimport { resolveBranch } from '../utils/branch'\nimport { logger } from '../utils/logger'\nimport { TourContext } from './tour-context'\nimport { TourKitContext } from './tourkit-context'\n\n/** Maximum hidden-step chain length before throwing HIDDEN_STEP_LOOP. */\nconst MAX_HIDDEN_CHAIN = 50\n\nfunction createStoppedState(state: TourReducerState): TourReducerState {\n  return {\n    ...state,\n    tourId: null,\n    isActive: false,\n    currentStepIndex: 0,\n    currentStep: null,\n    totalSteps: 0,\n    isLoading: false,\n    isTransitioning: false,\n    visitedSteps: [],\n    stepVisitCount: new Map(),\n    previousStepId: null,\n  }\n}\n\nfunction handleStartTour(\n  state: TourReducerState,\n  tourId: string,\n  stepIndex?: number\n): TourReducerState {\n  const tour = state.tours.get(tourId)\n  if (!tour) return state\n\n  const index = stepIndex ?? tour.startAt ?? 0\n  const step = tour.steps[index]\n  const stepId = step?.id\n\n  // Initialize visit tracking\n  const visitedSteps = stepId ? [stepId] : []\n  const stepVisitCount = new Map<string, number>()\n  if (stepId) {\n    stepVisitCount.set(stepId, 1)\n  }\n\n  return {\n    ...state,\n    tourId,\n    isActive: true,\n    currentStepIndex: index,\n    currentStep: step ?? null,\n    totalSteps: tour.steps.length,\n    isLoading: false,\n    isTransitioning: false,\n    visitedSteps,\n    stepVisitCount,\n    previousStepId: null,\n  }\n}\n\nfunction handleStepNavigation(state: TourReducerState, newIndex: number): TourReducerState {\n  const tour = state.tours.get(state.tourId ?? '')\n  if (!tour || newIndex < 0 || newIndex >= tour.steps.length) {\n    return state\n  }\n\n  return {\n    ...state,\n    currentStepIndex: newIndex,\n    currentStep: tour.steps[newIndex] ?? null,\n    isTransitioning: false,\n  }\n}\n\nfunction handleReset(state: TourReducerState, tourId?: string): TourReducerState {\n  if (tourId) {\n    return {\n      ...state,\n      completedTours: state.completedTours.filter((id) => id !== tourId),\n      skippedTours: state.skippedTours.filter((id) => id !== tourId),\n    }\n  }\n  return {\n    ...state,\n    completedTours: [],\n    skippedTours: [],\n  }\n}\n\n/** First registered `autoStart` tour the user hasn't already completed. */\nfunction findAutoStartTour(tours: Tour[], completedTours: string[]): Tour | undefined {\n  const auto = tours.find((t) => t.autoStart)\n  if (!auto || completedTours.includes(auto.id)) return undefined\n  return auto\n}\n\n// biome-ignore lint/complexity/noExcessiveCognitiveComplexity: reducer handles many action variants in one switch\nfunction tourReducer(state: TourReducerState, action: TourAction): TourReducerState {\n  switch (action.type) {\n    case 'START_TOUR':\n      return handleStartTour(state, action.tourId, action.stepIndex)\n    case 'NEXT_STEP':\n      return handleStepNavigation(state, state.currentStepIndex + 1)\n    case 'PREV_STEP':\n      return handleStepNavigation(state, state.currentStepIndex - 1)\n    case 'GO_TO_STEP':\n      return handleStepNavigation(state, action.stepIndex)\n    case 'SKIP_TOUR':\n    case 'COMPLETE_TOUR':\n    case 'STOP_TOUR':\n      return createStoppedState(state)\n    case 'SET_LOADING':\n      return { ...state, isLoading: action.isLoading }\n    case 'SET_TRANSITIONING':\n      return { ...state, isTransitioning: action.isTransitioning }\n    case 'ADD_COMPLETED':\n      return state.completedTours.includes(action.tourId)\n        ? state\n        : { ...state, completedTours: [...state.completedTours, action.tourId] }\n    case 'ADD_SKIPPED':\n      return state.skippedTours.includes(action.tourId)\n        ? state\n        : { ...state, skippedTours: [...state.skippedTours, action.tourId] }\n    case 'HYDRATE_TERMINAL_TOURS': {\n      // Post-mount load of persisted terminal tours (see the hydrate effect in\n      // TourProvider). Union-merge so an ADD_COMPLETED/ADD_SKIPPED dispatched\n      // before hydration lands is never lost.\n      const completedTours = [...new Set([...action.completedTours, ...state.completedTours])]\n      const skippedTours = [...new Set([...action.skippedTours, ...state.skippedTours])]\n      return { ...state, completedTours, skippedTours }\n    }\n    case 'RESET':\n      return handleReset(state, action.tourId)\n    case 'UPDATE_TOURS': {\n      // Fast-path: if the incoming array is shallow-equal to what we already\n      // have (same size, same per-id reference), skip the re-keyed Map and\n      // the downstream currentTour/stepIdMap invalidation. Consumers often\n      // pass inline arrays like `tours={[a, b]}` where the array identity\n      // changes every render but the tour objects themselves don't.\n      const sameIdentity =\n        state.tours.size === action.tours.length &&\n        action.tours.every((t) => state.tours.get(t.id) === t)\n      if (sameIdentity) return state\n\n      const newTours = new Map(action.tours.map((t) => [t.id, t]))\n\n      // If there's an active tour, refresh currentStep from the updated tour\n      // This ensures step properties like onAction are synchronized\n      if (state.isActive && state.tourId) {\n        const updatedTour = newTours.get(state.tourId)\n        if (updatedTour?.steps[state.currentStepIndex]) {\n          return {\n            ...state,\n            tours: newTours,\n            currentStep: updatedTour.steps[state.currentStepIndex],\n            totalSteps: updatedTour.steps.length,\n          }\n        }\n      }\n\n      return { ...state, tours: newTours }\n    }\n    case 'TRACK_STEP_VISIT': {\n      const newVisitedSteps = state.visitedSteps.includes(action.stepId)\n        ? state.visitedSteps\n        : [...state.visitedSteps, action.stepId]\n      const newStepVisitCount = new Map(state.stepVisitCount)\n      newStepVisitCount.set(action.stepId, (newStepVisitCount.get(action.stepId) ?? 0) + 1)\n      return {\n        ...state,\n        visitedSteps: newVisitedSteps,\n        stepVisitCount: newStepVisitCount,\n        previousStepId: action.previousStepId,\n      }\n    }\n    case 'CLEAR_VISIT_TRACKING':\n      return {\n        ...state,\n        visitedSteps: [],\n        stepVisitCount: new Map(),\n        previousStepId: null,\n      }\n    default:\n      return state\n  }\n}\n\nexport interface TourProviderProps {\n  children: React.ReactNode\n  tours?: Tour[]\n  /** Router adapter for multi-page tours */\n  router?: RouterAdapter\n  /** Persistence config for multi-page tours */\n  routePersistence?: MultiPagePersistenceConfig\n  /** Auto-navigate when step requires different route (default: true) */\n  autoNavigate?: boolean\n  /** Callback when navigation is needed but autoNavigate is false */\n  onNavigationRequired?: (route: string, stepId: string) => void\n  /**\n   * Called when the active tour is paused by an external signal.\n   * Currently the only `reason` is `'cross-tab'` (another tab posted\n   * `tour:active` on the cross-tab `BroadcastChannel`).\n   */\n  onTourPaused?: (tourId: string, reason: 'cross-tab') => void\n  /**\n   * Called when a cross-page step fails — typically when the step's target\n   * does not appear on the new route within `routeChangeStrategy: 'auto'`'s\n   * 3000ms wait. The provider stops the tour after this fires.\n   *\n   * Aborts triggered by `STOP_TOUR` or unmount do NOT call this — those are\n   * cooperative cancellation, not failures.\n   */\n  onStepError?: (err: TourRouteError) => void\n  /**\n   * Diagnostic mode — when `true`, the provider runs `explainTour` for every\n   * registered tour and exposes the result via `useTourDiagnostic(tourId)`.\n   * Defaults to `false`; the orchestrator tree-shakes out when unused.\n   *\n   * In `NODE_ENV !== 'production'` builds, leaving this off triggers a\n   * one-time `console.warn` per provider mount nudging dev consumers toward\n   * the better debug surface.\n   */\n  diagnose?: boolean\n  /**\n   * Extension gates (license, scheduling, custom) appended to the diagnostic\n   * pipeline AFTER built-ins. Only consulted when `diagnose` is `true`.\n   */\n  diagnosticGates?: DiagnosticGate[]\n  /**\n   * Optional user context plumbed to diagnostic gates (audience filter, etc).\n   * Only read when `diagnose` is `true`.\n   */\n  userContext?: Record<string, unknown>\n  /**\n   * Dev-only test bridge — when `true`, sets `window.__tourKit__` to a\n   * `TestBridge` exposing the imperative controls (mirrors the existing\n   * ref) so Playwright/E2E drivers can advance a tour from outside React.\n   *\n   * Defaults to `false`. Production builds MUST never expose this — wrap\n   * in a `process.env.NODE_ENV !== 'production'` guard at the call site.\n   * Tree-shakes when the prop is a literal `false`.\n   */\n  enableTestBridge?: boolean\n}\n\ninterface CrossTabActiveMessage {\n  type: 'tour:active'\n  tourId: string\n  tabId: string\n  ts: number\n}\n\n// Module-level guard so the dev `diagnose` tip prints once per page/session,\n// regardless of how many TourProvider instances mount.\nlet diagnoseHintFired = false\n\n/** Test-only: reset the once-per-session `diagnose` hint guard. */\nexport function __resetDiagnoseHintForTests(): void {\n  diagnoseHintFired = false\n}\n\nexport function TourProvider({\n  children,\n  tours = [],\n  router,\n  routePersistence = { enabled: false },\n  autoNavigate = true,\n  onNavigationRequired,\n  onTourPaused,\n  onStepError,\n  diagnose = false,\n  diagnosticGates,\n  userContext,\n  enableTestBridge = false,\n}: TourProviderProps) {\n  // Validate synchronously at render time so misconfigured hidden steps throw\n  // at the caller's render() instead of leaking into runtime. Cheap: just a\n  // shallow loop over the steps. Must run before any hook so a thrown error\n  // doesn't leave React with a partial hook order.\n  for (const tour of tours) validateTour(tour)\n\n  const [diagnostics, setDiagnostics] = React.useState<Record<string, EligibilityReport>>({})\n\n  // Dev-mode hint: fire once per page/session when `diagnose` is unset. Uses a\n  // module-level guard (see `diagnoseHintFired`) so multiple TourProvider\n  // instances — e.g. several tours under MultiTourKitProvider — don't each\n  // print the tip. Gated on NODE_ENV !== 'production' so prod builds stay silent.\n  // biome-ignore lint/correctness/useExhaustiveDependencies: mount-once warning, not a reactive concern\n  React.useEffect(() => {\n    if (diagnose) return\n    if (diagnoseHintFired) return\n    if (typeof process === 'undefined' || process.env?.NODE_ENV === 'production') return\n    diagnoseHintFired = true\n    logger.warn(\n      'Tip: pass <TourProvider diagnose> in dev to see why a tour did not fire. https://usertourkit.com/docs/core/diagnostic'\n    )\n  }, [])\n\n  const tourKitContext = React.useContext(TourKitContext)\n  const persistenceConfig = tourKitContext?.config.persistence\n  const {\n    getCompletedTours,\n    getSkippedTours,\n    markCompleted,\n    markSkipped,\n    reset: resetPersistence,\n  } = usePersistence(persistenceConfig)\n  const persistTerminalTours =\n    (persistenceConfig?.enabled ?? defaultPersistenceConfig.enabled) &&\n    (persistenceConfig?.trackCompleted ?? defaultPersistenceConfig.trackCompleted)\n  const [data, setDataState] = React.useState<Record<string, unknown>>({})\n  const { save, load, clear, externalVersion } = useRoutePersistence(routePersistence)\n\n  const initialState: TourReducerState = {\n    tourId: null,\n    isActive: false,\n    currentStepIndex: 0,\n    currentStep: null,\n    totalSteps: 0,\n    isLoading: false,\n    isTransitioning: false,\n    // Hydration safety: do NOT seed these from storage here. A render-time\n    // getCompletedTours() read makes the first client render differ from SSR\n    // (server has no storage), which shifts useId tree positions and breaks\n    // hydration for downstream useId consumers. Loaded post-mount via\n    // HYDRATE_TERMINAL_TOURS below.\n    completedTours: [],\n    skippedTours: [],\n    visitedSteps: [],\n    stepVisitCount: new Map(),\n    previousStepId: null,\n    tours: new Map(tours.map((t) => [t.id, t])),\n  }\n\n  const [state, dispatch] = React.useReducer(tourReducer, initialState)\n\n  // Load persisted terminal tours after mount so the first client render\n  // matches the server-rendered HTML exactly (standard SSR reconcile pattern).\n  React.useEffect(() => {\n    if (!persistTerminalTours) return\n    const completedTours = getCompletedTours()\n    const skippedTours = getSkippedTours()\n    if (completedTours.length === 0 && skippedTours.length === 0) return\n    dispatch({ type: 'HYDRATE_TERMINAL_TOURS', completedTours, skippedTours })\n  }, [persistTerminalTours, getCompletedTours, getSkippedTours])\n\n  // ─── Diagnostic engine wiring (Phase 3) ──────────────────────────────────\n  // Runs after the reducer is declared so the persistence gate can read live\n  // `state.completedTours` / `state.skippedTours`. Only fires when\n  // `diagnose === true`, so opted-out consumers pay zero runtime cost (and\n  // the orchestrator import tree-shakes out of their bundle).\n  //\n  // Stability keys: `userContext`, `diagnosticGates`, and `router` are\n  // reference types, so we derive primitive keys that survive identity\n  // churn from inline-literal props.\n  //\n  // - `userContextKey`: JSON-stringified content (try/catch around it — a\n  //   circular reference in a user-supplied object must NEVER crash the host\n  //   render path; we degrade to a stable sentinel instead).\n  // - `diagnosticGatesKey`: gate ids joined with NUL so kebab-case ids\n  //   cannot collide regardless of payload.\n  // - `tourIdsKey`: same NUL-joined shape as the gates key.\n  // - `currentRouteKey`: the router's current path as a string, so route\n  //   changes inside a stable router re-evaluate the route gate, and inline\n  //   router instances don't reference-thrash the effect.\n  const userContextKey = React.useMemo(() => {\n    if (!userContext) return ''\n    try {\n      return JSON.stringify(userContext)\n    } catch {\n      // Circular or otherwise unserializable. Falling back to a constant\n      // string means the effect won't re-run on content changes for this\n      // shape — acceptable degradation; the alternative (throwing during\n      // render) takes down the host tree even when `diagnose` is off.\n      return '[unserializable]'\n    }\n  }, [userContext])\n  const diagnosticGatesKey = (diagnosticGates ?? []).map((g) => g.id).join('\\x00')\n  const tourIdsKey = tours.map((t) => t.id).join('\\x00')\n  const currentRouteKey = router?.getCurrentRoute() ?? ''\n  // biome-ignore lint/correctness/useExhaustiveDependencies: stability keys (userContextKey, diagnosticGatesKey, tourIdsKey, currentRouteKey) replace the reference deps; state.completedTours/skippedTours are tracked as live refs\n  React.useEffect(() => {\n    if (!diagnose) return\n    let cancelled = false\n    const gates = diagnosticGates ?? []\n    const currentRoute = router?.getCurrentRoute()\n    void Promise.all(\n      tours.map((t) => {\n        const firstVisibleStep = t.steps.find((s) => s.kind !== 'hidden')\n        const stepRoute = firstVisibleStep?.route\n        const ctx: DiagnosticContext = {\n          userContext,\n          completedTours: state.completedTours,\n          skippedTours: state.skippedTours,\n          route:\n            stepRoute && currentRoute !== undefined\n              ? {\n                  current: currentRoute,\n                  matcher: stepRoute,\n                  mode: firstVisibleStep?.routeMatch ?? 'exact',\n                }\n              : undefined,\n          targetResolver: (sel) =>\n            typeof document !== 'undefined' ? document.querySelector<HTMLElement>(sel) : null,\n        }\n        return explainTour(t, ctx, gates).then((r) => [t.id, r] as const)\n      })\n    ).then((pairs) => {\n      if (cancelled) return\n      setDiagnostics(Object.fromEntries(pairs))\n    })\n    return () => {\n      cancelled = true\n    }\n  }, [\n    diagnose,\n    tourIdsKey,\n    userContextKey,\n    diagnosticGatesKey,\n    state.completedTours,\n    state.skippedTours,\n    currentRouteKey,\n  ])\n\n  // flowSession-restore: tour-scoped resume after reload. The hook uses a\n  // single fixed key (`flow:active`) so we discover the persisted tourId on\n  // mount without needing to know it up front; subsequent saves write the\n  // current state.tourId.\n  const flow = useFlowSession(\n    state.tourId ?? '',\n    routePersistence.flowSession\n      ? { ...routePersistence.flowSession, keyPrefix: routePersistence.key }\n      : undefined\n  )\n\n  const tabId = React.useMemo(() => {\n    if (typeof crypto !== 'undefined' && crypto.randomUUID) {\n      return crypto.randomUUID()\n    }\n    // Random-enough fallback for runtimes without crypto.randomUUID.\n    // A literal sentinel like 'ssr' would collide between tabs and silently\n    // disable the cross-tab self-message filter.\n    return `tab-${Date.now()}-${Math.random().toString(36).slice(2, 10)}`\n  }, [])\n  const broadcast = useBroadcast<CrossTabActiveMessage>(\n    routePersistence.crossTab?.channel ?? 'tourkit:active-flow',\n    { enabled: !!routePersistence.crossTab?.enabled }\n  )\n\n  // Stable callback ref for cross-tab pause notification\n  const onTourPausedRef = React.useRef(onTourPaused)\n  React.useEffect(() => {\n    onTourPausedRef.current = onTourPaused\n  })\n\n  // Latest-state ref consumed by the cross-tab subscribe handler so it can\n  // read isActive/tourId at fire time without re-subscribing on every state\n  // change (which would risk dropping in-flight messages).\n  const currentActiveRef = React.useRef<{ isActive: boolean; tourId: string | null }>({\n    isActive: false,\n    tourId: null,\n  })\n\n  // Idempotency guards: track the last tour for which the terminal callback\n  // (onComplete / onSkip) has already fired. Prevents double-firing inside the\n  // same React commit phase, where reducer state is still closure-stale.\n  // Reset inside start() / handleStartTour-equivalent paths (see below).\n  const completedTourIdRef = React.useRef<string | null>(null)\n  const skippedTourIdRef = React.useRef<string | null>(null)\n\n  // Sync tours prop with reducer state when tours are registered/unregistered\n  React.useEffect(() => {\n    dispatch({ type: 'UPDATE_TOURS', tours })\n  }, [tours])\n\n  // Get current tour\n  const currentTour = state.tourId ? (state.tours.get(state.tourId) ?? null) : null\n\n  // flowSession-restore: takes precedence over useRoutePersistence — it's\n  // tour-scoped (single active tour) vs the route-state's multi-tour scope.\n  // Runs once per mount, but waits for the tour list to be populated. The\n  // declarative `<Tour>` registration path (via `MultiTourKitProvider`)\n  // mounts children AFTER the parent's first effect tick, so a strict\n  // mount-only effect with `[]` deps would bail with `tours = []`. The ref\n  // guard makes it idempotent across the inevitable tours-change re-runs.\n  //\n  // Phase 1.3 — cross-page resume: if the restored blob has a `currentRoute`\n  // that differs from the current router pathname, navigate first and await\n  // the target before dispatching START_TOUR. On any failure, clear the\n  // session — a stale/wrong route will never recover on its own.\n  const flowRestoreAttemptedRef = React.useRef(false)\n  // biome-ignore lint/correctness/useExhaustiveDependencies: idempotent via flowRestoreAttemptedRef; re-runs when `tours` populates or the deferred session load completes (flow.ready)\n  React.useEffect(() => {\n    if (flowRestoreAttemptedRef.current) return\n    // The session blob loads post-mount (hydration safety) — wait for it.\n    if (!flow.ready) return\n    const restored = flow.session\n    if (!restored || flow.isStale) return\n    if (tours.length === 0) return // wait for declarative <Tour> children\n    const restoredTour = tours.find((t) => t.id === restored.tourId)\n    flowRestoreAttemptedRef.current = true\n    if (!restoredTour) return\n\n    // `flow-restore` timer — visible in DevTools / Playwright's console\n    // listener, lets consumers verify the hard-refresh resume budget. The\n    // phase-1.3 target is < 200ms wall time from mount to `START_TOUR`.\n    // Instrumented on BOTH paths (sync same-route restore and async\n    // navigate-then-wait) so the metric fires for the common case too.\n    const startTimer = () => {\n      if (typeof console !== 'undefined' && typeof console.time === 'function') {\n        console.time('flow-restore')\n      }\n    }\n    let timerEnded = false\n    const endTimer = () => {\n      if (timerEnded) return\n      timerEnded = true\n      if (typeof console !== 'undefined' && typeof console.timeEnd === 'function') {\n        console.timeEnd('flow-restore')\n      }\n    }\n\n    const dispatchStart = () => {\n      dispatch({\n        type: 'START_TOUR',\n        tourId: restored.tourId,\n        stepIndex: restored.stepIndex,\n      })\n    }\n\n    const needsRouteRestore =\n      restored.currentRoute && router && restored.currentRoute !== router.getCurrentRoute()\n\n    if (!needsRouteRestore) {\n      startTimer()\n      dispatchStart()\n      endTimer()\n      return\n    }\n\n    const targetStep = restoredTour.steps[restored.stepIndex]\n    // Narrowing: `needsRouteRestore` proved `currentRoute` is a string.\n    const route = restored.currentRoute as string\n    // Cancellation: the restore IIFE awaits async work (navigate +\n    // MutationObserver). If the provider unmounts mid-await, dispatch /\n    // flow.clear would mutate a dead instance and write to storage on\n    // behalf of a tour the user has already left.\n    let cancelled = false\n    startTimer()\n    // biome-ignore lint/complexity/noExcessiveCognitiveComplexity: restore orchestrator (navigate + wait + cancellation guards)\n    void (async () => {\n      try {\n        await router.navigate(route)\n        if (cancelled) {\n          endTimer()\n          return\n        }\n        if (targetStep && isVisibleStep(targetStep)) {\n          await waitForStepTarget(targetStep, {\n            route,\n            timeoutMs: targetStep.waitTimeout ?? 3000,\n          })\n          if (cancelled) {\n            endTimer()\n            return\n          }\n        }\n        dispatchStart()\n        endTimer()\n      } catch {\n        endTimer()\n        if (cancelled) return\n        // Stale session (route 404, target missing). Clear so the next mount\n        // doesn't loop on the same broken state.\n        flow.clear()\n      }\n    })()\n\n    return () => {\n      cancelled = true\n    }\n  }, [tours, flow.ready])\n\n  // Restore persisted state once flow readiness is known — and re-run when\n  // another tab writes (externalVersion bumps whenever `syncTabs` is on and\n  // the storage key changes). Gated on flow.ready so the flowSession-restore\n  // precedence check below sees the loaded session, not the pre-load `null`.\n  // biome-ignore lint/correctness/useExhaustiveDependencies: Only run on flow readiness / external sync\n  React.useEffect(() => {\n    if (!flow.ready) return\n    // flowSession restore (above) wins — skip route restore if it already\n    // dispatched START_TOUR.\n    if (flow.session && !flow.isStale) return\n    const persisted = load()\n    if (persisted?.tourId && tours.some((t) => t.id === persisted.tourId)) {\n      dispatch({\n        type: 'START_TOUR',\n        tourId: persisted.tourId,\n        stepIndex: persisted.stepIndex,\n      })\n    }\n  }, [externalVersion, flow.ready])\n\n  // Auto-start tours declaring autoStart on mount.\n  // Persistence restore takes precedence — read persisted state synchronously\n  // so we don't double-dispatch in the same mount batch. Waits for flow.ready\n  // (post-mount session load) before deciding; the ref keeps it mount-once so\n  // the ready flip can't double-fire it.\n  const autoStartAttemptedRef = React.useRef(false)\n  // biome-ignore lint/correctness/useExhaustiveDependencies: mount-once autoStart trigger (ref-guarded), deferred until flow.ready\n  React.useEffect(() => {\n    if (autoStartAttemptedRef.current || !flow.ready) return\n    if (flow.session && !flow.isStale) return\n    autoStartAttemptedRef.current = true\n    const persisted = load()\n    if (persisted?.tourId && tours.some((t) => t.id === persisted.tourId)) return\n    const completedTours = persistTerminalTours ? getCompletedTours() : state.completedTours\n    const auto = findAutoStartTour(tours, completedTours)\n    if (!auto) return\n    dispatch({\n      type: 'START_TOUR',\n      tourId: auto.id,\n      stepIndex: auto.startAt ?? 0,\n    })\n  }, [flow.ready])\n\n  // Save state on changes\n  // biome-ignore lint/correctness/useExhaustiveDependencies: Intentionally only save on specific state changes\n  React.useEffect(() => {\n    if (state.isActive && routePersistence.enabled) {\n      save(state)\n    }\n  }, [state.tourId, state.currentStepIndex, state.isActive, save, routePersistence.enabled])\n\n  // Throttled flowSession save on step change while active. Deps are\n  // exhaustive — the throttle inside `flow.save` handles coalescing.\n  // `currentRoute` is included so a hard-refresh during a multi-page tour\n  // resumes on the right URL (Phase 1.3 — FlowSessionV2).\n  React.useEffect(() => {\n    if (state.isActive && state.tourId && routePersistence.flowSession) {\n      flow.save(state.currentStepIndex, router?.getCurrentRoute())\n    }\n  }, [\n    state.currentStepIndex,\n    state.isActive,\n    state.tourId,\n    flow.save,\n    routePersistence.flowSession,\n    router,\n  ])\n\n  // AbortController scoped to the active tour. Lets `waitForStepTarget`\n  // cancel cleanly on STOP_TOUR and on unmount instead of resolving a stale\n  // navigation onto a torn-down tree. Reset on every tour-id change.\n  const abortControllerRef = React.useRef<AbortController | null>(null)\n  // biome-ignore lint/correctness/useExhaustiveDependencies: tour-scoped — only swap on tour identity / activeness\n  React.useEffect(() => {\n    abortControllerRef.current?.abort()\n    abortControllerRef.current = state.isActive ? new AbortController() : null\n  }, [state.tourId, state.isActive])\n  // Final teardown on unmount — independent of the activeness swap above so\n  // the abort always fires once even when the component unmounts mid-tour.\n  React.useEffect(() => () => abortControllerRef.current?.abort(), [])\n\n  // Clear flowSession blob ONLY on a true → false transition (tour ended).\n  // The initial mount has `state.isActive === false`; without this guard\n  // we would wipe a freshly restored blob right after the restore effect\n  // dispatched START_TOUR (saved by the leading-edge throttle re-write,\n  // but fragile and an unnecessary storage churn).\n  const wasActiveRef = React.useRef(false)\n  // biome-ignore lint/correctness/useExhaustiveDependencies: only react to isActive flip\n  React.useEffect(() => {\n    if (wasActiveRef.current && !state.isActive && routePersistence.flowSession) {\n      flow.clear()\n    }\n    wasActiveRef.current = state.isActive\n  }, [state.isActive])\n\n  // Keep the latest-state ref in sync (read by the cross-tab subscriber).\n  React.useEffect(() => {\n    currentActiveRef.current = { isActive: state.isActive, tourId: state.tourId }\n  })\n\n  // Last-announce timestamp — also used as tie-breaker when two tabs\n  // simultaneously announce (e.g., both restoring from the same persisted\n  // session at cold start). The later announce wins; the earlier one yields.\n  const announceTsRef = React.useRef<number | null>(null)\n\n  // Cross-tab announce: whenever this tab activates a tour, post to the channel.\n  React.useEffect(() => {\n    if (state.isActive && state.tourId) {\n      announceTsRef.current = Date.now()\n      broadcast.post({\n        type: 'tour:active',\n        tourId: state.tourId,\n        tabId,\n        ts: announceTsRef.current,\n      })\n    }\n  }, [state.isActive, state.tourId, tabId, broadcast])\n\n  // Cross-tab subscribe: pause our active tour when another tab announces.\n  React.useEffect(() => {\n    return broadcast.subscribe((msg) => {\n      if (msg.type !== 'tour:active') return\n      if (msg.tabId === tabId) return\n      const pausedTourId = currentActiveRef.current.tourId\n      if (!currentActiveRef.current.isActive || !pausedTourId) return\n      // Tie-break: if we announced AFTER the incoming message, we are the\n      // newer owner and should keep running. Otherwise yield. Without this,\n      // two tabs cold-restoring the same flow.session at the same instant\n      // pause each other and the user sees no tour anywhere.\n      const myTs = announceTsRef.current\n      if (myTs !== null && myTs > msg.ts) return\n      dispatch({ type: 'STOP_TOUR' })\n      onTourPausedRef.current?.(pausedTourId, 'cross-tab')\n    })\n  }, [broadcast, tabId])\n\n  // setData is hoisted above navigateToStep so the hidden-step branch\n  // resolver can access it without depending on a later closure.\n  const setData = React.useCallback((key: string, value: unknown) => {\n    setDataState((prev) => ({ ...prev, [key]: value }))\n  }, [])\n\n  // ─── Engine context wiring ───────────────────────────────────────────────\n  // `navigateToStep` and `handleBranchTarget` live in `../lib/tour-engine/`.\n  //\n  // Engine impls are awaited across microtask boundaries. To avoid the stale-\n  // closure trap, the engine context's accessors route through a set of\n  // \"live\" refs that mirror the latest committed state. Even if an impl\n  // captures `ctx` from render N, calling `ctx.getState()` from render N+1\n  // reads through `stateRef.current` which has already been refreshed.\n  //\n  // `engineContextRef` itself is rebuilt each render so non-getter fields\n  // (router, callbacks) stay current; the getters all read through the same\n  // long-lived refs.\n  const stateRef = React.useRef<TourReducerState>(state)\n  const currentTourLiveRef = React.useRef<Tour | null>(null)\n  const dataRef = React.useRef<Record<string, unknown>>(data)\n  const stepIdMapRef = React.useRef<Map<string, number>>(new Map())\n  const engineContextRef = React.useRef<TourEngineContext | null>(null)\n\n  const navigateToStep = React.useCallback((stepIndex: number): Promise<boolean> => {\n    const ctx = engineContextRef.current\n    if (!ctx) return Promise.resolve(false)\n    return navigateToStepImpl(ctx, stepIndex)\n  }, [])\n\n  // Step ID to index map for branch resolution\n  const stepIdMap = React.useMemo(() => {\n    const map = new Map<string, number>()\n    currentTour?.steps.forEach((step, index) => {\n      map.set(step.id, index)\n    })\n    return map\n  }, [currentTour])\n\n  // Build branch context for branch resolvers\n  const buildBranchContext = React.useCallback(\n    (action?: string, actionPayload?: unknown): BranchContext => {\n      const callbackContext = buildCallbackContext(state, currentTour, data)\n      return {\n        ...callbackContext,\n        action,\n        actionPayload,\n        setData,\n      }\n    },\n    [state, currentTour, data, setData]\n  )\n\n  // Helper to complete the current tour. Idempotent across both stale-closure\n  // synchronous double-calls (via ref) and post-COMPLETE_TOUR re-firing (via\n  // isActive). Single source of truth for ALL completion paths — public\n  // complete(), next() at last step, branch 'complete', and the no-visible-step\n  // auto-finish path.\n  const completeTour = React.useCallback(() => {\n    if (!state.isActive || !currentTour) return\n    if (completedTourIdRef.current === currentTour.id) return\n    completedTourIdRef.current = currentTour.id\n    if (persistTerminalTours) markCompleted(currentTour.id)\n    dispatch({ type: 'ADD_COMPLETED', tourId: currentTour.id })\n    dispatch({ type: 'COMPLETE_TOUR' })\n    clear()\n    tourKitContext?.onTourComplete?.(currentTour.id)\n    currentTour.onComplete?.({ ...state, tour: currentTour, data })\n  }, [currentTour, state, data, tourKitContext, clear, persistTerminalTours, markCompleted])\n\n  // Helper to skip the current tour. Mirrors completeTour for skip semantics.\n  const skipTour = React.useCallback(() => {\n    if (!state.isActive || !currentTour) return\n    if (skippedTourIdRef.current === currentTour.id) return\n    skippedTourIdRef.current = currentTour.id\n    if (persistTerminalTours) markSkipped(currentTour.id)\n    dispatch({ type: 'ADD_SKIPPED', tourId: currentTour.id })\n    dispatch({ type: 'SKIP_TOUR' })\n    clear()\n    tourKitContext?.onTourSkip?.(currentTour.id, state.currentStepIndex)\n    currentTour.onSkip?.({ ...state, tour: currentTour, data })\n  }, [currentTour, state, data, tourKitContext, clear, persistTerminalTours, markSkipped])\n\n  // Branch-target orchestration extracted to ../lib/tour-engine/handle-branch-target.\n  // Wrapper delegates through the engine context ref so async branches read\n  // fresh state across awaits.\n  const handleBranchTarget = React.useCallback(\n    (target: BranchTarget, branchContext: BranchContext, actionId?: string): Promise<void> => {\n      const ctx = engineContextRef.current\n      if (!ctx) return Promise.resolve()\n      return handleBranchTargetImpl(ctx, target, branchContext, actionId)\n    },\n    []\n  )\n\n  // Refresh the live refs synchronously each render so engine getters always\n  // resolve to the latest committed state, even when called through a `ctx`\n  // captured during an earlier render (e.g. a BranchWait recursion that\n  // resumes after a state-changing dispatch).\n  stateRef.current = state\n  currentTourLiveRef.current = currentTour\n  dataRef.current = data\n  stepIdMapRef.current = stepIdMap\n\n  engineContextRef.current = {\n    getState: () => stateRef.current,\n    getCurrentTour: () => currentTourLiveRef.current,\n    getData: () => dataRef.current,\n    getStepIdMap: () => stepIdMapRef.current,\n    dispatch,\n    abortControllerRef,\n    completedTourIdRef,\n    skippedTourIdRef,\n    router,\n    autoNavigate,\n    maxHiddenChain: MAX_HIDDEN_CHAIN,\n    onNavigationRequired,\n    onStepError,\n    completeTour,\n    skipTour,\n    setData,\n    navigateToStep,\n    tourKitContext: tourKitContext satisfies TourEngineAnalytics | null,\n  }\n\n  // Actions\n  const start = React.useCallback(\n    async (tourId?: string, stepIndex?: number) => {\n      const id = tourId ?? tours[0]?.id\n      if (!id) return\n\n      const tour = state.tours.get(id)\n      if (!tour) return\n\n      const initialIndex = stepIndex ?? tour.startAt ?? 0\n\n      // Build context for when evaluation\n      const context = buildCallbackContext(\n        {\n          ...state,\n          tourId: id,\n          isActive: true,\n          totalSteps: tour.steps.length,\n          currentStepIndex: initialIndex,\n          currentStep: tour.steps[initialIndex] ?? null,\n        },\n        tour,\n        data\n      )\n\n      // Find first visible step from the initial index\n      const visibleIndex = await findNextVisibleStepIndex(initialIndex, 1, tour.steps, context)\n\n      if (visibleIndex === -1) {\n        logger.warn(`Tour \"${id}\" has no visible steps`)\n        return\n      }\n\n      // Re-arm terminal-callback guards for the (re)started tour\n      completedTourIdRef.current = null\n      skippedTourIdRef.current = null\n\n      dispatch({ type: 'START_TOUR', tourId: id, stepIndex: visibleIndex })\n      tourKitContext?.onTourStart?.(id)\n      tour.onStart?.({ ...state, tour, data })\n    },\n    [tours, state, data, tourKitContext]\n  )\n\n  const next = React.useCallback(async () => {\n    if (!state.isActive || !currentTour) return\n\n    const currentStep = state.currentStep\n\n    // Check for onNext branch override\n    if (currentStep?.onNext !== undefined) {\n      dispatch({ type: 'SET_TRANSITIONING', isTransitioning: true })\n      const branchContext = buildBranchContext()\n      const target = await resolveBranch(currentStep.onNext, branchContext)\n      await handleBranchTarget(target, branchContext)\n      return\n    }\n\n    const isLastStep = state.currentStepIndex >= currentTour.steps.length - 1\n    if (isLastStep) {\n      completeTour()\n      return\n    }\n\n    dispatch({ type: 'SET_TRANSITIONING', isTransitioning: true })\n\n    // Build context and find next visible step (skipping steps where when returns false)\n    const context = buildCallbackContext(state, currentTour, data)\n    const nextStepIndex = await findNextVisibleStepIndex(\n      state.currentStepIndex + 1,\n      1, // forward direction\n      currentTour.steps,\n      context\n    )\n\n    // No more visible steps - complete the tour\n    if (nextStepIndex === -1) {\n      completeTour()\n      return\n    }\n\n    // Navigate to the next visible step\n    const navigated = await navigateToStep(nextStepIndex)\n    if (!navigated) {\n      // Reset the transitioning flag we set above. The auto-strategy failure\n      // path (TARGET_NOT_FOUND / NAVIGATION_REJECTED) already dispatches\n      // STOP_TOUR which clears the flag — this redundant dispatch only\n      // matters for the prompt / manual / hidden-terminate paths where the\n      // tour is still active but the navigation was deferred.\n      dispatch({ type: 'SET_TRANSITIONING', isTransitioning: false })\n      return\n    }\n\n    const nextStep = currentTour.steps[nextStepIndex]\n    if (nextStep) {\n      dispatch({\n        type: 'TRACK_STEP_VISIT',\n        stepId: nextStep.id,\n        previousStepId: currentStep?.id ?? null,\n      })\n      tourKitContext?.onStepView?.(currentTour.id, nextStep.id, nextStepIndex)\n      currentTour.onStepChange?.(nextStep, nextStepIndex, {\n        ...state,\n        tour: currentTour,\n        data,\n      })\n    }\n  }, [\n    state,\n    currentTour,\n    data,\n    tourKitContext,\n    navigateToStep,\n    completeTour,\n    buildBranchContext,\n    handleBranchTarget,\n  ])\n\n  // biome-ignore lint/complexity/noExcessiveCognitiveComplexity: step navigation with branch/loop handling\n  const prev = React.useCallback(async () => {\n    if (!state.isActive || !currentTour) return\n\n    const currentStep = state.currentStep\n\n    // Check for onPrev branch override\n    if (currentStep?.onPrev !== undefined) {\n      // null means disable going back\n      if (currentStep.onPrev === null) {\n        return\n      }\n      dispatch({ type: 'SET_TRANSITIONING', isTransitioning: true })\n      const branchContext = buildBranchContext()\n      const target = await resolveBranch(currentStep.onPrev, branchContext)\n      await handleBranchTarget(target, branchContext)\n      return\n    }\n\n    // Default: don't go back if at first step\n    if (state.currentStepIndex <= 0) return\n\n    dispatch({ type: 'SET_TRANSITIONING', isTransitioning: true })\n\n    // Build context and find previous visible step (skipping steps where when returns false)\n    const context = buildCallbackContext(state, currentTour, data)\n    const prevStepIndex = await findNextVisibleStepIndex(\n      state.currentStepIndex - 1,\n      -1, // backward direction\n      currentTour.steps,\n      context\n    )\n\n    // No previous visible step - stay on current step\n    if (prevStepIndex === -1) {\n      dispatch({ type: 'SET_TRANSITIONING', isTransitioning: false })\n      return\n    }\n\n    // Navigate to the previous visible step\n    const navigated = await navigateToStep(prevStepIndex)\n\n    if (!navigated) {\n      dispatch({ type: 'SET_TRANSITIONING', isTransitioning: false })\n      return\n    }\n\n    const prevStep = currentTour.steps[prevStepIndex]\n    if (prevStep) {\n      dispatch({\n        type: 'TRACK_STEP_VISIT',\n        stepId: prevStep.id,\n        previousStepId: currentStep?.id ?? null,\n      })\n      tourKitContext?.onStepView?.(currentTour.id, prevStep.id, prevStepIndex)\n      currentTour.onStepChange?.(prevStep, prevStepIndex, {\n        ...state,\n        tour: currentTour,\n        data,\n      })\n    }\n  }, [\n    state,\n    currentTour,\n    data,\n    tourKitContext,\n    navigateToStep,\n    buildBranchContext,\n    handleBranchTarget,\n  ])\n\n  const goTo = React.useCallback(\n    async (stepIndex: number) => {\n      if (!state.isActive || !currentTour) return\n\n      const targetStep = currentTour.steps[stepIndex]\n      if (!targetStep) return\n\n      dispatch({ type: 'SET_TRANSITIONING', isTransitioning: true })\n\n      // Build context and evaluate when condition for target step\n      const context = buildCallbackContext(state, currentTour, data)\n      const stepContext: TourCallbackContext = {\n        ...context,\n        currentStepIndex: stepIndex,\n        currentStep: targetStep,\n      }\n      const shouldShow = await evaluateStepWhen(targetStep, stepContext)\n\n      // If target step can be shown, use it; otherwise find nearest visible step\n      const targetIndex = shouldShow\n        ? stepIndex\n        : await findNearestVisibleStepIndex(stepIndex + 1, currentTour.steps, context)\n\n      if (targetIndex === -1) {\n        dispatch({ type: 'SET_TRANSITIONING', isTransitioning: false })\n        return\n      }\n\n      // Navigate to the target visible step\n      const navigated = await navigateToStep(targetIndex)\n      if (!navigated) {\n        dispatch({ type: 'SET_TRANSITIONING', isTransitioning: false })\n        return\n      }\n\n      const step = currentTour.steps[targetIndex]\n      if (step) {\n        tourKitContext?.onStepView?.(currentTour.id, step.id, targetIndex)\n        currentTour.onStepChange?.(step, targetIndex, {\n          ...state,\n          tour: currentTour,\n          data,\n        })\n      }\n    },\n    [state, currentTour, data, tourKitContext, navigateToStep]\n  )\n\n  const skip = skipTour\n  const complete = completeTour\n\n  const stop = React.useCallback(() => {\n    dispatch({ type: 'STOP_TOUR' })\n  }, [])\n\n  const setDontShowAgain = React.useCallback((_tourId: string, _value: boolean) => {\n    // Implemented in usePersistence hook\n  }, [])\n\n  const reset = React.useCallback(\n    (tourId?: string) => {\n      if (persistTerminalTours) resetPersistence(tourId)\n      dispatch({ type: 'RESET', tourId })\n    },\n    [persistTerminalTours, resetPersistence]\n  )\n\n  // Navigate to a step by its ID\n  const goToStep = React.useCallback(\n    async (stepId: string) => {\n      if (!state.isActive || !currentTour) return\n\n      const stepIndex = stepIdMap.get(stepId)\n      if (stepIndex === undefined) {\n        logger.warn(`Step \"${stepId}\" not found in tour`)\n        return\n      }\n\n      await goTo(stepIndex)\n    },\n    [state.isActive, currentTour, stepIdMap, goTo]\n  )\n\n  // Start a different tour (for cross-tour branching)\n  const startTour = React.useCallback(\n    async (tourId: string, stepId?: string | number) => {\n      const tour = state.tours.get(tourId)\n      if (!tour) {\n        logger.warn(`Tour \"${tourId}\" not found`)\n        return\n      }\n\n      let stepIndex: number | undefined\n      if (stepId !== undefined) {\n        if (typeof stepId === 'number') {\n          stepIndex = stepId\n        } else {\n          const tourStepMap = new Map<string, number>()\n          tour.steps.forEach((s, i) => tourStepMap.set(s.id, i))\n          stepIndex = tourStepMap.get(stepId)\n          if (stepIndex === undefined) {\n            logger.warn(`Step \"${stepId}\" not found in tour \"${tourId}\"`)\n          }\n        }\n      }\n\n      await start(tourId, stepIndex)\n    },\n    [state.tours, start]\n  )\n\n  // Trigger a branch action defined in the current step's onAction\n  const triggerBranchAction = React.useCallback(\n    async (actionId: string, payload?: unknown) => {\n      if (!state.isActive || !currentTour || !state.currentStep) return\n\n      const currentStep = state.currentStep\n      const branch = currentStep.onAction?.[actionId]\n\n      if (!branch) {\n        logger.warn(`Action \"${actionId}\" not found on step \"${currentStep.id}\"`)\n        return\n      }\n\n      dispatch({ type: 'SET_TRANSITIONING', isTransitioning: true })\n\n      const branchContext = buildBranchContext(actionId, payload)\n      const target = await resolveBranch(branch, branchContext)\n\n      // Fire analytics callbacks\n      tourKitContext?.onBranchAction?.(currentTour.id, currentStep.id, actionId, target)\n      currentTour.onBranchAction?.(currentStep.id, actionId, target)\n\n      await handleBranchTarget(target, branchContext, actionId)\n    },\n    [\n      state.isActive,\n      currentTour,\n      state.currentStep,\n      buildBranchContext,\n      tourKitContext,\n      handleBranchTarget,\n    ]\n  )\n\n  // ─── Tour registry wiring (Phase 1, useTourActions) ──────────────────────\n  // Every tour in `tours` self-registers in the module-level `tourRegistry` so\n  // a sibling subtree can call `useTourActions(id).start()` without prop\n  // drilling or window-event workarounds. The registry is decoupled from the\n  // React tree (module-level Map<string, WeakRef<RegistryEntry>>), so the\n  // sibling consumer does NOT need to be inside this provider.\n  //\n  // Two effects below:\n  //   1. Lifecycle effect — registers one entry per tour on mount, unregisters\n  //      on unmount. Stable key is the NUL-joined ids so inline `tours={[...]}`\n  //      props don't re-register every render.\n  //   2. State-mirror effect — replaces each entry's `state` slice when the\n  //      reducer fires. The registry only notifies subscribers when the slice\n  //      actually changed, so spurious renders are clamped to one per real\n  //      transition.\n  //\n  // Action methods are wired through latest-state refs (`controllerRef`) so\n  // entries can be created once and the closures stay valid as the controller\n  // identity churns on every state change. This mirrors the `bridgeMethodsRef`\n  // pattern below and keeps the registry entry stable for the lifetime of the\n  // tour.\n  const controllerRef = React.useRef({ start, stop, next, prev, goToStep })\n  React.useEffect(() => {\n    controllerRef.current = { start, stop, next, prev, goToStep }\n  })\n\n  // `tourIdsKey` is declared earlier (diagnostic engine block) — reuse it here.\n  React.useEffect(() => {\n    if (tourIdsKey.length === 0) return\n    const ids = tourIdsKey.split('\\x00').filter(Boolean)\n    const unregisters: Array<() => void> = []\n    for (const id of ids) {\n      const unregister = tourRegistry.register({\n        id,\n        state: { isActive: false, currentStepId: null, progress: 0 },\n        actions: {\n          start: () => {\n            void controllerRef.current.start(id)\n          },\n          stop: () => {\n            controllerRef.current.stop()\n          },\n          restart: () => {\n            void controllerRef.current.start(id, 0)\n          },\n          next: () => {\n            void controllerRef.current.next()\n          },\n          prev: () => {\n            void controllerRef.current.prev()\n          },\n          goToStep: (stepId) => {\n            void controllerRef.current.goToStep(stepId)\n          },\n        },\n      })\n      unregisters.push(unregister)\n    }\n    return () => {\n      for (const u of unregisters) u()\n    }\n  }, [tourIdsKey])\n\n  React.useEffect(() => {\n    if (tourIdsKey.length === 0) return\n    const ids = tourIdsKey.split('\\x00').filter(Boolean)\n    for (const id of ids) {\n      const isThisTourActive = state.isActive && state.tourId === id\n      const progress =\n        isThisTourActive && state.totalSteps > 0\n          ? (state.currentStepIndex + 1) / state.totalSteps\n          : 0\n      tourRegistry.update(id, {\n        isActive: isThisTourActive,\n        currentStepId: isThisTourActive ? (state.currentStep?.id ?? null) : null,\n        progress,\n      })\n    }\n  }, [\n    tourIdsKey,\n    state.isActive,\n    state.tourId,\n    state.currentStep,\n    state.currentStepIndex,\n    state.totalSteps,\n  ])\n\n  // ─── Test bridge wiring (Phase 6, issue #86) ─────────────────────────────\n  // `enableTestBridge` opts in to `window.__tourKit__` — used by Playwright\n  // helpers to drive a tour from out-of-process. Default is `false` so\n  // production never leaks the surface. The effect short-circuits at the top\n  // when disabled, making the bridge body dead-code under a literal `false`.\n  //\n  // Why a methods ref:\n  // - The bridge identity is stable per mount, but each call must dispatch\n  //   through the LATEST `start`/`next`/etc. closures. A ref avoids\n  //   re-creating (and re-publishing) the bridge on every controller-method\n  //   identity change, which would invalidate any cached helper closures in\n  //   long-running Playwright contexts.\n  // Build the latest-methods snapshot once per render, then publish to the ref.\n  // The ref initial value uses the same object so the first effect run sees a\n  // populated `current` even before this render's assignment commits.\n  const bridgeMethods = {\n    start,\n    next,\n    previous: prev,\n    goToStep,\n    complete,\n    skip,\n    diagnostics,\n  }\n  const bridgeMethodsRef = React.useRef(bridgeMethods)\n  bridgeMethodsRef.current = bridgeMethods\n\n  const testBridgeWarnedRef = React.useRef(false)\n\n  React.useEffect(() => {\n    if (!enableTestBridge) return\n    if (typeof window === 'undefined') return\n\n    if (typeof process === 'undefined' || process.env?.NODE_ENV !== 'production') {\n      if (!testBridgeWarnedRef.current) {\n        testBridgeWarnedRef.current = true\n        console.warn('[Tour Kit] Test bridge enabled. Disable for production.')\n      }\n    }\n\n    const bridge: TestBridge = {\n      start: (tourId) => {\n        void bridgeMethodsRef.current.start(tourId)\n      },\n      next: () => {\n        void bridgeMethodsRef.current.next()\n      },\n      previous: () => {\n        void bridgeMethodsRef.current.previous()\n      },\n      goToStep: (stepId) => {\n        void bridgeMethodsRef.current.goToStep(stepId)\n      },\n      complete: () => {\n        bridgeMethodsRef.current.complete()\n      },\n      skip: () => {\n        bridgeMethodsRef.current.skip()\n      },\n      getDiagnostic: (tourId) => bridgeMethodsRef.current.diagnostics[tourId] ?? null,\n    }\n    window.__tourKit__ = bridge\n\n    return () => {\n      // Identity check defends against another library reassigning the global\n      // between our mount and unmount — see the cleanup-safety unit test.\n      if (window.__tourKit__ === bridge) {\n        // biome-ignore lint/performance/noDelete: full removal mirrors the absent-by-default invariant — `= undefined` would leave an own property and break consumer `'__tourKit__' in window` checks\n        delete window.__tourKit__\n      }\n    }\n  }, [enableTestBridge])\n\n  const contextValue = React.useMemo<TourContextValue>(\n    () => ({\n      ...state,\n      tour: currentTour,\n      data,\n      start,\n      next,\n      prev,\n      goTo,\n      skip,\n      complete,\n      stop,\n      setDontShowAgain,\n      reset,\n      setData,\n      goToStep,\n      startTour,\n      triggerBranchAction,\n      // Only attach the diagnostics field when `diagnose` is on — keeps\n      // `ctx.diagnostics` strictly undefined for opted-out consumers so the\n      // hook's `null` branch is observable.\n      ...(diagnose ? { diagnostics } : {}),\n    }),\n    [\n      state,\n      currentTour,\n      data,\n      start,\n      next,\n      prev,\n      goTo,\n      skip,\n      complete,\n      stop,\n      setDontShowAgain,\n      reset,\n      setData,\n      goToStep,\n      startTour,\n      triggerBranchAction,\n      diagnose,\n      diagnostics,\n    ]\n  )\n\n  return (\n    <TourContext.Provider value={contextValue}>\n      <AdvanceOnEffect />\n      {children}\n    </TourContext.Provider>\n  )\n}\n\n/**\n * Internal component to handle advanceOn behavior\n * This needs to be a separate component because hooks can't be called\n * conditionally, and useAdvanceOn needs access to the TourContext\n */\nfunction AdvanceOnEffect() {\n  useAdvanceOn()\n  return null\n}\n","import { useCallback, useContext, useMemo } from 'react'\nimport { TourContext } from '../context/tour-context'\nimport type { TourStep } from '../types'\n\n/**\n * Return shape of `useTour()`.\n *\n * `goToStep` and `startTour` are surfaced at the top level (no `.actions.`\n * prefix) and accept step ids narrowed to `TStep['id']`. When `TStep` defaults\n * to `TourStep`, the id parameter widens to `string` — preserving every\n * existing call site that writes `useTour().start(...)` / `useTour().next(...)`.\n */\nexport interface UseTourReturn<TStep extends TourStep = TourStep> {\n  // State\n  isActive: boolean\n  isLoading: boolean\n  isTransitioning: boolean\n  currentStep: TStep | null\n  currentStepIndex: number\n  totalSteps: number\n  isFirstStep: boolean\n  isLastStep: boolean\n  progress: number\n\n  // Actions\n  start: (tourIdOrStepIndex?: string | number, stepIndex?: number) => void\n  next: () => void\n  prev: () => void\n  goTo: (stepIndex: number) => void\n  skip: () => void\n  complete: () => void\n  stop: () => void\n  /**\n   * Navigate directly to a step by its ID. Narrowed to `TStep['id']` when a\n   * concrete step type is supplied — misspellings fail at compile time.\n   */\n  goToStep: <TId extends TStep['id'] = TStep['id']>(stepId: TId) => Promise<void>\n  /**\n   * Start a different tour by ID. `stepId` is narrowed to that tour's step\n   * ids when `TStep` is specified, or widens to `string | number` by default.\n   */\n  startTour: <TId extends TStep['id'] = TStep['id']>(\n    tourId: string,\n    stepId?: TId | number\n  ) => Promise<void>\n\n  // Utilities\n  isStepActive: (stepId: TStep['id']) => boolean\n  getStep: (stepId: TStep['id']) => TStep | undefined\n}\n\nexport function useTour<TStep extends TourStep = TourStep>(tourId?: string): UseTourReturn<TStep> {\n  const context = useContext(TourContext)\n\n  if (!context) {\n    throw new Error('useTour must be used within a TourProvider')\n  }\n\n  const {\n    tourId: activeTourId,\n    isActive,\n    isLoading,\n    isTransitioning,\n    currentStep,\n    currentStepIndex,\n    totalSteps,\n    tour,\n    start: contextStart,\n    next,\n    prev,\n    goTo,\n    skip,\n    complete,\n    stop,\n    goToStep: contextGoToStep,\n    startTour: contextStartTour,\n  } = context\n\n  // If tourId provided, only active if it matches\n  const isThisTourActive = tourId ? isActive && activeTourId === tourId : isActive\n\n  const start = useCallback(\n    (tourIdOrStepIndex?: string | number, stepIndex?: number) => {\n      // If first arg is a string, it's a tourId\n      if (typeof tourIdOrStepIndex === 'string') {\n        contextStart(tourIdOrStepIndex, stepIndex)\n      } else if (typeof tourIdOrStepIndex === 'number') {\n        // First arg is a step index, use hook's tourId\n        contextStart(tourId, tourIdOrStepIndex)\n      } else {\n        // No args, use hook's tourId\n        contextStart(tourId)\n      }\n    },\n    [contextStart, tourId]\n  )\n\n  const isFirstStep = currentStepIndex === 0\n  const isLastStep = totalSteps > 0 && currentStepIndex === totalSteps - 1\n  const progress = totalSteps > 0 ? (currentStepIndex + 1) / totalSteps : 0\n\n  const isStepActive = useCallback(\n    (stepId: TStep['id']) => currentStep?.id === stepId,\n    [currentStep]\n  )\n\n  const getStep = useCallback(\n    (stepId: TStep['id']) => tour?.steps.find((s) => s.id === stepId) as TStep | undefined,\n    [tour]\n  )\n\n  return useMemo(\n    () =>\n      ({\n        isActive: isThisTourActive,\n        isLoading,\n        isTransitioning,\n        currentStep: isThisTourActive ? currentStep : null,\n        currentStepIndex: isThisTourActive ? currentStepIndex : 0,\n        totalSteps: isThisTourActive ? totalSteps : 0,\n        isFirstStep,\n        isLastStep,\n        progress,\n        start,\n        next,\n        prev,\n        goTo,\n        skip,\n        complete,\n        stop,\n        goToStep: contextGoToStep,\n        startTour: contextStartTour,\n        isStepActive,\n        getStep,\n      }) as unknown as UseTourReturn<TStep>,\n    [\n      isThisTourActive,\n      isLoading,\n      isTransitioning,\n      currentStep,\n      currentStepIndex,\n      totalSteps,\n      isFirstStep,\n      isLastStep,\n      progress,\n      start,\n      next,\n      prev,\n      goTo,\n      skip,\n      complete,\n      stop,\n      contextGoToStep,\n      contextStartTour,\n      isStepActive,\n      getStep,\n    ]\n  )\n}\n","import { useCallback, useEffect, useMemo, useRef, useState } from 'react'\nimport type { TourTarget } from '../types/target'\nimport { getElement, getScrollParent } from '../utils/dom'\nimport { throttleRAF } from '../utils/throttle'\n\nexport interface ElementPositionResult {\n  element: HTMLElement | null\n  rect: DOMRect | null\n  scrollParent: HTMLElement | Window | null\n  update: () => void\n}\n\n/**\n * Subscribe to a target's position. Accepts every `TourTarget` shape (string\n * selector, `RefObject`, getter) plus a direct `HTMLElement` for callers that\n * already hold the resolved node. Resolution flows through `getElement`, which\n * delegates the union branches to `resolveTarget`.\n */\nexport function useElementPosition(target: TourTarget | HTMLElement | null): ElementPositionResult {\n  const [element, setElement] = useState<HTMLElement | null>(null)\n  const [rect, setRect] = useState<DOMRect | null>(null)\n  const [scrollParent, setScrollParent] = useState<HTMLElement | Window | null>(null)\n  const observerRef = useRef<ResizeObserver | null>(null)\n\n  // Resolve target to element\n  useEffect(() => {\n    const el = getElement(target)\n    setElement(el)\n    setScrollParent(el ? getScrollParent(el) : null)\n  }, [target])\n\n  const update = useCallback(() => {\n    if (element) {\n      setRect(element.getBoundingClientRect())\n    }\n  }, [element])\n\n  // Throttle updates to RAF for smooth 60fps during scroll/resize\n  const throttledUpdate = useMemo(() => throttleRAF(update), [update])\n\n  useEffect(() => {\n    if (!element) {\n      setRect(null)\n      return\n    }\n\n    update()\n\n    // Observe element resize\n    observerRef.current = new ResizeObserver(throttledUpdate)\n    observerRef.current.observe(element)\n\n    // Listen for window scroll/resize with passive listeners for better performance\n    window.addEventListener('scroll', throttledUpdate, { passive: true, capture: true })\n    window.addEventListener('resize', throttledUpdate, { passive: true })\n\n    // Also observe scrollable parent's resize if it's not window\n    if (scrollParent && scrollParent !== window && scrollParent instanceof HTMLElement) {\n      observerRef.current.observe(scrollParent)\n    }\n\n    return () => {\n      throttledUpdate.cancel()\n      observerRef.current?.disconnect()\n      window.removeEventListener('scroll', throttledUpdate, true)\n      window.removeEventListener('resize', throttledUpdate)\n    }\n  }, [element, scrollParent, update, throttledUpdate])\n\n  return { element, rect, scrollParent, update }\n}\n","import { useCallback, useContext, useEffect, useMemo, useState } from 'react'\nimport { TourContext } from '../context/tour-context'\nimport { useElementPosition } from './use-element-position'\n\nexport interface UseStepReturn {\n  isActive: boolean\n  isVisible: boolean\n  hasCompleted: boolean\n  targetElement: HTMLElement | null\n  targetRect: DOMRect | null\n  show: () => void\n  hide: () => void\n  complete: () => void\n}\n\nexport function useStep(stepId: string): UseStepReturn {\n  const context = useContext(TourContext)\n\n  if (!context) {\n    throw new Error('useStep must be used within a TourProvider')\n  }\n\n  const { currentStep, goTo, tour, next } = context\n\n  const step = tour?.steps.find((s) => s.id === stepId)\n  const stepIndex = tour?.steps.findIndex((s) => s.id === stepId) ?? -1\n\n  const isActive = currentStep?.id === stepId\n  const [isVisible, setIsVisible] = useState(false)\n  const [hasCompleted, setHasCompleted] = useState(false)\n\n  const { element: targetElement, rect: targetRect } = useElementPosition(step?.target ?? null)\n\n  useEffect(() => {\n    if (isActive) {\n      setIsVisible(true)\n    }\n  }, [isActive])\n\n  const show = useCallback(() => {\n    if (stepIndex >= 0) {\n      goTo(stepIndex)\n    }\n  }, [goTo, stepIndex])\n\n  const hide = useCallback(() => {\n    setIsVisible(false)\n  }, [])\n\n  const complete = useCallback(() => {\n    setHasCompleted(true)\n    next()\n  }, [next])\n\n  return useMemo(\n    () => ({\n      isActive,\n      isVisible,\n      hasCompleted,\n      targetElement,\n      targetRect,\n      show,\n      hide,\n      complete,\n    }),\n    [isActive, isVisible, hasCompleted, targetElement, targetRect, show, hide, complete]\n  )\n}\n","import { useCallback, useEffect, useMemo, useRef, useState } from 'react'\nimport type { SpotlightConfig } from '../types'\nimport { defaultSpotlightConfig } from '../types/config'\nimport { throttleRAF } from '../utils/throttle'\n\nexport interface UseSpotlightReturn {\n  isVisible: boolean\n  targetRect: DOMRect | null\n  overlayStyle: React.CSSProperties\n  cutoutStyle: React.CSSProperties\n  show: (target: HTMLElement, config?: SpotlightConfig) => void\n  hide: () => void\n  update: () => void\n}\n\nexport function useSpotlight(): UseSpotlightReturn {\n  const [isVisible, setIsVisible] = useState(false)\n  const [targetRect, setTargetRect] = useState<DOMRect | null>(null)\n  const [config, setConfig] = useState<SpotlightConfig>(defaultSpotlightConfig)\n  const targetRef = useRef<HTMLElement | null>(null)\n\n  const updateRect = useCallback(() => {\n    if (targetRef.current) {\n      setTargetRect(targetRef.current.getBoundingClientRect())\n    }\n  }, [])\n\n  // Throttle updates to RAF for smooth 60fps during scroll/resize\n  const throttledUpdateRect = useMemo(() => throttleRAF(updateRect), [updateRect])\n\n  useEffect(() => {\n    if (!isVisible) return\n\n    window.addEventListener('scroll', throttledUpdateRect, { passive: true, capture: true })\n    window.addEventListener('resize', throttledUpdateRect, { passive: true })\n\n    return () => {\n      throttledUpdateRect.cancel()\n      window.removeEventListener('scroll', throttledUpdateRect, true)\n      window.removeEventListener('resize', throttledUpdateRect)\n    }\n  }, [isVisible, throttledUpdateRect])\n\n  const show = useCallback((target: HTMLElement, spotlightConfig?: SpotlightConfig) => {\n    targetRef.current = target\n    setConfig({ ...defaultSpotlightConfig, ...spotlightConfig })\n    setTargetRect(target.getBoundingClientRect())\n    setIsVisible(true)\n  }, [])\n\n  const hide = useCallback(() => {\n    setIsVisible(false)\n    targetRef.current = null\n    setTargetRect(null)\n  }, [])\n\n  const overlayStyle = useMemo<React.CSSProperties>(\n    () => ({\n      position: 'fixed',\n      inset: 0,\n      backgroundColor: 'transparent',\n      transition: config.animate ? `all ${config.animationDuration ?? 300}ms ease-out` : undefined,\n      pointerEvents: 'auto',\n    }),\n    [config]\n  )\n\n  const cutoutStyle = useMemo<React.CSSProperties>(() => {\n    if (!targetRect) return {}\n\n    const padding = config.padding ?? 8\n    const borderRadius = config.borderRadius ?? 4\n\n    return {\n      position: 'absolute',\n      top: targetRect.top - padding,\n      left: targetRect.left - padding,\n      width: targetRect.width + padding * 2,\n      height: targetRect.height + padding * 2,\n      borderRadius,\n      boxShadow: `0 0 0 9999px ${config.color ?? 'rgba(0, 0, 0, 0.5)'}`,\n      transition: config.animate ? `all ${config.animationDuration ?? 300}ms ease-out` : undefined,\n      pointerEvents: 'none',\n    }\n  }, [targetRect, config])\n\n  return useMemo(\n    () => ({\n      isVisible,\n      targetRect,\n      overlayStyle,\n      cutoutStyle,\n      show,\n      hide,\n      update: updateRect,\n    }),\n    [isVisible, targetRect, overlayStyle, cutoutStyle, show, hide, updateRect]\n  )\n}\n","import { useContext, useEffect, useMemo } from 'react'\nimport { TourContext } from '../context/tour-context'\nimport type { KeyboardConfig } from '../types'\nimport { defaultKeyboardConfig } from '../types/config'\n\nexport function useKeyboardNavigation(config?: KeyboardConfig): void {\n  const context = useContext(TourContext)\n\n  if (!context) {\n    throw new Error('useKeyboardNavigation must be used within a TourProvider')\n  }\n\n  const { isActive, next, prev, skip } = context\n  const mergedConfig = useMemo(() => ({ ...defaultKeyboardConfig, ...config }), [config])\n\n  useEffect(() => {\n    if (!isActive || !mergedConfig.enabled) return\n\n    const handleKeyDown = (event: KeyboardEvent) => {\n      const { key } = event\n\n      // Ignore if user is typing in an input, select, or editable region\n      const active = document.activeElement as HTMLElement | null\n      if (\n        active instanceof HTMLInputElement ||\n        active instanceof HTMLTextAreaElement ||\n        active instanceof HTMLSelectElement ||\n        active?.isContentEditable ||\n        active?.getAttribute('role') === 'textbox'\n      ) {\n        return\n      }\n\n      if (mergedConfig.nextKeys?.includes(key)) {\n        event.preventDefault()\n        next()\n      } else if (mergedConfig.prevKeys?.includes(key)) {\n        event.preventDefault()\n        prev()\n      } else if (mergedConfig.exitKeys?.includes(key)) {\n        event.preventDefault()\n        skip()\n      }\n    }\n\n    document.addEventListener('keydown', handleKeyDown)\n    return () => document.removeEventListener('keydown', handleKeyDown)\n  }, [isActive, mergedConfig, next, prev, skip])\n}\n","import { useCallback, useEffect, useRef } from 'react'\nimport { getFocusableElements } from '../utils/dom'\n\nexport interface UseFocusTrapOptions {\n  /**\n   * When `true`, sibling content outside the trapped container is marked\n   * `inert` + `aria-hidden=\"true\"` while the trap is active, giving true modal\n   * semantics (`aria-modal=\"true\"`). The subtree containing the trapped\n   * container (e.g. its portal root) is left interactive. Attributes are\n   * restored to their previous values on deactivate/unmount.\n   *\n   * Default: `false` (focus is trapped, but the background stays perceivable —\n   * appropriate for non-modal dialogs).\n   */\n  inertBackground?: boolean\n}\n\nexport interface UseFocusTrapReturn {\n  containerRef: React.RefObject<HTMLElement | null>\n  activate: () => void\n  deactivate: () => void\n}\n\n/**\n * Module-level ref-count of the `inert` + `aria-hidden` applied to background\n * elements. Concurrent/nested inert-background traps may touch the same element;\n * each records the ORIGINAL (pre-any-trap) state once and increments a count,\n * and the original is only restored when the last trap releases. Without this,\n * the later trap's restore could re-apply `aria-hidden` after the first removed\n * it, stranding the background hidden from assistive tech.\n */\ninterface InertRecord {\n  count: number\n  originalInert: boolean\n  originalAriaHidden: string | null\n}\nconst inertRegistry = new WeakMap<HTMLElement, InertRecord>()\n\n/**\n * Marks every direct child of `document.body` that does not contain `container`\n * as `inert` + `aria-hidden`, returning a function that releases this trap's\n * hold (restoring the original state once no trap needs the element hidden).\n * `container` is typically inside a portal appended to `body`, so its own portal\n * root is skipped and stays interactive.\n */\nfunction applyBackgroundInert(container: HTMLElement): () => void {\n  if (typeof document === 'undefined' || !document.body) return () => {}\n\n  const affected: HTMLElement[] = []\n\n  for (const child of Array.from(document.body.children)) {\n    if (!(child instanceof HTMLElement)) continue\n    // Leave the subtree that owns the trapped container interactive.\n    if (child === container || child.contains(container)) continue\n\n    affected.push(child)\n    const existing = inertRegistry.get(child)\n    if (existing) {\n      existing.count += 1\n    } else {\n      inertRegistry.set(child, {\n        count: 1,\n        originalInert: child.hasAttribute('inert'),\n        originalAriaHidden: child.getAttribute('aria-hidden'),\n      })\n      child.setAttribute('inert', '')\n      child.setAttribute('aria-hidden', 'true')\n    }\n  }\n\n  return () => {\n    for (const el of affected) {\n      const record = inertRegistry.get(el)\n      if (!record) continue\n      record.count -= 1\n      if (record.count > 0) continue\n      // Last trap released — restore the original (pre-trap) state.\n      inertRegistry.delete(el)\n      if (!record.originalInert) el.removeAttribute('inert')\n      if (record.originalAriaHidden === null) {\n        el.removeAttribute('aria-hidden')\n      } else {\n        el.setAttribute('aria-hidden', record.originalAriaHidden)\n      }\n    }\n  }\n}\n\nexport function useFocusTrap(\n  enabled = true,\n  options: UseFocusTrapOptions = {}\n): UseFocusTrapReturn {\n  const { inertBackground = false } = options\n\n  const containerRef = useRef<HTMLElement | null>(null)\n  const previousActiveElement = useRef<HTMLElement | null>(null)\n  const isTrapping = useRef(false)\n  const restoreInert = useRef<(() => void) | null>(null)\n\n  const handleKeyDown = useCallback((event: KeyboardEvent) => {\n    if (!isTrapping.current || event.key !== 'Tab' || !containerRef.current) {\n      return\n    }\n\n    const container = containerRef.current\n    const focusable = getFocusableElements(container)\n\n    if (focusable.length === 0) {\n      // Nothing focusable inside — keep focus on the container itself rather\n      // than letting Tab escape to the background.\n      event.preventDefault()\n      container.focus()\n      return\n    }\n\n    const first = focusable[0]\n    const last = focusable[focusable.length - 1]\n    const active = document.activeElement\n\n    // If focus has drifted outside the container, pull it back in. Guards the\n    // case where focus is on neither the first nor last focusable (so the\n    // boundary checks below would miss it) yet has left the dialog.\n    if (!(active instanceof Node) || !container.contains(active)) {\n      event.preventDefault()\n      first.focus()\n      return\n    }\n\n    if (event.shiftKey && active === first) {\n      event.preventDefault()\n      last.focus()\n    } else if (!event.shiftKey && active === last) {\n      event.preventDefault()\n      first.focus()\n    }\n  }, [])\n\n  const activate = useCallback(() => {\n    if (!enabled || !containerRef.current) return\n    // Idempotent: don't re-capture the previously-focused element if already\n    // trapping (e.g. an effect firing twice under React Strict Mode).\n    if (isTrapping.current) return\n\n    // Prefer the element captured when the trap was enabled (see effect below).\n    // Falling back to `document.activeElement` here is a last resort — by the\n    // time activate() runs (often several renders later, once a lazy portal has\n    // mounted), focus may already have drifted to <body>.\n    if (!previousActiveElement.current) {\n      const active = document.activeElement as HTMLElement | null\n      if (active && active !== document.body) {\n        previousActiveElement.current = active\n      }\n    }\n    isTrapping.current = true\n\n    if (inertBackground) {\n      restoreInert.current = applyBackgroundInert(containerRef.current)\n    }\n\n    const focusable = getFocusableElements(containerRef.current)\n    if (focusable.length > 0) {\n      focusable[0].focus()\n    } else {\n      containerRef.current.focus?.()\n    }\n\n    document.addEventListener('keydown', handleKeyDown)\n  }, [enabled, inertBackground, handleKeyDown])\n\n  const deactivate = useCallback(() => {\n    document.removeEventListener('keydown', handleKeyDown)\n\n    restoreInert.current?.()\n    restoreInert.current = null\n\n    if (isTrapping.current && previousActiveElement.current) {\n      previousActiveElement.current.focus()\n    }\n    previousActiveElement.current = null\n    isTrapping.current = false\n  }, [handleKeyDown])\n\n  // Capture the element to restore focus to as soon as the trap becomes\n  // enabled — before the portal mounts or `inert`/focus moves shift\n  // `document.activeElement` to <body>. activate() can run several renders\n  // later (once a lazy portal node exists), by which point the trigger is no\n  // longer the active element. Capturing here makes focus restoration reliable.\n  useEffect(() => {\n    if (!enabled) {\n      // Enabled→false without a deactivate() (e.g. the trap was enabled but its\n      // consumer never activated because a lazy portal never mounted). Clear the\n      // captured element so the next enable re-captures the correct trigger\n      // instead of restoring focus to a stale one.\n      if (!isTrapping.current) previousActiveElement.current = null\n      return\n    }\n    if (previousActiveElement.current) return\n    const active = document.activeElement as HTMLElement | null\n    if (active && active !== document.body) {\n      previousActiveElement.current = active\n    }\n  }, [enabled])\n\n  useEffect(() => {\n    return () => {\n      document.removeEventListener('keydown', handleKeyDown)\n      restoreInert.current?.()\n      restoreInert.current = null\n    }\n  }, [handleKeyDown])\n\n  return { containerRef, activate, deactivate }\n}\n","import { useCallback, useEffect, useState, useSyncExternalStore } from 'react'\n\n/**\n * SSR-safe media query hook.\n *\n * Uses `useSyncExternalStore` so the server snapshot (`false`) is also used for\n * the first client (hydration) render, then React re-renders with the real\n * `matchMedia` value after hydration. This guarantees the first client render\n * matches the server output — no hydration mismatch — without reading\n * `matchMedia` in a render-time initializer.\n */\nexport function useMediaQuery(query: string): boolean {\n  const subscribe = useCallback(\n    (onChange: () => void) => {\n      if (typeof window === 'undefined' || typeof window.matchMedia !== 'function') {\n        return () => {}\n      }\n      const mediaQuery = window.matchMedia(query)\n      mediaQuery.addEventListener('change', onChange)\n      return () => mediaQuery.removeEventListener('change', onChange)\n    },\n    [query]\n  )\n\n  const getSnapshot = useCallback(() => {\n    if (typeof window === 'undefined' || typeof window.matchMedia !== 'function') {\n      return false\n    }\n    return window.matchMedia(query).matches\n  }, [query])\n\n  // Server (and first hydration render) always reports `false` so client and\n  // server agree on the initial markup.\n  const getServerSnapshot = () => false\n\n  return useSyncExternalStore(subscribe, getSnapshot, getServerSnapshot)\n}\n\nexport function usePrefersReducedMotion(): boolean {\n  return useMediaQuery('(prefers-reduced-motion: reduce)')\n}\n\n/**\n * SSR-safe wrapper around `usePrefersReducedMotion` that defaults to `true`\n * server-side and on first client render (Comeau pattern), then flips to the\n * actual `matchMedia` value after the first effect.\n *\n * Why: animation classes that depend on this hook must default to \"no\n * animation\" during SSR/first paint to avoid a one-frame motion flash for\n * users who have requested reduced motion.\n */\nexport function useReducedMotion(): boolean {\n  const [reduce, setReduce] = useState(true)\n  const matches = useMediaQuery('(prefers-reduced-motion: reduce)')\n\n  useEffect(() => {\n    setReduce(matches)\n  }, [matches])\n\n  return reduce\n}\n","import { useCallback, useMemo } from 'react'\nimport { useTourContext } from '../context/tour-context'\nimport type { BranchContext, BranchTarget, UseBranchReturn } from '../types/branch'\nimport { resolveBranch } from '../utils/branch'\n\n/**\n * Hook for triggering branch actions from step content\n *\n * @example\n * ```tsx\n * function RoleSelectStep() {\n *   const { triggerAction, hasAction } = useBranch()\n *\n *   return (\n *     <div>\n *       <h2>What's your role?</h2>\n *       <button onClick={() => triggerAction('developer')}>\n *         I'm a Developer\n *       </button>\n *       <button onClick={() => triggerAction('designer')}>\n *         I'm a Designer\n *       </button>\n *     </div>\n *   )\n * }\n * ```\n *\n * @throws Error if used outside of TourProvider\n */\nexport function useBranch(): UseBranchReturn {\n  const context = useTourContext()\n\n  const currentStep = context.currentStep\n\n  /**\n   * List of available action IDs for the current step\n   */\n  const availableActions = useMemo(() => {\n    if (!currentStep?.onAction) return []\n    return Object.keys(currentStep.onAction)\n  }, [currentStep])\n\n  /**\n   * Check if an action is available for the current step\n   */\n  const hasAction = useCallback(\n    (actionId: string): boolean => {\n      return !!currentStep?.onAction?.[actionId]\n    },\n    [currentStep]\n  )\n\n  /**\n   * Trigger a named action defined in the current step's onAction\n   */\n  const triggerAction = useCallback(\n    async (actionId: string, payload?: unknown): Promise<void> => {\n      await context.triggerBranchAction(actionId, payload)\n    },\n    [context.triggerBranchAction]\n  )\n\n  /**\n   * Preview where an action would navigate without actually navigating\n   */\n  const previewAction = useCallback(\n    async (actionId: string, payload?: unknown): Promise<BranchTarget> => {\n      if (!currentStep?.onAction?.[actionId]) {\n        return 'next'\n      }\n\n      const branch = currentStep.onAction[actionId]\n\n      const previewContext: BranchContext = {\n        tourId: context.tourId,\n        isActive: context.isActive,\n        currentStepIndex: context.currentStepIndex,\n        currentStep: context.currentStep,\n        totalSteps: context.totalSteps,\n        isLoading: context.isLoading,\n        isTransitioning: context.isTransitioning,\n        completedTours: context.completedTours,\n        skippedTours: context.skippedTours,\n        visitedSteps: context.visitedSteps,\n        stepVisitCount: context.stepVisitCount,\n        previousStepId: context.previousStepId,\n        tour: context.tour,\n        data: context.data,\n        action: actionId,\n        actionPayload: payload,\n        setData: () => {},\n      }\n\n      try {\n        return await resolveBranch(branch, previewContext)\n      } catch {\n        return 'next'\n      }\n    },\n    [\n      currentStep,\n      context.tourId,\n      context.isActive,\n      context.currentStepIndex,\n      context.currentStep,\n      context.totalSteps,\n      context.isLoading,\n      context.isTransitioning,\n      context.completedTours,\n      context.skippedTours,\n      context.visitedSteps,\n      context.stepVisitCount,\n      context.previousStepId,\n      context.tour,\n      context.data,\n    ]\n  )\n\n  return {\n    triggerAction,\n    availableActions,\n    hasAction,\n    previewAction,\n  }\n}\n","import type { ScrollConfig } from '../types'\nimport { isElementVisible } from './dom'\n\nconst defaultScrollConfig: Required<ScrollConfig> = {\n  enabled: true,\n  behavior: 'smooth',\n  block: 'center',\n  offset: 20,\n}\n\n/**\n * Scroll element into view with configuration\n */\nexport function scrollIntoView(element: HTMLElement, config?: ScrollConfig): Promise<void> {\n  const mergedConfig = { ...defaultScrollConfig, ...config }\n\n  if (!mergedConfig.enabled) {\n    return Promise.resolve()\n  }\n\n  return new Promise((resolve) => {\n    if (isElementVisible(element)) {\n      resolve()\n      return\n    }\n\n    element.scrollIntoView({\n      behavior: mergedConfig.behavior,\n      block: mergedConfig.block,\n    })\n\n    // Estimate scroll duration\n    const duration = mergedConfig.behavior === 'smooth' ? 500 : 0\n    setTimeout(resolve, duration)\n  })\n}\n\n/**\n * Scroll to specific position\n */\nexport function scrollTo(\n  container: HTMLElement | Window,\n  position: { top?: number; left?: number },\n  behavior: ScrollBehavior = 'smooth'\n): void {\n  container.scrollTo({\n    ...position,\n    behavior,\n  })\n}\n\n/**\n * Get current scroll position\n */\nexport function getScrollPosition(container: HTMLElement | Window = window): {\n  x: number\n  y: number\n} {\n  if (container === window) {\n    return {\n      x: window.scrollX || document.documentElement.scrollLeft,\n      y: window.scrollY || document.documentElement.scrollTop,\n    }\n  }\n\n  const el = container as HTMLElement\n  return {\n    x: el.scrollLeft,\n    y: el.scrollTop,\n  }\n}\n\n/**\n * Symbol used to attach a shared lock state to `document.body`, so nested\n * `lockScroll()` calls (e.g. tour card opens a modal that also locks scroll)\n * share a single lock instead of each reading `scrollY === 0` once the body\n * is already fixed.\n */\nconst LOCK_KEY = Symbol.for('tourkit.scroll-lock')\n\ninterface LockState {\n  depth: number\n  scrollY: number\n  prev: {\n    position: string\n    top: string\n    width: string\n    overflowY: string\n  }\n}\n\ntype BodyWithLock = HTMLElement & { [LOCK_KEY]?: LockState }\n\n/**\n * Lock body scroll and return unlock function.\n *\n * Ref-counted: nested calls share a single lock. The saved scroll position\n * is captured once (on the outermost call) and restored once (when the\n * outermost unlock runs).\n */\nexport function lockScroll(): () => void {\n  const body = document.body as BodyWithLock\n\n  if (!body[LOCK_KEY]) {\n    body[LOCK_KEY] = {\n      depth: 0,\n      scrollY: window.scrollY,\n      prev: {\n        position: body.style.position,\n        top: body.style.top,\n        width: body.style.width,\n        overflowY: body.style.overflowY,\n      },\n    }\n    body.style.position = 'fixed'\n    body.style.top = `-${body[LOCK_KEY].scrollY}px`\n    body.style.width = '100%'\n    body.style.overflowY = 'scroll'\n  }\n  body[LOCK_KEY].depth += 1\n\n  let released = false\n  return () => {\n    if (released) return\n    released = true\n    const state = body[LOCK_KEY]\n    if (!state) return\n    state.depth -= 1\n    if (state.depth === 0) {\n      body.style.position = state.prev.position\n      body.style.top = state.prev.top\n      body.style.width = state.prev.width\n      body.style.overflowY = state.prev.overflowY\n      window.scrollTo(0, state.scrollY)\n      delete body[LOCK_KEY]\n    }\n  }\n}\n","/**\n * Announce message to screen readers\n */\nexport function announce(message: string, politeness: 'polite' | 'assertive' = 'polite'): void {\n  if (typeof document === 'undefined') return\n\n  const announcer = document.createElement('div')\n\n  announcer.setAttribute('role', 'status')\n  announcer.setAttribute('aria-live', politeness)\n  announcer.setAttribute('aria-atomic', 'true')\n\n  // Visually hidden\n  Object.assign(announcer.style, {\n    position: 'absolute',\n    width: '1px',\n    height: '1px',\n    padding: '0',\n    margin: '-1px',\n    overflow: 'hidden',\n    clip: 'rect(0, 0, 0, 0)',\n    whiteSpace: 'nowrap',\n    border: '0',\n  })\n\n  document.body.appendChild(announcer)\n\n  // Delay for screen reader registration\n  setTimeout(() => {\n    announcer.textContent = message\n  }, 100)\n\n  // Cleanup — `.remove()` is a no-op when the node is already detached, so it\n  // survives the SPA navigation case where `document.body` is replaced between\n  // the announce and the 1s cleanup tick.\n  setTimeout(() => {\n    announcer.remove()\n  }, 1000)\n}\n\n/**\n * Generate unique ID for accessibility\n */\nexport function generateId(prefix = 'tourkit'): string {\n  return `${prefix}-${Math.random().toString(36).substring(2, 11)}`\n}\n\n/**\n * Check if user prefers reduced motion\n */\nexport function prefersReducedMotion(): boolean {\n  if (typeof window === 'undefined') return false\n  return window.matchMedia('(prefers-reduced-motion: reduce)').matches\n}\n\n/**\n * Generate step announcement for screen readers\n */\nexport function getStepAnnouncement(\n  stepTitle: string | undefined,\n  currentStep: number,\n  totalSteps: number\n): string {\n  const stepInfo = `Step ${currentStep} of ${totalSteps}`\n  return stepTitle ? `${stepInfo}: ${stepTitle}` : stepInfo\n}\n","import type { Tour, TourOptions, TourStep } from '../types'\n\nlet tourIdCounter = 0\n\n/**\n * Create a tour with auto-generated ID\n */\nexport function createTour(steps: TourStep[], options?: TourOptions): Tour {\n  return {\n    id: `tour-${++tourIdCounter}`,\n    steps,\n    ...options,\n  }\n}\n\n/**\n * Create a tour with explicit ID\n */\nexport function createNamedTour(id: string, steps: TourStep[], options?: TourOptions): Tour {\n  return {\n    id,\n    steps,\n    ...options,\n  }\n}\n","import type { StepOptions, VisibleTourStep } from '../types'\n\nlet stepIdCounter = 0\n\n/**\n * Create a visible step with auto-generated ID. `target` and `content` are\n * required — hidden steps should be authored as object literals because they\n * don't share this surface.\n */\nexport function createStep(\n  target: VisibleTourStep['target'],\n  content: VisibleTourStep['content'],\n  options?: Partial<StepOptions>\n): VisibleTourStep {\n  return {\n    id: `step-${++stepIdCounter}`,\n    target,\n    content,\n    ...options,\n  }\n}\n\n/**\n * Create a visible step with an explicit ID.\n */\nexport function createNamedStep(\n  id: string,\n  target: VisibleTourStep['target'],\n  content: VisibleTourStep['content'],\n  options?: Partial<StepOptions>\n): VisibleTourStep {\n  return {\n    id,\n    target,\n    content,\n    ...options,\n  }\n}\n","import { type ClassValue, clsx } from 'clsx'\nimport { twMerge } from 'tailwind-merge'\n\n/**\n * Merge class names with Tailwind CSS classes\n * Compatible with shadcn/ui cn() utility\n */\nexport function cn(...inputs: ClassValue[]): string {\n  return twMerge(clsx(inputs))\n}\n","'use client'\n\nimport * as React from 'react'\nimport type { ReactElement, ReactNode } from 'react'\n\nexport type RenderProp = (props: Record<string, unknown>) => ReactElement\n\nexport interface UnifiedSlotProps {\n  children: ReactNode | RenderProp\n  [key: string]: unknown\n}\n\n/**\n * Unified Slot component that works with both Radix UI and Base UI.\n *\n * For Radix UI: clones element with merged props (className concat,\n * style merge, on* handler compose, ref merge).\n * For Base UI: calls `children` as a render prop with the merged props.\n *\n * Wrapped in `React.forwardRef` so the `ref` prop reaches this component\n * on both React 18 (where `ref` is stripped from `props` by createElement)\n * and React 19 (where it's a regular prop).\n */\nexport const UnifiedSlot = React.forwardRef<unknown, UnifiedSlotProps>(function UnifiedSlot(\n  { children, ...props },\n  ref\n) {\n  // Handle render prop pattern (Base UI style)\n  if (typeof children === 'function') {\n    const forwarded = ref ? { ...props, ref } : props\n    return (children as RenderProp)(forwarded)\n  }\n\n  // Clone element with merged props (Radix UI style)\n  if (React.isValidElement(children)) {\n    const childProps = children.props as Record<string, unknown>\n    const childRef = getElementRef(children)\n    const mergedRef = mergeRefs(ref ?? undefined, childRef)\n\n    const mergedProps = mergeProps(props, childProps)\n\n    // Only add ref if we have one to merge\n    if (mergedRef) {\n      mergedProps.ref = mergedRef\n    }\n\n    return React.cloneElement(children, mergedProps as Partial<unknown> & React.Attributes)\n  }\n\n  // Fallback: return empty fragment (should not happen with proper usage)\n  return <>{children}</>\n})\n\nUnifiedSlot.displayName = 'UnifiedSlot'\n\n/**\n * Reads the ref off a ReactElement in a way that works for both React 18 and\n * React 19 *and* avoids the React 19 `element.ref` deprecation warning.\n *\n * - React 18: `ref` lives on `element.ref`; `element.props.ref` is a warning getter.\n * - React 19: `ref` lives on `element.props.ref`; `element.ref` is a warning getter.\n *\n * The runtime decides which side is the warning getter via `isReactWarning`,\n * mirroring the canonical pattern in `@radix-ui/react-slot`.\n */\nfunction getElementRef(element: React.ReactElement): React.Ref<unknown> | undefined {\n  const elementWithRef = element as unknown as { ref?: React.Ref<unknown> }\n  const elementProps = (element.props ?? {}) as { ref?: React.Ref<unknown> }\n\n  const propsGetter = Object.getOwnPropertyDescriptor(elementProps, 'ref')?.get as\n    | (((this: unknown) => unknown) & { isReactWarning?: boolean })\n    | undefined\n  if (propsGetter?.isReactWarning) return elementWithRef.ref\n\n  const elementGetter = Object.getOwnPropertyDescriptor(element, 'ref')?.get as\n    | (((this: unknown) => unknown) & { isReactWarning?: boolean })\n    | undefined\n  if (elementGetter?.isReactWarning) return elementProps.ref\n\n  return elementProps.ref ?? elementWithRef.ref\n}\n\n/**\n * Merges multiple refs into a single ref callback\n */\nfunction mergeRefs<T>(...refs: Array<React.Ref<T> | undefined>): React.RefCallback<T> | null {\n  const validRefs = refs.filter((r): r is React.Ref<T> => r != null)\n  if (validRefs.length === 0) return null\n  return (value: T) => {\n    for (const ref of validRefs) {\n      if (typeof ref === 'function') {\n        ref(value)\n      } else if (ref != null) {\n        ;(ref as React.RefObject<T | null>).current = value\n      }\n    }\n  }\n}\n\nfunction mergeProps(\n  slotProps: Record<string, unknown>,\n  childProps: Record<string, unknown>\n): Record<string, unknown> {\n  // Child props override slot props by default, except for className (concat),\n  // style (merge), and on* handlers (compose) — matches @radix-ui/react-slot.\n  const overrideProps: Record<string, unknown> = { ...childProps }\n\n  for (const propName in childProps) {\n    const slotValue = slotProps[propName]\n    const childValue = childProps[propName]\n    const isHandler = /^on[A-Z]/.test(propName)\n\n    if (isHandler) {\n      if (typeof slotValue === 'function' && typeof childValue === 'function') {\n        overrideProps[propName] = (...args: unknown[]) => {\n          ;(childValue as (...a: unknown[]) => unknown)(...args)\n          ;(slotValue as (...a: unknown[]) => unknown)(...args)\n        }\n      } else if (typeof slotValue === 'function') {\n        overrideProps[propName] = slotValue\n      }\n    } else if (propName === 'style') {\n      overrideProps[propName] = {\n        ...(slotValue as React.CSSProperties | undefined),\n        ...(childValue as React.CSSProperties | undefined),\n      }\n    } else if (propName === 'className') {\n      overrideProps[propName] = [slotValue, childValue].filter(Boolean).join(' ')\n    }\n  }\n\n  return { ...slotProps, ...overrideProps }\n}\n","'use client'\n\nimport { createContext, useContext } from 'react'\n\nexport type UILibrary = 'radix-ui' | 'base-ui'\n\nconst UILibraryContext = createContext<UILibrary>('radix-ui')\n\nexport interface UILibraryProviderProps {\n  library?: UILibrary\n  children: React.ReactNode\n}\n\n/**\n * Provider component that allows users to choose their preferred UI library.\n * Defaults to 'radix-ui' for backward compatibility.\n *\n * @example\n * ```tsx\n * <UILibraryProvider library=\"base-ui\">\n *   <App />\n * </UILibraryProvider>\n * ```\n */\nexport function UILibraryProvider({ library = 'radix-ui', children }: UILibraryProviderProps) {\n  return <UILibraryContext.Provider value={library}>{children}</UILibraryContext.Provider>\n}\n\n/**\n * Hook to get the current UI library setting\n *\n * @returns The current UI library ('radix-ui' or 'base-ui')\n */\nexport function useUILibrary(): UILibrary {\n  return useContext(UILibraryContext)\n}\n","const TEMPLATE_RE = /\\{\\{\\s*([^}|]+?)\\s*(?:\\|\\s*([^}]*?))?\\s*\\}\\}/g\n\nexport interface InterpolateOptions {\n  /** Returned when a key is missing AND no inline fallback was given. Default: '' */\n  defaultFallback?: string\n  /** Logs unresolved keys to console.warn in dev. Default: true */\n  warnOnMissing?: boolean\n}\n\nexport function interpolate(\n  template: string,\n  vars: Record<string, unknown> | undefined,\n  opts: InterpolateOptions = {}\n): string {\n  if (!template.includes('{{')) return template\n  const { defaultFallback = '', warnOnMissing = process.env.NODE_ENV !== 'production' } = opts\n  return template.replace(TEMPLATE_RE, (_match, rawKey: string, rawFallback?: string) => {\n    const key = rawKey.trim()\n    const value = getNestedValue(vars, key)\n    if (value !== undefined && value !== null) return String(value)\n    if (rawFallback !== undefined) return rawFallback.trim()\n    if (warnOnMissing) console.warn(`[tour-kit] interpolate: missing key \"${key}\"`)\n    return defaultFallback\n  })\n}\n\nfunction getNestedValue(obj: unknown, path: string): unknown {\n  if (!obj || typeof obj !== 'object') return undefined\n  return path.split('.').reduce<unknown>((acc, k) => {\n    if (acc && typeof acc === 'object' && k in acc) return (acc as Record<string, unknown>)[k]\n    return undefined\n  }, obj)\n}\n","'use client'\nimport { type ReactNode, createContext, useContext, useMemo } from 'react'\nimport type { Messages, TranslateFn } from './use-t'\n\nexport interface LocaleContextValue {\n  locale: string\n  messages: Messages\n  /** Optional consumer-side override — delegates t() to host app's i18n */\n  t?: TranslateFn\n  /** Auto-derived from locale; consumers can override */\n  direction?: 'ltr' | 'rtl'\n}\n\nconst LocaleContext = createContext<LocaleContextValue>({ locale: 'en', messages: {} })\n\nexport interface LocaleProviderProps extends Partial<LocaleContextValue> {\n  children: ReactNode\n}\n\nexport function LocaleProvider({\n  locale = 'en',\n  messages = {},\n  t,\n  direction,\n  children,\n}: LocaleProviderProps) {\n  const value = useMemo(\n    () => ({ locale, messages, t, direction: direction ?? deriveDir(locale) }),\n    [locale, messages, t, direction]\n  )\n  return <LocaleContext.Provider value={value}>{children}</LocaleContext.Provider>\n}\n\nexport function useLocale(): LocaleContextValue {\n  return useContext(LocaleContext)\n}\n\nconst RTL = new Set(['ar', 'he', 'fa', 'ur'])\nfunction deriveDir(locale: string): 'ltr' | 'rtl' {\n  return RTL.has(locale.split('-')[0]) ? 'rtl' : 'ltr'\n}\n","/**\n * ICU subset plural resolver. Recognizes:\n *\n *   {<varName>, plural, =N {literal} one {…} few {…} many {…} other {…}}\n *\n * Backed by `Intl.PluralRules` (validation log: 95.67% global support).\n * `=N` exact matches take precedence over plural categories. `#` inside the\n * chosen branch is replaced with the stringified count value (ICU convention).\n *\n * Falls through to the original template when the count is not a number, no\n * branch matches, or the block is malformed — leaving `interpolate` to handle it.\n */\n\nconst pluralRulesCache = new Map<string, Intl.PluralRules>()\n\nfunction getPluralRules(locale: string): Intl.PluralRules {\n  let rules = pluralRulesCache.get(locale)\n  if (!rules) {\n    try {\n      rules = new Intl.PluralRules(locale)\n    } catch {\n      rules = new Intl.PluralRules('en')\n    }\n    pluralRulesCache.set(locale, rules)\n  }\n  return rules\n}\n\n// biome-ignore lint/complexity/noExcessiveCognitiveComplexity: ICU subset scanner — brace-depth state machine + plural category lookup\nexport function resolvePlural(\n  template: string,\n  locale: string,\n  vars: Record<string, unknown> | undefined\n): string {\n  // Cheap reject — most templates have no plural marker\n  if (!template.includes(', plural,')) return template\n\n  let result = ''\n  let i = 0\n  while (i < template.length) {\n    const ch = template[i]\n    if (ch !== '{') {\n      result += ch\n      i++\n      continue\n    }\n\n    // Find matching close brace via depth counting (handles nested {{var}} tokens)\n    const blockStart = i\n    let depth = 1\n    let j = i + 1\n    while (j < template.length && depth > 0) {\n      const c = template[j]\n      if (c === '{') depth++\n      else if (c === '}') depth--\n      j++\n    }\n\n    if (depth !== 0) {\n      // Unmatched brace — bail and emit the rest verbatim for downstream handling\n      result += template.slice(blockStart)\n      break\n    }\n\n    const blockEnd = j\n    const blockBody = template.slice(blockStart + 1, blockEnd - 1)\n\n    // Match `<varName>, plural, <body>` — anything else is a passthrough\n    const headerMatch = /^\\s*([^\\s,{}]+)\\s*,\\s*plural\\s*,\\s*([\\s\\S]*)$/.exec(blockBody)\n    if (!headerMatch) {\n      // Not a plural block — emit original including outer braces\n      result += template.slice(blockStart, blockEnd)\n      i = blockEnd\n      continue\n    }\n\n    const varName = headerMatch[1] ?? ''\n    const body = headerMatch[2] ?? ''\n    const rawCount = vars?.[varName]\n    const count = typeof rawCount === 'number' ? rawCount : Number(rawCount)\n\n    if (typeof rawCount !== 'number' && !Number.isFinite(count)) {\n      // Not numeric — fall back to \"other\" or emit original\n      const otherBranch = findPluralBranch(body, 'other')\n      result += otherBranch ?? template.slice(blockStart, blockEnd)\n      i = blockEnd\n      continue\n    }\n\n    // Try `=N` exact match first\n    const exactBranch = findPluralBranch(body, `=${count}`)\n    if (exactBranch !== null) {\n      result += exactBranch.replace(/#/g, String(count))\n      i = blockEnd\n      continue\n    }\n\n    // Try plural category from Intl.PluralRules\n    const category = getPluralRules(locale).select(count)\n    const catBranch = findPluralBranch(body, category)\n    if (catBranch !== null) {\n      result += catBranch.replace(/#/g, String(count))\n      i = blockEnd\n      continue\n    }\n\n    // Final fallback — `other`\n    const otherBranch = findPluralBranch(body, 'other')\n    if (otherBranch !== null) {\n      result += otherBranch.replace(/#/g, String(count))\n      i = blockEnd\n      continue\n    }\n\n    // Nothing matched — emit original block unchanged\n    result += template.slice(blockStart, blockEnd)\n    i = blockEnd\n  }\n\n  return result\n}\n\n/**\n * Walks a plural body looking for `<category> {<text>}` and returns the matching\n * branch text. Brace depth is tracked so nested `{{var}}` interpolation tokens\n * inside a branch don't terminate the search prematurely.\n */\n// biome-ignore lint/complexity/noExcessiveCognitiveComplexity: brace-depth scanner with state machine\nfunction findPluralBranch(body: string, category: string): string | null {\n  let i = 0\n  while (i < body.length) {\n    while (i < body.length && /\\s/.test(body[i] ?? '')) i++\n    if (i >= body.length) break\n\n    const nameStart = i\n    while (i < body.length && body[i] !== '{' && !/\\s/.test(body[i] ?? '')) i++\n    const name = body.slice(nameStart, i)\n    if (!name) break\n\n    while (i < body.length && /\\s/.test(body[i] ?? '')) i++\n    if (body[i] !== '{') return null\n\n    let depth = 1\n    let j = i + 1\n    while (j < body.length && depth > 0) {\n      const c = body[j]\n      if (c === '{') depth++\n      else if (c === '}') depth--\n      j++\n    }\n    if (depth !== 0) return null\n\n    const text = body.slice(i + 1, j - 1)\n    if (name === category) return text\n    i = j\n  }\n  return null\n}\n","import { useCallback } from 'react'\nimport { interpolate } from '../interpolate'\nimport { useLocale } from './locale-context'\nimport { resolvePlural } from './plural'\n\nexport type Messages = Record<string, string>\nexport type TranslateFn = (key: string, vars?: Record<string, unknown>) => string\n\n/**\n * Hook returning a translator function `t(key, vars?)` that:\n *\n *   1. Delegates to `LocaleContextValue.t` when a consumer adapter is supplied\n *      (host i18n libraries like next-intl take precedence over the built-in path).\n *   2. Looks up `messages[key]`. Falls back to the key itself in dev (visible\n *      breadcrumb) and to an empty string in production.\n *   3. Resolves any `{count, plural, …}` block via `Intl.PluralRules`.\n *   4. Substitutes `{{var}}` tokens via `interpolate`.\n */\nexport function useT(): TranslateFn {\n  const { locale, messages, t: adapter } = useLocale()\n  return useCallback<TranslateFn>(\n    (key, vars) => {\n      if (adapter) return adapter(key, vars)\n      const template = messages[key]\n      if (template === undefined) {\n        return process.env.NODE_ENV !== 'production' ? key : ''\n      }\n      const resolved = resolvePlural(template, locale, vars)\n      return interpolate(resolved, vars, { warnOnMissing: false })\n    },\n    [adapter, locale, messages]\n  )\n}\n","import { useContext } from 'react'\nimport { TourContext } from '../context/tour-context'\nimport type { EligibilityReport } from '../types/diagnostic'\n\n/**\n * Read the diagnostic report for a given tour id. Returns `null` when the\n * provider is mounted without `diagnose={true}`, when the tour is unknown,\n * or before the first diagnostic effect tick has resolved.\n *\n * Throws if called outside a `<TourProvider>` — the diagnostic surface is\n * useless without context plumbing, so make the misuse loud.\n */\nexport function useTourDiagnostic(tourId: string): EligibilityReport | null {\n  const ctx = useContext(TourContext)\n  if (!ctx) {\n    throw new Error('useTourDiagnostic must be used inside <TourProvider>')\n  }\n  return ctx.diagnostics?.[tourId] ?? null\n}\n","/**\n * Frequency rules — promoted from `@tour-kit/announcements` in Phase 3a of the\n * UserGuiding parity initiative. Re-exported from `@tour-kit/announcements`\n * with `@deprecated` JSDoc for backward compat.\n */\n\n/**\n * How often a UI surface (announcement, hint, tour) can be shown.\n *\n *   - `'once'`     — show only when never viewed\n *   - `'session'`  — show until dismissed in the current session\n *   - `'always'`   — show every time conditions are met\n *   - `{ type: 'times', count }`     — show up to `count` times total\n *   - `{ type: 'interval', days }`   — re-show after `days` days have passed\n */\nexport type FrequencyRule =\n  | 'once'\n  | 'session'\n  | 'always'\n  | { type: 'times'; count: number }\n  | { type: 'interval'; days: number }\n\n/**\n * Minimal state shape needed by the frequency helpers. Both\n * `AnnouncementState` (announcements) and the per-hint frequency slice\n * satisfy this — keep this interface narrow so new consumers (tours, etc.)\n * do not have to invent new state fields.\n */\nexport interface FrequencyState {\n  viewCount: number\n  isDismissed: boolean\n  lastViewedAt: Date | null\n}\n\n/**\n * Decide whether a surface can be shown right now given its persisted state\n * and the configured rule. `undefined` rule defaults to \"always show\".\n */\nexport function canShowByFrequency(\n  state: FrequencyState,\n  rule: FrequencyRule | undefined\n): boolean {\n  if (!rule) {\n    return true\n  }\n\n  if (typeof rule === 'string') {\n    switch (rule) {\n      case 'once':\n        return state.viewCount === 0\n      case 'session':\n      case 'always':\n        return !state.isDismissed\n      default:\n        return true\n    }\n  }\n\n  switch (rule.type) {\n    case 'times':\n      return state.viewCount < rule.count\n    case 'interval': {\n      if (state.viewCount === 0) return true\n      if (!state.lastViewedAt) return true\n      const days = daysBetween(state.lastViewedAt, new Date())\n      return days >= rule.days\n    }\n    default:\n      return true\n  }\n}\n\n/**\n * Whether dismissal is permanent for the rule. `'once'` and `'session'`\n * suppress further shows after dismissal; `'always'` and the object rules\n * permit re-showing.\n */\nexport function canShowAfterDismissal(rule: FrequencyRule | undefined): boolean {\n  if (!rule) return true\n  if (typeof rule === 'string') {\n    return rule !== 'once' && rule !== 'session'\n  }\n  return true\n}\n\n/**\n * Hard cap on lifetime views for the rule. `'once'` → 1; everything else is\n * effectively unbounded except `{ type: 'times', count }` which returns `count`.\n */\nexport function getViewLimit(rule: FrequencyRule | undefined): number {\n  if (!rule) return Number.POSITIVE_INFINITY\n  if (typeof rule === 'string') {\n    return rule === 'once' ? 1 : Number.POSITIVE_INFINITY\n  }\n  if (rule.type === 'times') return rule.count\n  return Number.POSITIVE_INFINITY\n}\n\nfunction daysBetween(a: Date, b: Date): number {\n  const msPerDay = 24 * 60 * 60 * 1000\n  return Math.floor(Math.abs(b.getTime() - a.getTime()) / msPerDay)\n}\n","/**\n * `LocalizedText` is the shared shape for any human-readable string that\n * may either be a literal (interpolated via `interpolate`) or a dictionary\n * key (resolved via `useT()`). The discriminated union narrows on\n * `typeof === 'string'`, so existing string-based consumers stay assignable\n * — adding the object branch is a pure widening.\n */\nexport type LocalizedText = string | { key: string }\n\n/**\n * Type guard: true when `value` is the `{ key: string }` branch of\n * `LocalizedText`. Returns false for plain strings, `undefined`, `null`,\n * arrays, primitives, and objects without a `key` property.\n */\nexport function isI18nKey(value: unknown): value is { key: string } {\n  return (\n    typeof value === 'object' &&\n    value !== null &&\n    !Array.isArray(value) &&\n    'key' in value &&\n    typeof (value as { key: unknown }).key === 'string'\n  )\n}\n","'use client'\nimport { createContext, useContext, useMemo } from 'react'\nimport type { SegmentationContextValue, SegmentationProviderProps } from './types'\n\nconst Ctx = createContext<SegmentationContextValue>({ segments: {} })\n\nexport function SegmentationProvider({\n  children,\n  segments,\n  userContext,\n  currentUserId,\n}: SegmentationProviderProps) {\n  // Destructure props at the parameter level so the memo closure captures\n  // exactly what the deps list declares — equivalent to the plan's\n  // `[value.segments, value.userContext, value.currentUserId]` (big plan\n  // line 341), but lints cleanly under useExhaustiveDependencies.\n  const memo = useMemo<SegmentationContextValue>(\n    () => ({ segments, userContext, currentUserId }),\n    [segments, userContext, currentUserId]\n  )\n  return <Ctx.Provider value={memo}>{children}</Ctx.Provider>\n}\n\nexport function useSegmentationContext() {\n  return useContext(Ctx)\n}\n","import { useCallback } from 'react'\nimport { interpolate } from '../interpolate'\nimport { type LocalizedText, isI18nKey } from '../localized-text'\nimport { useSegmentationContext } from '../segmentation/segmentation-context'\nimport { useT } from './use-t'\n\n/**\n * Returns a memoized resolver `(value) => string` that takes a `LocalizedText`\n * (or `undefined`) and returns the rendered string. Intended for any component\n * that surfaces consumer-authored copy where the output must be a `string`\n * (e.g. `aria-label`, `title` attributes, `Dialog.Title` props).\n *\n *   const resolveText = useResolveLocalizedText()\n *   const title = resolveText(task.config.title)\n *\n * For `ReactNode` pass-through use `useResolvedText` (per-package hook in\n * `@tour-kit/react` / `@tour-kit/hints`) — it returns `ReactNode` so consumers\n * can pass JSX through arbitrary `LocalizedText | ReactNode` fields.\n *\n * **Vars source:** `useSegmentationContext().userContext`. Consumers who pass\n * `userContext` to `<SegmentationProvider>` for audience targeting get\n * automatic interpolation against the same data with no extra plumbing.\n *\n * **Without any provider:** the default segmentation context has\n * `userContext: undefined`, so plain templates fall back to `{{x | default}}`\n * rules and keyed values resolve to the key itself in dev / empty in prod —\n * the same contract as `useT()`.\n */\nexport function useResolveLocalizedText(): (value: LocalizedText | undefined) => string {\n  const t = useT()\n  const { userContext } = useSegmentationContext()\n  return useCallback(\n    (value) => {\n      if (value === undefined || value === null) return ''\n      if (typeof value === 'string') {\n        return interpolate(value, userContext, { warnOnMissing: false })\n      }\n      if (isI18nKey(value)) return t(value.key, userContext)\n      return ''\n    },\n    [t, userContext]\n  )\n}\n","'use client'\n\nimport type * as React from 'react'\nimport { interpolate } from '../interpolate'\nimport { type LocalizedText, isI18nKey } from '../localized-text'\nimport { useSegmentationContext } from '../segmentation/segmentation-context'\nimport { useT } from './use-t'\n\n/**\n * Resolve a `LocalizedText | ReactNode` value into a `ReactNode`. Drives the\n * Phase 3a unified text pipeline (promoted to core in Phase 1 of the refactor\n * train — previously duplicated in `@tour-kit/react`, `@tour-kit/hints`, and\n * `@tour-kit/announcements`).\n *\n *   - `string` → `interpolate(value, vars)` (templated literal)\n *   - `{ key }` → `useT()(value.key, vars)` (i18n dictionary)\n *   - any other `ReactNode` → returned as-is\n *\n * `vars` defaults to `useSegmentationContext().userContext` so consumers\n * authoring `'Hi {{user.name}}'` get interpolation against the same context\n * driving audience targeting.\n *\n * **Hook, not function** — `useT()` requires React render context. Call from\n * a component body, never from an event handler or `.map()` callback.\n *\n * For string-only outputs (aria-label, title, Dialog.Title) use\n * `useResolveLocalizedText` instead — it returns `string` and skips the\n * ReactNode pass-through branch.\n */\nexport function useResolvedText(\n  value: React.ReactNode | LocalizedText | undefined,\n  vars?: Record<string, unknown>\n): React.ReactNode {\n  const t = useT()\n  const { userContext } = useSegmentationContext()\n  const effectiveVars = vars ?? userContext\n\n  if (value === undefined || value === null) return value\n  if (typeof value === 'string') return interpolate(value, effectiveVars)\n  if (isI18nKey(value)) return t(value.key, effectiveVars)\n  return value as React.ReactNode\n}\n","import * as React from 'react'\nimport type { UseTourActionsReturn } from '../types/registry'\nimport { tourRegistry } from './tour-registry'\n\n/**\n * Module-level frozen no-op. Allocated once and reused across every unknown-id\n * call so consumers can safely write `useTourActions(id).start()` during a\n * route transition (before the tour has mounted) without dancing around an\n * `undefined` return.\n *\n * Frozen so any consumer that tries to mutate it (e.g., assigning a callback\n * to `result.start = ...`) gets a clear strict-mode error instead of silently\n * leaking patched no-ops across renders.\n */\nconst FROZEN_NOOP: UseTourActionsReturn = Object.freeze({\n  isActive: false,\n  currentStepId: null,\n  progress: 0,\n  start: () => {\n    /* no-op: tour is not registered */\n  },\n  stop: () => {\n    /* no-op: tour is not registered */\n  },\n  restart: () => {\n    /* no-op: tour is not registered */\n  },\n  next: () => {\n    /* no-op: tour is not registered */\n  },\n  prev: () => {\n    /* no-op: tour is not registered */\n  },\n  goToStep: () => {\n    /* no-op: tour is not registered */\n  },\n})\n\n/**\n * `useSyncExternalStore`'s SSR-safe `getServerSnapshot`. The registry is a\n * module-level singleton populated by client-side effects, so during SSR\n * there's nothing to read — return `null` and let consumers fall through to\n * the frozen no-op.\n */\nfunction getServerSnapshot(): null {\n  return null\n}\n\n/**\n * Read tour state and call imperative actions from anywhere in the React tree,\n * including siblings of the owning `<TourProvider>` or `<Tour>` component.\n *\n * Standalone `<Tour id=\"welcome\">` self-registers at mount, and any sibling\n * can call `useTourActions('welcome').start()` to drive it. When the tour id\n * is unknown (typo, route transition, future mount), the hook returns a\n * frozen no-op object — calls silently drop rather than throw, so callers\n * don't need to wrap every action in optional chaining.\n *\n * @param tourId - Tour id matching a `<Tour id>` / `<TourProvider tours>` entry\n */\nexport function useTourActions(tourId: string): UseTourActionsReturn {\n  // getSnapshot must return a value whose identity changes when the data\n  // changes. The registry replaces `entry.state` wholesale on each transition,\n  // so reading `entry?.state` produces a fresh reference each time the state\n  // mirror is updated. Returning `entry` itself would keep the same identity\n  // across state changes (only the inner `state` field churns), and\n  // useSyncExternalStore would never observe an update via Object.is.\n  const getSnapshot = React.useCallback(() => tourRegistry.get(tourId)?.state ?? null, [tourId])\n  const state = React.useSyncExternalStore(tourRegistry.subscribe, getSnapshot, getServerSnapshot)\n\n  if (!state) return FROZEN_NOOP\n\n  // Post-state-read: re-resolve the entry for its action handles. The entry\n  // is the same object whose state we just read, so a follow-up `get(id)`\n  // returns null only if the tour unregistered between getSnapshot and here\n  // — an unobservable interleaving with the React render commit. Treat that\n  // case the same as \"unknown id\".\n  const entry = tourRegistry.get(tourId)\n  if (!entry) return FROZEN_NOOP\n\n  return {\n    isActive: state.isActive,\n    currentStepId: state.currentStepId,\n    progress: state.progress,\n    start: entry.actions.start,\n    stop: entry.actions.stop,\n    restart: entry.actions.restart,\n    next: entry.actions.next,\n    prev: entry.actions.prev,\n    goToStep: entry.actions.goToStep,\n  }\n}\n","import { useMemo } from 'react'\nimport { logger } from '../../utils/logger'\nimport { matchesAudience } from '../audience'\nimport { useSegmentationContext } from './segmentation-context'\nimport type { SegmentSource } from './types'\n\n/**\n * Pure evaluation of a single registered segment. Shared by `useSegment`\n * and `useSegments` so the static-vs-audience branch stays in lockstep —\n * drift between the two would silently let `useSegment('x')` and\n * `useSegments().x` disagree.\n */\nfunction evaluateSegment(\n  seg: SegmentSource,\n  userContext: Record<string, unknown> | undefined,\n  currentUserId: string | undefined\n): boolean {\n  // Array.isArray narrows SegmentDefinition (array) vs StaticSegment (object).\n  if (!Array.isArray(seg)) {\n    return currentUserId !== undefined && seg.userIds.includes(currentUserId)\n  }\n  return matchesAudience(seg, userContext)\n}\n\n/**\n * Resolve a named segment to a boolean for the current user.\n *\n * Composition rules:\n * - Inside one segment, conditions are AND-joined by `matchesAudience`.\n * - To express OR, register two named segments and reference both at the\n *   call site, OR use an audience operator that supports OR semantics\n *   (e.g. `operator: 'in'` against an array of values).\n *\n * Returns `false` (with a dev-only `console.warn`) for unknown names — never\n * throws — so a typo cannot crash the consumer tree. Static segments without\n * a `currentUserId` resolve to `false` (anonymous users by definition cannot\n * be in a closed cohort). An empty conditions array (`[]`) resolves to `true`\n * because `matchesAudience` treats \"no conditions\" as \"match everyone\".\n *\n * @example\n *   <SegmentationProvider\n *     segments={{\n *       admins: [{ type: 'user_property', key: 'role', operator: 'equals', value: 'admin' }],\n *       beta:   { type: 'static', userIds: ['u_1', 'u_2'] },\n *     }}\n *     userContext={{ role: 'admin' }}\n *     currentUserId=\"u_2\"\n *   >\n *     <App />\n *   </SegmentationProvider>\n *\n *   useSegment('admins') // → true\n *   useSegment('beta')   // → true\n *   useSegment('ghost')  // → false + dev warn\n */\nexport function useSegment(name: string): boolean {\n  const { segments, userContext, currentUserId } = useSegmentationContext()\n  return useMemo(() => {\n    const seg = segments[name]\n    if (!seg) {\n      if (process.env.NODE_ENV !== 'production') {\n        logger.warn(`useSegment: unknown segment \"${name}\"`)\n      }\n      return false\n    }\n    return evaluateSegment(seg, userContext, currentUserId)\n  }, [name, segments, userContext, currentUserId])\n}\n\n/**\n * Batch lookup: returns a `Record<string, boolean>` keyed by every registered\n * segment name. Useful for debug overlays and analytics dispatch.\n *\n * Does NOT warn on unknown names — enumeration intentionally walks the\n * registered set, so by definition every key is known.\n */\nexport function useSegments(): Record<string, boolean> {\n  const { segments, userContext, currentUserId } = useSegmentationContext()\n  return useMemo(() => {\n    const out: Record<string, boolean> = {}\n    for (const name of Object.keys(segments)) {\n      out[name] = evaluateSegment(segments[name], userContext, currentUserId)\n    }\n    return out\n  }, [segments, userContext, currentUserId])\n}\n","/**\n * Parse a CSV string into a deduped array of trimmed user IDs.\n *\n * Spec (RFC 4180-lite — no nested CSV, no multi-line quoted fields):\n * - Strips a leading BOM (`﻿`).\n * - Splits on `\\r\\n` or `\\n`. Empty lines are skipped (including a trailing one).\n * - Header detection: case-insensitive match on `id` / `user_id` / `userId`\n *   in the first column → drops that row. Otherwise treats the first row as data.\n * - Quote-aware first-column parser: `\"u,1\"` preserves the comma; doubled\n *   quotes `\"\"` decode to a literal `\"`.\n * - Multi-column rows: only the first column is taken.\n * - Result is trimmed and deduplicated, preserving first-seen order.\n *\n * Hand-rolled to keep `@tour-kit/core` under its bundle budget — adding\n * `papaparse` or `csv-parse` would bust the brotli-with-deps cap (24 KB\n * after Phase 2; measured 23.13 KB).\n *\n * @example\n *   parseUserIdsFromCsv('id\\nu_1\\nu_2')             // → ['u_1', 'u_2']\n *   parseUserIdsFromCsv('id\\n\"u,1\"\\nu_2')           // → ['u,1', 'u_2']\n *   parseUserIdsFromCsv('id,email\\nu_1,a@b.com')    // → ['u_1']\n */\nexport function parseUserIdsFromCsv(csv: string): string[] {\n  if (!csv) return []\n\n  const src = csv.charCodeAt(0) === 0xfeff ? csv.slice(1) : csv\n  const lines = src.split(/\\r\\n|\\n/).filter((line) => line.length > 0)\n  if (lines.length === 0) return []\n\n  const startIdx = HEADER_RE.test(firstColumn(lines[0])) ? 1 : 0\n\n  const seen = new Set<string>()\n  const out: string[] = []\n  for (let i = startIdx; i < lines.length; i++) {\n    const value = firstColumn(lines[i])\n    if (value && !seen.has(value)) {\n      seen.add(value)\n      out.push(value)\n    }\n  }\n  return out\n}\n\nconst HEADER_RE = /^(id|user_?id)$/i\n\nfunction firstColumn(line: string): string {\n  if (line[0] === '\"') {\n    let out = ''\n    let i = 1\n    while (i < line.length) {\n      const ch = line[i]\n      if (ch === '\"' && line[i + 1] === '\"') {\n        out += '\"'\n        i += 2\n        continue\n      }\n      if (ch === '\"') break\n      out += ch\n      i++\n    }\n    return out.trim()\n  }\n  let out = ''\n  let i = 0\n  while (i < line.length && line[i] !== ',') {\n    out += line[i]\n    i++\n  }\n  return out.trim()\n}\n"]}