@weavix/sdk-react 0.0.13 → 0.0.15

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- {"version":3,"file":"index.mjs","names":[],"sources":["../src/components/ErrorBoundary.tsx","../src/components/PluginError.tsx","../src/components/PluginLoader.tsx","../src/hooks/useContext.ts","../src/hooks/useIsYateam.ts","../src/hooks/useLanguage.ts","../src/hooks/useTheme.ts","../src/hooks/useUserId.ts","../src/components/PluginProvider.tsx","../src/hooks/useConfirm.ts","../src/hooks/useLocalizedString.ts","../src/hooks/useToaster.ts"],"sourcesContent":["import { Component, ReactNode } from 'react';\n\ninterface ErrorBoundaryProps {\n children: ReactNode;\n fallback: (error: Error) => ReactNode;\n}\n\ninterface ErrorBoundaryState {\n hasError: boolean;\n error: Error | null;\n}\n\nexport class ErrorBoundary extends Component<ErrorBoundaryProps, ErrorBoundaryState> {\n static getDerivedStateFromError(error: Error): ErrorBoundaryState {\n return { hasError: true, error };\n }\n\n constructor(props: ErrorBoundaryProps) {\n super(props);\n this.state = { hasError: false, error: null };\n }\n\n componentDidCatch(error: Error, errorInfo: React.ErrorInfo) {\n console.error('ErrorBoundary caught an error:', error, errorInfo);\n }\n\n render() {\n if (this.state.hasError && this.state.error) {\n return this.props.fallback(this.state.error);\n }\n\n return this.props.children;\n }\n}\n","import type { FC } from 'react';\nimport './PluginError.scss';\n\nexport interface PluginErrorProps {\n error: Error;\n}\n\nconst PluginErrorImpl = ({ error }: PluginErrorProps) => (\n <div className=\"plugin-error\">\n <div className=\"plugin-error__container\">\n <div className=\"plugin-error__header\">\n <svg\n className=\"plugin-error__icon\"\n width=\"24\"\n height=\"24\"\n viewBox=\"0 0 24 24\"\n fill=\"none\"\n >\n <circle cx=\"12\" cy=\"12\" r=\"10\" fill=\"#f44336\" />\n <path\n d=\"M12 7v6m0 4h.01\"\n stroke=\"white\"\n strokeWidth=\"2\"\n strokeLinecap=\"round\"\n />\n </svg>\n <h3 className=\"plugin-error__title\">Ошибка инициализации плагина</h3>\n </div>\n <div className=\"plugin-error__message\">\n Не удалось инициализировать плагин. Проверьте параметры запуска и попробуйте\n перезагрузить страницу.\n </div>\n <details className=\"plugin-error__details\">\n <summary className=\"plugin-error__summary\">Детали ошибки</summary>\n <pre className=\"plugin-error__stack\">\n {error.message}\n {error.stack && `\\n\\n${error.stack}`}\n </pre>\n </details>\n </div>\n </div>\n);\n\n/**\n * Дефолтный компонент для отображения ошибки инициализации плагина\n */\nexport const PluginError = PluginErrorImpl as FC<PluginErrorProps>;\n","import type { FC } from 'react';\nimport './PluginLoader.scss';\n\nconst PluginLoaderImpl = () => (\n <div className=\"plugin-loader\">\n <div className=\"plugin-loader__content\">\n <div className=\"plugin-loader__spinner\" />\n <div className=\"plugin-loader__text\">Загрузка плагина...</div>\n </div>\n </div>\n);\n\n/**\n * Простой лоадер для отображения во время инициализации плагина\n */\nexport const PluginLoader = PluginLoaderImpl as FC;\n","import { on } from '@weavix/sdk-core';\nimport { useEffect, useState } from 'react';\n\n/**\n * Reactive hook for receiving the current slot context pushed by the host.\n * @template T - Type of the context object (defaults to `unknown`)\n * @returns Current context, or `undefined` until the first event arrives from the host.\n * @example\n * ```tsx\n * interface IssueContext {\n * key: string;\n * summary: string;\n * }\n *\n * function App() {\n * const context = useContext<IssueContext>();\n * if (!context) return <Loader />;\n * return <div>{context.summary}</div>;\n * }\n * ```\n */\nexport function useContext<T = unknown>(): T | undefined {\n const [context, setContext] = useState<T | undefined>(() => {\n let initial: T | undefined;\n const unsubscribe = on('context.changed', (value) => {\n initial = value as T;\n });\n unsubscribe();\n return initial;\n });\n\n useEffect(() => {\n const unsubscribe = on('context.changed', (value) => {\n setContext(value as T);\n });\n\n return unsubscribe;\n }, []);\n\n return context;\n}\n","import { hostApi } from '@weavix/sdk-core';\nimport { useEffect, useState } from 'react';\n\n/**\n * Реактивный хук для получения текущей сборки приложения.\n * @returns Является ли ятимом приложение (например, 'true'), или `undefined` до получения первого события.\n * @example\n * ```tsx\n * function App() {\n * const isYateam = useIsYateam();\n * return <span>Ятим ли сейчас?: {isYateam}</span>;\n * }\n * ```\n */\nexport function useIsYateam(): boolean | undefined {\n const [isYateam, setIsYateam] = useState<boolean | undefined>(undefined);\n\n useEffect(() => {\n const init = async () => {\n const yateam = (await hostApi.getIsYateam()) as boolean | undefined;\n setIsYateam(yateam);\n };\n\n init();\n }, []);\n\n return isYateam;\n}\n","import { on } from '@weavix/sdk-core';\nimport { useEffect, useState } from 'react';\n\n/**\n * Реактивный хук для получения текущего языка хоста.\n * @returns Код текущего языка (например, `'ru'`, `'en'`), или `undefined` до получения первого события.\n * @example\n * ```tsx\n * function App() {\n * const language = useLanguage();\n * return <span>Текущий язык: {language}</span>;\n * }\n * ```\n */\nexport function useLanguage(): string | undefined {\n const [language, setLanguage] = useState<string | undefined>(() => {\n let initial: string | undefined;\n const unsubscribe = on('language.changed', (value) => {\n initial = value;\n });\n unsubscribe();\n return initial;\n });\n\n useEffect(() => {\n const unsubscribe = on('language.changed', (value) => {\n setLanguage(value);\n });\n\n return unsubscribe;\n }, []);\n\n return language;\n}\n","import { type Theme, on } from '@weavix/sdk-core';\nimport { useEffect, useState } from 'react';\n\n/**\n * Реактивный хук для получения текущей темы хоста.\n * @returns Текущая тема (`'light'` | `'dark'` и т.д.), или `undefined` до получения первого события.\n * @example\n * ```tsx\n * function App() {\n * const theme = useTheme();\n * return <div className={theme}>...</div>;\n * }\n * ```\n */\nexport function useTheme(): Theme | undefined {\n const [theme, setTheme] = useState<Theme | undefined>(() => {\n let initial: Theme | undefined;\n const unsubscribe = on('theme.changed', (value) => {\n initial = value;\n });\n unsubscribe();\n return initial;\n });\n\n useEffect(() => {\n const unsubscribe = on('theme.changed', (value) => {\n setTheme(value);\n });\n\n return unsubscribe;\n }, []);\n\n return theme;\n}\n","import { hostApi } from '@weavix/sdk-core';\nimport { useEffect, useState } from 'react';\n\n/**\n * Реактивный хук для получения айди текущего пользователя.\n * @returns Айди пользователя (например, `'qwertyu'`), или `undefined` до получения первого события.\n * @example\n * ```tsx\n * function App() {\n * const userId = useUserId();\n * return <span>Айди: {userId}</span>;\n * }\n * ```\n */\nexport function useUserId(): string | undefined {\n const [userId, setUserId] = useState<string | undefined>(undefined);\n\n useEffect(() => {\n const init = async () => {\n const id = (await hostApi.getUserId()) as string | undefined;\n\n setUserId(id);\n };\n\n init();\n }, []);\n\n return userId;\n}\n","import {\n type BasicContext,\n type ContextLevel,\n type Theme,\n dispatchHostEvent,\n hostApi,\n setHandler,\n uiApi,\n} from '@weavix/sdk-core';\nimport {\n type ReactNode,\n createContext,\n useContext,\n useEffect,\n useMemo,\n useRef,\n useState,\n} from 'react';\nimport { useContext as useSlotContext } from '../hooks/useContext';\nimport { useIsYateam } from '../hooks/useIsYateam';\nimport { useLanguage } from '../hooks/useLanguage';\nimport { useTheme } from '../hooks/useTheme';\nimport { useUserId } from '../hooks/useUserId';\nimport { ErrorBoundary } from './ErrorBoundary';\nimport { PluginError } from './PluginError';\n\n/**\n * Generic registerHandler — no Tracker-specific types.\n */\nexport type RegisterHandlerFunction = (\n methodName: string,\n handler: (...args: unknown[]) => unknown,\n) => void;\n\ninterface CommonPluginContextValue {\n /** Current host theme. Updated reactively on theme.changed. */\n theme: Theme | undefined;\n /** Current host language. Updated reactively on language.changed. */\n language: string | undefined;\n /** Service in which the plugin was opened. */\n service: string;\n /** User ID. */\n userId?: string;\n /** Is this a yateam environment? */\n isYateam?: boolean;\n /** Origin of the parent window (host). */\n origin: string;\n /** Slot in which the plugin is opened. */\n slot: string;\n /** URL inside the plugin. */\n innerUrl: string;\n /** Plugin query parameters. */\n queryParams: Record<string, string>;\n /** Register a handler for responding to host requests. */\n registerHandler: RegisterHandlerFunction;\n}\n\n/**\n * Plugin context at contextLevel = 'basic'.\n * slotContext contains only entityId.\n */\nexport interface BasicPluginContextValue extends CommonPluginContextValue {\n /** Page context — only entityId at basic level. */\n slotContext: BasicContext | undefined;\n\n /** Context level declared in the manifest. */\n contextLevel: 'basic';\n}\n\n/**\n * Plugin context at contextLevel = 'full'.\n * slotContext contains the full slot object.\n */\nexport interface FullPluginContextValue extends CommonPluginContextValue {\n /** Page context — full slot object at full level. */\n slotContext: unknown;\n\n /** Context level declared in the manifest. */\n contextLevel: 'full';\n}\n\nexport type PluginContextValue = BasicPluginContextValue | FullPluginContextValue;\n\n/** Internal context type — only stable data (slot + registerHandler) */\ntype InternalContextValue = {\n slot: string;\n registerHandler: RegisterHandlerFunction;\n innerUrl: string;\n queryParams: Record<string, string>;\n contextLevel: ContextLevel;\n entityId: string | null;\n entityMeta: Record<string, string> | undefined;\n};\n\nconst PluginContext = createContext<InternalContextValue | null>(null);\n\n/**\n * Hook for getting theme, language, slot and slot context from PluginProvider.\n *\n * All values are reactive — updated automatically on push events from the host:\n * - `theme` — on `theme.changed`\n * - `language` — on `language.changed`\n * - `slotContext` — on `context.changed`\n *\n * Supports two context levels:\n * - `'basic'` (default) — slotContext contains only `{ entityId }`.\n * - `'full'` — slotContext contains the full slot object.\n * Requires `contextLevel: \"full\"` in the plugin manifest.\n */\nexport function usePluginContext(): BasicPluginContextValue;\nexport function usePluginContext(level: 'basic'): BasicPluginContextValue;\nexport function usePluginContext(level: 'full'): FullPluginContextValue;\nexport function usePluginContext(\n level: ContextLevel = 'basic',\n): BasicPluginContextValue | FullPluginContextValue {\n const ctx = useContext(PluginContext);\n if (!ctx) {\n throw new Error('usePluginContext must be used within PluginProvider');\n }\n\n // Runtime guard: code requests more than manifest allows\n if (level === 'full' && ctx.contextLevel !== 'full') {\n throw new Error(\n \"🛑 [Security] Code requests 'full' context, but manifest declares 'basic'. \" +\n 'Change the contextLevel in your manifest to get full access.',\n );\n }\n\n // Reactive values — each hook subscribes to its own event\n const theme = useTheme();\n const language = useLanguage();\n const isYateam = useIsYateam();\n const userId = useUserId();\n const fullSlotContext = useSlotContext();\n\n const commonContextValue = {\n service: hostApi.getService(),\n origin: hostApi.getOrigin(),\n slot: ctx.slot,\n innerUrl: ctx.innerUrl,\n queryParams: ctx.queryParams,\n registerHandler: ctx.registerHandler,\n theme,\n language,\n isYateam,\n userId,\n };\n\n if (level === 'basic') {\n const basicSlotContext: BasicContext | undefined = ctx.entityId\n ? { entityId: ctx.entityId, ...(ctx.entityMeta ? { entityMeta: ctx.entityMeta } : {}) }\n : undefined;\n\n return {\n ...commonContextValue,\n contextLevel: 'basic',\n slotContext: basicSlotContext,\n } as BasicPluginContextValue;\n }\n\n return {\n ...commonContextValue,\n contextLevel: 'full',\n slotContext: fullSlotContext,\n } as FullPluginContextValue;\n}\n\nexport interface PluginProviderProps {\n children: ReactNode;\n /**\n * Automatically resize the plugin container when content changes.\n * @default true\n */\n autoResize?: boolean;\n /**\n * Component to display during initialization.\n * @default undefined (nothing shown)\n */\n fallback?: ReactNode;\n /**\n * Component to display on initialization error.\n * @default <PluginError error={error} />\n */\n errorFallback?: (error: Error) => ReactNode;\n /**\n * Automatically notify the host that the plugin is ready after initialization.\n * @default true\n */\n autoNotifyReady?: boolean;\n}\n\nexport const isInternalUrl = (url: string) => {\n try {\n const urlObj = new URL(url, window.location.href);\n return urlObj.origin === window.location.origin;\n } catch {\n return true;\n }\n};\n\n/**\n * Generic plugin provider.\n * Wraps the application and manages the plugin lifecycle.\n *\n * After initialization, theme, language and slot context are available via\n * `usePluginContext()` and update reactively on push events from the host.\n * @example\n * ```tsx\n * root.render(\n * <PluginProvider>\n * <App />\n * </PluginProvider>\n * );\n * ```\n */\nexport function PluginProvider({\n children,\n autoResize = true,\n fallback,\n errorFallback,\n autoNotifyReady = true,\n}: PluginProviderProps) {\n const initializedRef = useRef(false);\n const [initialized, setInitialized] = useState(false);\n const [error, setError] = useState<Error | null>(null);\n const [internalValue, setInternalValue] = useState<InternalContextValue | null>(null);\n\n const registerHandler = useMemo<RegisterHandlerFunction>(() => {\n return (methodName: string, handler: (...args: unknown[]) => unknown) =>\n setHandler(methodName as never, handler as never);\n }, []);\n\n useEffect(() => {\n const handleLinkClick = (event: MouseEvent) => {\n const target = event.target as HTMLElement;\n const linkElement = target.closest<HTMLElement>('[href], [data-href]');\n\n if (!linkElement) return;\n\n const href = linkElement.getAttribute('href') || linkElement.getAttribute('data-href');\n if (!href) return;\n\n if (isInternalUrl(href)) {\n return;\n }\n\n event.preventDefault();\n\n const targetAttr = linkElement.getAttribute('target');\n const newTab = targetAttr === '_blank';\n\n uiApi\n .navigate({\n path: href,\n options: {\n newTab,\n },\n })\n .then(() => {\n console.info(`Navigation: ${href}`);\n })\n .catch((err) => {\n console.error('Navigation error:', err);\n });\n };\n\n document.addEventListener('click', handleLinkClick);\n\n return () => {\n document.removeEventListener('click', handleLinkClick);\n };\n }, []);\n\n useEffect(() => {\n // Prevent double initialization in React StrictMode\n if (initializedRef.current) {\n return;\n }\n\n const initPlugin = async () => {\n try {\n hostApi.init({ autoResize });\n initializedRef.current = true;\n\n const contextLevel = hostApi.getContextLevel();\n const entityId = hostApi.getEntityId();\n const entityMeta = hostApi.getEntityMeta();\n\n setInternalValue({\n slot: hostApi.getSlot(),\n innerUrl: hostApi.getInnerUrl(),\n queryParams: hostApi.getQueryParams(),\n contextLevel,\n entityId,\n entityMeta,\n registerHandler,\n });\n\n if (autoNotifyReady) {\n await hostApi.notifyReady();\n }\n\n // Fetch initial values and prime the eventBus cache so that\n // hooks subscribing after these responses arrive still get the values.\n // For basic contextLevel, skip the context.get postMessage call.\n const [theme, language, context, isYateam, userId] = await Promise.allSettled([\n hostApi.getTheme(),\n hostApi.getLanguage(),\n contextLevel === 'full' ? hostApi.getContext() : Promise.resolve(null),\n hostApi.getIsYateam(),\n hostApi.getUserId(),\n ]);\n\n if (theme.status === 'fulfilled' && theme.value) {\n dispatchHostEvent({\n messageId: '',\n type: 'event',\n method: 'theme.changed',\n result: theme.value,\n });\n }\n if (language.status === 'fulfilled' && language.value) {\n dispatchHostEvent({\n messageId: '',\n type: 'event',\n method: 'language.changed',\n result: language.value,\n });\n }\n\n if (isYateam.status === 'fulfilled' && isYateam.value) {\n dispatchHostEvent({\n messageId: '',\n type: 'event',\n method: 'isYateam.changed',\n result: isYateam.value,\n });\n }\n\n if (userId.status === 'fulfilled' && userId.value) {\n dispatchHostEvent({\n messageId: '',\n type: 'event',\n method: 'userId.changed',\n result: userId.value,\n });\n }\n\n // For basic level, dispatch entityId as context.\n // For full level, dispatch the full context from host.\n if (contextLevel === 'basic') {\n if (entityId) {\n dispatchHostEvent({\n messageId: '',\n type: 'event',\n method: 'context.changed',\n result: { entityId, ...(entityMeta ? { entityMeta } : {}) },\n });\n }\n } else if (context.status === 'fulfilled' && context.value) {\n dispatchHostEvent({\n messageId: '',\n type: 'event',\n method: 'context.changed',\n result: context.value,\n });\n }\n\n setInitialized(true);\n } catch (err) {\n setError(err as Error);\n }\n };\n\n initPlugin();\n }, [autoResize, registerHandler, autoNotifyReady]);\n\n if (error) {\n if (errorFallback) {\n return <>{errorFallback(error)}</>;\n }\n\n return <PluginError error={error} />;\n }\n\n if (!initialized || !internalValue) {\n return <>{fallback}</>;\n }\n\n return (\n <ErrorBoundary\n fallback={errorFallback || ((pluginError) => <PluginError error={pluginError} />)}\n >\n <PluginContext.Provider value={internalValue}>{children}</PluginContext.Provider>\n </ErrorBoundary>\n );\n}\n","import { type ConfirmOptions, type ConfirmResult, uiApi } from '@weavix/sdk-core';\nimport { useCallback } from 'react';\n\nexport type UseConfirmReturn = {\n show: (options: ConfirmOptions) => Promise<ConfirmResult>;\n};\n\nconst useConfirmImpl = () => {\n const show = useCallback((options: ConfirmOptions) => uiApi.confirm.show(options), []);\n\n return { show };\n};\n\nexport const useConfirm = useConfirmImpl as () => UseConfirmReturn;\n","import { type LocalizedString, getLocalizedString } from '@weavix/sdk-core';\nimport { useLanguage } from './useLanguage';\n\nconst useLocalizedStringImpl = (fallbackLanguage = 'ru') => {\n const language = useLanguage();\n\n return (value: LocalizedString): string => {\n return getLocalizedString(value, language, fallbackLanguage);\n };\n};\n\n/**\n * Хук для получения локализованной строки на основе текущего языка из контекста.\n */\nexport const useLocalizedString = useLocalizedStringImpl as (\n fallbackLanguage?: string,\n) => (value: LocalizedString) => string;\n","import { type ToastOptions, uiApi } from '@weavix/sdk-core';\nimport { useCallback } from 'react';\n\nexport type UseToasterReturn = {\n add: (options: ToastOptions) => Promise<{ name: string }>;\n};\n\nconst useToasterImpl = () => {\n const add = useCallback((options: ToastOptions) => uiApi.toaster.add(options), []);\n\n return { add };\n};\n\nexport const useToaster = useToasterImpl as () => UseToasterReturn;\n"],"mappings":";;;;AAYA,IAAa,IAAb,cAAmC,EAAkD;CACjF,OAAO,yBAAyB,GAAkC;EAC9D,OAAO;GAAE,UAAU;GAAM;GAAO;;CAGpC,YAAY,GAA2B;EAEnC,AADA,MAAM,EAAM,EACZ,KAAK,QAAQ;GAAE,UAAU;GAAO,OAAO;GAAM;;CAGjD,kBAAkB,GAAc,GAA4B;EACxD,QAAQ,MAAM,kCAAkC,GAAO,EAAU;;CAGrE,SAAS;EAKL,OAJI,KAAK,MAAM,YAAY,KAAK,MAAM,QAC3B,KAAK,MAAM,SAAS,KAAK,MAAM,MAAM,GAGzC,KAAK,MAAM;;GCeb,KAvCY,EAAE,eACvB,kBAAC,OAAD;CAAK,WAAU;WACX,kBAAC,OAAD;EAAK,WAAU;YAAf;GACI,kBAAC,OAAD;IAAK,WAAU;cAAf,CACI,kBAAC,OAAD;KACI,WAAU;KACV,OAAM;KACN,QAAO;KACP,SAAQ;KACR,MAAK;eALT,CAOI,kBAAC,UAAD;MAAQ,IAAG;MAAK,IAAG;MAAK,GAAE;MAAK,MAAK;MAAY,CAAA,EAChD,kBAAC,QAAD;MACI,GAAE;MACF,QAAO;MACP,aAAY;MACZ,eAAc;MAChB,CAAA,CACA;QACN,kBAAC,MAAD;KAAI,WAAU;eAAsB;KAAiC,CAAA,CACnE;;GACN,kBAAC,OAAD;IAAK,WAAU;cAAwB;IAGjC,CAAA;GACN,kBAAC,WAAD;IAAS,WAAU;cAAnB,CACI,kBAAC,WAAD;KAAS,WAAU;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,GAAU,EAAiB;GCMvD,WAHF,EAAE,KAFG,GAAa,MAA0B,EAAM,QAAQ,IAAI,EAAQ,EAAE,EAAE,CAExE,EAAK"}
1
+ {"version":3,"file":"index.mjs","names":[],"sources":["../src/components/ErrorBoundary.tsx","../src/components/PluginError.tsx","../src/components/PluginLoader.tsx","../src/hooks/useContext.ts","../src/hooks/useIsYateam.ts","../src/hooks/useLanguage.ts","../src/hooks/useTheme.ts","../src/hooks/useUserId.ts","../src/components/PluginProvider.tsx","../src/hooks/useConfirm.ts","../src/hooks/useLocalizedString.ts","../src/hooks/useToaster.ts"],"sourcesContent":["import { Component, ReactNode } from 'react';\n\ninterface ErrorBoundaryProps {\n children: ReactNode;\n fallback: (error: Error) => ReactNode;\n}\n\ninterface ErrorBoundaryState {\n hasError: boolean;\n error: Error | null;\n}\n\nexport class ErrorBoundary extends Component<ErrorBoundaryProps, ErrorBoundaryState> {\n static getDerivedStateFromError(error: Error): ErrorBoundaryState {\n return { hasError: true, error };\n }\n\n constructor(props: ErrorBoundaryProps) {\n super(props);\n this.state = { hasError: false, error: null };\n }\n\n componentDidCatch(error: Error, errorInfo: React.ErrorInfo) {\n console.error('ErrorBoundary caught an error:', error, errorInfo);\n }\n\n render() {\n if (this.state.hasError && this.state.error) {\n return this.props.fallback(this.state.error);\n }\n\n return this.props.children;\n }\n}\n","import type { FC } from 'react';\nimport './PluginError.scss';\n\nexport interface PluginErrorProps {\n error: Error;\n}\n\nconst PluginErrorImpl = ({ error }: PluginErrorProps) => (\n <div className=\"plugin-error\">\n <div className=\"plugin-error__container\">\n <div className=\"plugin-error__header\">\n <svg\n className=\"plugin-error__icon\"\n width=\"24\"\n height=\"24\"\n viewBox=\"0 0 24 24\"\n fill=\"none\"\n >\n <circle cx=\"12\" cy=\"12\" r=\"10\" fill=\"#f44336\" />\n <path\n d=\"M12 7v6m0 4h.01\"\n stroke=\"white\"\n strokeWidth=\"2\"\n strokeLinecap=\"round\"\n />\n </svg>\n <h3 className=\"plugin-error__title\">Ошибка инициализации плагина</h3>\n </div>\n <div className=\"plugin-error__message\">\n Не удалось инициализировать плагин. Проверьте параметры запуска и попробуйте\n перезагрузить страницу.\n </div>\n <details className=\"plugin-error__details\">\n <summary className=\"plugin-error__summary\">Детали ошибки</summary>\n <pre className=\"plugin-error__stack\">\n {error.message}\n {error.stack && `\\n\\n${error.stack}`}\n </pre>\n </details>\n </div>\n </div>\n);\n\n/**\n * Дефолтный компонент для отображения ошибки инициализации плагина\n */\nexport const PluginError = PluginErrorImpl as FC<PluginErrorProps>;\n","import type { FC } from 'react';\nimport './PluginLoader.scss';\n\nconst PluginLoaderImpl = () => (\n <div className=\"plugin-loader\">\n <div className=\"plugin-loader__content\">\n <div className=\"plugin-loader__spinner\" />\n <div className=\"plugin-loader__text\">Загрузка плагина...</div>\n </div>\n </div>\n);\n\n/**\n * Простой лоадер для отображения во время инициализации плагина\n */\nexport const PluginLoader = PluginLoaderImpl as FC;\n","import { on } from '@weavix/sdk-core';\nimport { useEffect, useState } from 'react';\n\n/**\n * Reactive hook for receiving the current slot context pushed by the host.\n * @template T - Type of the context object (defaults to `unknown`)\n * @returns Current context, or `undefined` until the first event arrives from the host.\n * @example\n * ```tsx\n * interface IssueContext {\n * key: string;\n * summary: string;\n * }\n *\n * function App() {\n * const context = useContext<IssueContext>();\n * if (!context) return <Loader />;\n * return <div>{context.summary}</div>;\n * }\n * ```\n */\nexport function useContext<T = unknown>(): T | undefined {\n const [context, setContext] = useState<T | undefined>(() => {\n let initial: T | undefined;\n const unsubscribe = on('context.changed', (value) => {\n initial = value as T;\n });\n unsubscribe();\n return initial;\n });\n\n useEffect(() => {\n const unsubscribe = on('context.changed', (value) => {\n setContext(value as T);\n });\n\n return unsubscribe;\n }, []);\n\n return context;\n}\n","import { hostApi } from '@weavix/sdk-core';\nimport { useEffect, useState } from 'react';\n\n/**\n * Реактивный хук для получения текущей сборки приложения.\n * @returns Является ли ятимом приложение (например, 'true'), или `undefined` до получения первого события.\n * @example\n * ```tsx\n * function App() {\n * const isYateam = useIsYateam();\n * return <span>Ятим ли сейчас?: {isYateam}</span>;\n * }\n * ```\n */\nexport function useIsYateam(): boolean | undefined {\n const [isYateam, setIsYateam] = useState<boolean | undefined>(undefined);\n\n useEffect(() => {\n const init = async () => {\n const yateam = (await hostApi.getIsYateam()) as boolean | undefined;\n setIsYateam(yateam);\n };\n\n init();\n }, []);\n\n return isYateam;\n}\n","import { on } from '@weavix/sdk-core';\nimport { useEffect, useState } from 'react';\n\n/**\n * Реактивный хук для получения текущего языка хоста.\n * @returns Код текущего языка (например, `'ru'`, `'en'`), или `undefined` до получения первого события.\n * @example\n * ```tsx\n * function App() {\n * const language = useLanguage();\n * return <span>Текущий язык: {language}</span>;\n * }\n * ```\n */\nexport function useLanguage(): string | undefined {\n const [language, setLanguage] = useState<string | undefined>(() => {\n let initial: string | undefined;\n const unsubscribe = on('language.changed', (value) => {\n initial = value;\n });\n unsubscribe();\n return initial;\n });\n\n useEffect(() => {\n const unsubscribe = on('language.changed', (value) => {\n setLanguage(value);\n });\n\n return unsubscribe;\n }, []);\n\n return language;\n}\n","import { type Theme, on } from '@weavix/sdk-core';\nimport { useEffect, useState } from 'react';\n\n/**\n * Реактивный хук для получения текущей темы хоста.\n * @returns Текущая тема (`'light'` | `'dark'` и т.д.), или `undefined` до получения первого события.\n * @example\n * ```tsx\n * function App() {\n * const theme = useTheme();\n * return <div className={theme}>...</div>;\n * }\n * ```\n */\nexport function useTheme(): Theme | undefined {\n const [theme, setTheme] = useState<Theme | undefined>(() => {\n let initial: Theme | undefined;\n const unsubscribe = on('theme.changed', (value) => {\n initial = value;\n });\n unsubscribe();\n return initial;\n });\n\n useEffect(() => {\n const unsubscribe = on('theme.changed', (value) => {\n setTheme(value);\n });\n\n return unsubscribe;\n }, []);\n\n return theme;\n}\n","import { hostApi } from '@weavix/sdk-core';\nimport { useEffect, useState } from 'react';\n\n/**\n * Реактивный хук для получения айди текущего пользователя.\n * @returns Айди пользователя (например, `'qwertyu'`), или `undefined` до получения первого события.\n * @example\n * ```tsx\n * function App() {\n * const userId = useUserId();\n * return <span>Айди: {userId}</span>;\n * }\n * ```\n */\nexport function useUserId(): string | undefined {\n const [userId, setUserId] = useState<string | undefined>(undefined);\n\n useEffect(() => {\n const init = async () => {\n const id = (await hostApi.getUserId()) as string | undefined;\n\n setUserId(id);\n };\n\n init();\n }, []);\n\n return userId;\n}\n","import {\n type BasicContext,\n type ContextLevel,\n type Theme,\n dispatchHostEvent,\n hostApi,\n setHandler,\n uiApi,\n} from '@weavix/sdk-core';\nimport {\n type ReactNode,\n createContext,\n useContext,\n useEffect,\n useMemo,\n useRef,\n useState,\n} from 'react';\nimport { useContext as useSlotContext } from '../hooks/useContext';\nimport { useIsYateam } from '../hooks/useIsYateam';\nimport { useLanguage } from '../hooks/useLanguage';\nimport { useTheme } from '../hooks/useTheme';\nimport { useUserId } from '../hooks/useUserId';\nimport { ErrorBoundary } from './ErrorBoundary';\nimport { PluginError } from './PluginError';\n\n/**\n * Generic registerHandler — no Tracker-specific types.\n */\nexport type RegisterHandlerFunction = (\n methodName: string,\n handler: (...args: unknown[]) => unknown,\n) => void;\n\ninterface CommonPluginContextValue {\n /** Current host theme. Updated reactively on theme.changed. */\n theme: Theme | undefined;\n /** Current host language. Updated reactively on language.changed. */\n language: string | undefined;\n /** Service in which the plugin was opened. */\n service: string;\n /** User ID. */\n userId?: string;\n /** Is this a yateam environment? */\n isYateam?: boolean;\n /** Origin of the parent window (host). */\n origin: string;\n /** Slot in which the plugin is opened. */\n slot: string;\n /** URL inside the plugin. */\n innerUrl: string;\n /** Plugin query parameters. */\n queryParams: Record<string, string>;\n /** Register a handler for responding to host requests. */\n registerHandler: RegisterHandlerFunction;\n}\n\n/**\n * Plugin context at contextLevel = 'basic'.\n * slotContext contains only entityId.\n */\nexport interface BasicPluginContextValue extends CommonPluginContextValue {\n /** Page context — only entityId at basic level. */\n slotContext: BasicContext | undefined;\n\n /** Context level declared in the manifest. */\n contextLevel: 'basic';\n}\n\n/**\n * Plugin context at contextLevel = 'full'.\n * slotContext contains the full slot object.\n */\nexport interface FullPluginContextValue extends CommonPluginContextValue {\n /** Page context — full slot object at full level. */\n slotContext: unknown;\n\n /** Context level declared in the manifest. */\n contextLevel: 'full';\n}\n\nexport type PluginContextValue = BasicPluginContextValue | FullPluginContextValue;\n\n/** Internal context type — only stable data (slot + registerHandler) */\ntype InternalContextValue = {\n slot: string;\n registerHandler: RegisterHandlerFunction;\n innerUrl: string;\n queryParams: Record<string, string>;\n contextLevel: ContextLevel;\n entityId: string | null;\n entityMeta: Record<string, string> | undefined;\n};\n\nconst PluginContext = createContext<InternalContextValue | null>(null);\n\n/**\n * Hook for getting theme, language, slot and slot context from PluginProvider.\n *\n * All values are reactive — updated automatically on push events from the host:\n * - `theme` — on `theme.changed`\n * - `language` — on `language.changed`\n * - `slotContext` — on `context.changed`\n *\n * Supports two context levels:\n * - `'basic'` (default) — slotContext contains only `{ entityId }`.\n * - `'full'` — slotContext contains the full slot object.\n * Requires `contextLevel: \"full\"` in the plugin manifest.\n */\nexport function usePluginContext(): BasicPluginContextValue;\nexport function usePluginContext(level: 'basic'): BasicPluginContextValue;\nexport function usePluginContext(level: 'full'): FullPluginContextValue;\nexport function usePluginContext(\n level: ContextLevel = 'basic',\n): BasicPluginContextValue | FullPluginContextValue {\n const ctx = useContext(PluginContext);\n if (!ctx) {\n throw new Error('usePluginContext must be used within PluginProvider');\n }\n\n // Runtime guard: code requests more than manifest allows\n if (level === 'full' && ctx.contextLevel !== 'full') {\n throw new Error(\n \"🛑 [Security] Code requests 'full' context, but manifest declares 'basic'. \" +\n 'Change the contextLevel in your manifest to get full access.',\n );\n }\n\n // Reactive values — each hook subscribes to its own event\n const theme = useTheme();\n const language = useLanguage();\n const isYateam = useIsYateam();\n const userId = useUserId();\n const fullSlotContext = useSlotContext();\n\n const commonContextValue = {\n service: hostApi.getService(),\n origin: hostApi.getOrigin(),\n slot: ctx.slot,\n innerUrl: ctx.innerUrl,\n queryParams: ctx.queryParams,\n registerHandler: ctx.registerHandler,\n theme,\n language,\n isYateam,\n userId,\n };\n\n if (level === 'basic') {\n const basicSlotContext: BasicContext | undefined = ctx.entityId\n ? { entityId: ctx.entityId, ...(ctx.entityMeta ? { entityMeta: ctx.entityMeta } : {}) }\n : undefined;\n\n return {\n ...commonContextValue,\n contextLevel: 'basic',\n slotContext: basicSlotContext,\n } as BasicPluginContextValue;\n }\n\n return {\n ...commonContextValue,\n contextLevel: 'full',\n slotContext: fullSlotContext,\n } as FullPluginContextValue;\n}\n\nexport interface PluginProviderProps {\n children: ReactNode;\n /**\n * Automatically resize the plugin container when content changes.\n * @default true\n */\n autoResize?: boolean;\n /**\n * Component to display during initialization.\n * @default undefined (nothing shown)\n */\n fallback?: ReactNode;\n /**\n * Component to display on initialization error.\n * @default <PluginError error={error} />\n */\n errorFallback?: (error: Error) => ReactNode;\n /**\n * Automatically notify the host that the plugin is ready after initialization.\n * @default true\n */\n autoNotifyReady?: boolean;\n}\n\nexport const isInternalUrl = (url: string) => {\n try {\n const urlObj = new URL(url, window.location.href);\n return urlObj.origin === window.location.origin;\n } catch {\n return true;\n }\n};\n\n/**\n * Generic plugin provider.\n * Wraps the application and manages the plugin lifecycle.\n *\n * After initialization, theme, language and slot context are available via\n * `usePluginContext()` and update reactively on push events from the host.\n * @example\n * ```tsx\n * root.render(\n * <PluginProvider>\n * <App />\n * </PluginProvider>\n * );\n * ```\n */\nexport function PluginProvider({\n children,\n autoResize = true,\n fallback,\n errorFallback,\n autoNotifyReady = true,\n}: PluginProviderProps) {\n const initializedRef = useRef(false);\n const [initialized, setInitialized] = useState(false);\n const [error, setError] = useState<Error | null>(null);\n const [internalValue, setInternalValue] = useState<InternalContextValue | null>(null);\n\n const registerHandler = useMemo<RegisterHandlerFunction>(() => {\n return (methodName: string, handler: (...args: unknown[]) => unknown) =>\n setHandler(methodName as never, handler as never);\n }, []);\n\n useEffect(() => {\n const handleLinkClick = (event: MouseEvent) => {\n const target = event.target as HTMLElement;\n const linkElement = target.closest<HTMLElement>('[href], [data-href]');\n\n if (!linkElement) return;\n\n const href = linkElement.getAttribute('href') || linkElement.getAttribute('data-href');\n if (!href) return;\n\n if (isInternalUrl(href)) {\n return;\n }\n\n event.preventDefault();\n\n const targetAttr = linkElement.getAttribute('target');\n const newTab = targetAttr === '_blank';\n\n uiApi\n .navigate({\n path: href,\n options: {\n newTab,\n },\n })\n .then(() => {\n console.info(`Navigation: ${href}`);\n })\n .catch((err) => {\n console.error('Navigation error:', err);\n });\n };\n\n document.addEventListener('click', handleLinkClick);\n\n return () => {\n document.removeEventListener('click', handleLinkClick);\n };\n }, []);\n\n useEffect(() => {\n // Prevent double initialization in React StrictMode\n if (initializedRef.current) {\n return;\n }\n\n const initPlugin = async () => {\n try {\n hostApi.init({ autoResize });\n initializedRef.current = true;\n\n const contextLevel = hostApi.getContextLevel();\n const entityId = hostApi.getEntityId();\n const entityMeta = hostApi.getEntityMeta();\n\n setInternalValue({\n slot: hostApi.getSlot(),\n innerUrl: hostApi.getInnerUrl(),\n queryParams: hostApi.getQueryParams(),\n contextLevel,\n entityId,\n entityMeta,\n registerHandler,\n });\n\n if (autoNotifyReady) {\n await hostApi.notifyReady();\n }\n\n // Fetch initial values and prime the eventBus cache so that\n // hooks subscribing after these responses arrive still get the values.\n // For basic contextLevel, skip the context.get postMessage call.\n const [theme, language, context, isYateam, userId] = await Promise.allSettled([\n hostApi.getTheme(),\n hostApi.getLanguage(),\n contextLevel === 'full' ? hostApi.getContext() : Promise.resolve(null),\n hostApi.getIsYateam(),\n hostApi.getUserId(),\n ]);\n\n if (theme.status === 'fulfilled' && theme.value) {\n dispatchHostEvent({\n messageId: '',\n type: 'event',\n method: 'theme.changed',\n result: theme.value,\n });\n }\n if (language.status === 'fulfilled' && language.value) {\n dispatchHostEvent({\n messageId: '',\n type: 'event',\n method: 'language.changed',\n result: language.value,\n });\n }\n\n if (isYateam.status === 'fulfilled' && isYateam.value) {\n dispatchHostEvent({\n messageId: '',\n type: 'event',\n method: 'isYateam.changed',\n result: isYateam.value,\n });\n }\n\n if (userId.status === 'fulfilled' && userId.value) {\n dispatchHostEvent({\n messageId: '',\n type: 'event',\n method: 'userId.changed',\n result: userId.value,\n });\n }\n\n // For basic level, dispatch entityId as context.\n // For full level, dispatch the full context from host.\n if (contextLevel === 'basic') {\n if (entityId) {\n dispatchHostEvent({\n messageId: '',\n type: 'event',\n method: 'context.changed',\n result: { entityId, ...(entityMeta ? { entityMeta } : {}) },\n });\n }\n } else if (context.status === 'fulfilled' && context.value) {\n dispatchHostEvent({\n messageId: '',\n type: 'event',\n method: 'context.changed',\n result: context.value,\n });\n }\n\n setInitialized(true);\n } catch (err) {\n setError(err as Error);\n }\n };\n\n initPlugin();\n }, [autoResize, registerHandler, autoNotifyReady]);\n\n if (error) {\n if (errorFallback) {\n return <>{errorFallback(error)}</>;\n }\n\n return <PluginError error={error} />;\n }\n\n if (!initialized || !internalValue) {\n return <>{fallback}</>;\n }\n\n return (\n <ErrorBoundary\n fallback={errorFallback || ((pluginError) => <PluginError error={pluginError} />)}\n >\n <PluginContext.Provider value={internalValue}>{children}</PluginContext.Provider>\n </ErrorBoundary>\n );\n}\n","import { type ConfirmOptions, type ConfirmResult, uiApi } from '@weavix/sdk-core';\nimport { useCallback } from 'react';\n\nexport type UseConfirmReturn = {\n show: (options: ConfirmOptions) => Promise<ConfirmResult>;\n};\n\nconst useConfirmImpl = () => {\n const show = useCallback((options: ConfirmOptions) => uiApi.confirm.show(options), []);\n\n return { show };\n};\n\nexport const useConfirm = useConfirmImpl as () => UseConfirmReturn;\n","import { type LocalizedString, getLocalizedString } from '@weavix/sdk-core';\nimport { useLanguage } from './useLanguage';\n\nconst useLocalizedStringImpl = (fallbackLanguage = 'ru') => {\n const language = useLanguage();\n\n return (value: LocalizedString): string => {\n return getLocalizedString(value, language, fallbackLanguage);\n };\n};\n\n/**\n * Хук для получения локализованной строки на основе текущего языка из контекста.\n */\nexport const useLocalizedString = useLocalizedStringImpl as (\n fallbackLanguage?: string,\n) => (value: LocalizedString) => string;\n","import { type ToastOptions, uiApi } from '@weavix/sdk-core';\nimport { useCallback } from 'react';\n\nexport type UseToasterReturn = {\n add: (options: ToastOptions) => Promise<{ name: string }>;\n};\n\nconst useToasterImpl = () => {\n const add = useCallback((options: ToastOptions) => uiApi.toaster.add(options), []);\n\n return { add };\n};\n\nexport const useToaster = useToasterImpl as () => UseToasterReturn;\n"],"mappings":";;;;AAYA,IAAa,IAAb,cAAmC,EAAkD;CACjF,OAAO,yBAAyB,GAAkC;EAC9D,OAAO;GAAE,UAAU;GAAM;EAAM;CACnC;CAEA,YAAY,GAA2B;EAEnC,AADA,MAAM,CAAK,GACX,KAAK,QAAQ;GAAE,UAAU;GAAO,OAAO;EAAK;CAChD;CAEA,kBAAkB,GAAc,GAA4B;EACxD,QAAQ,MAAM,kCAAkC,GAAO,CAAS;CACpE;CAEA,SAAS;EAKL,OAJI,KAAK,MAAM,YAAY,KAAK,MAAM,QAC3B,KAAK,MAAM,SAAS,KAAK,MAAM,KAAK,IAGxC,KAAK,MAAM;CACtB;AACJ,GCaa,KAvCY,EAAE,eACvB,kBAAC,OAAD;CAAK,WAAU;WACX,kBAAC,OAAD;EAAK,WAAU;YAAf;GACI,kBAAC,OAAD;IAAK,WAAU;cAAf,CACI,kBAAC,OAAD;KACI,WAAU;KACV,OAAM;KACN,QAAO;KACP,SAAQ;KACR,MAAK;eALT,CAOI,kBAAC,UAAD;MAAQ,IAAG;MAAK,IAAG;MAAK,GAAE;MAAK,MAAK;KAAW,CAAA,GAC/C,kBAAC,QAAD;MACI,GAAE;MACF,QAAO;MACP,aAAY;MACZ,eAAc;KACjB,CAAA,CACA;QACL,kBAAC,MAAD;KAAI,WAAU;eAAsB;IAAgC,CAAA,CACnE;;GACL,kBAAC,OAAD;IAAK,WAAU;cAAwB;GAGlC,CAAA;GACL,kBAAC,WAAD;IAAS,WAAU;cAAnB,CACI,kBAAC,WAAD;KAAS,WAAU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AAa,WAHF,EAAE,MAFI,GAAa,MAA4B,EAAM,QAAQ,KAAK,CAAO,GAAG,CAAC,CAE3E,EAAK,ICIL,KAXmB,IAAmB,SAAS;CACxD,IAAM,IAAW,EAAY;CAE7B,QAAQ,MACG,EAAmB,GAAO,GAAU,CAAgB;AAEnE,GCIa,WAHF,EAAE,KAFG,GAAa,MAA0B,EAAM,QAAQ,IAAI,CAAO,GAAG,CAAC,CAEvE,EAAI"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@weavix/sdk-react",
3
- "version": "0.0.13",
3
+ "version": "0.0.15",
4
4
  "exports": {
5
5
  ".": {
6
6
  "types": "./dist/index.d.ts",
@@ -12,7 +12,7 @@
12
12
  "README.md"
13
13
  ],
14
14
  "dependencies": {
15
- "@weavix/sdk-core": "0.0.13"
15
+ "@weavix/sdk-core": "0.0.15"
16
16
  },
17
17
  "peerDependencies": {
18
18
  "react": "^18.0.0"