UNPKG

@saleor/app-sdk

Version:
279 lines (266 loc) 9.84 kB
import { AppPermission, LocaleCode, Permission } from '../types.js'; import * as React from 'react'; import { ReactNode } from 'react'; import * as jose from 'jose'; import { NextPage } from 'next'; type Values<T> = T[keyof T]; declare const ActionType: { /** * Ask Dashboard to redirect - either internal or external route */ readonly redirect: "redirect"; /** * Ask Dashboard to send a notification toast */ readonly notification: "notification"; /** * Ask Dashboard to update deep URL to preserve app route after refresh */ readonly updateRouting: "updateRouting"; /** * Inform Dashboard that AppBridge is ready */ readonly notifyReady: "notifyReady"; /** * Request one or more permissions from the Dashboard * * Available from 3.15 */ readonly requestPermission: "requestPermissions"; }; type ActionType = Values<typeof ActionType>; type ActionWithId<Name extends ActionType, Payload extends {}> = { payload: Payload & { actionId: string; }; type: Name; }; type RedirectPayload = { /** * Relative (inside Dashboard) or absolute URL path. */ to: string; newContext?: boolean; }; /** * Redirects Dashboard user. */ type RedirectAction = ActionWithId<"redirect", RedirectPayload>; declare function createRedirectAction(payload: RedirectPayload): RedirectAction; type NotificationPayload = { /** * Matching Dashboard's notification object. */ status?: "info" | "success" | "warning" | "error"; title?: string; text?: string; apiMessage?: string; }; type NotificationAction = ActionWithId<"notification", NotificationPayload>; /** * Shows a notification using Dashboard's notification system. */ declare function createNotificationAction(payload: NotificationPayload): NotificationAction; type UpdateRoutingPayload = { newRoute: string; }; type UpdateRouting = ActionWithId<"updateRouting", UpdateRoutingPayload>; declare function createUpdateRoutingAction(payload: UpdateRoutingPayload): UpdateRouting; type NotifyReady = ActionWithId<"notifyReady", {}>; declare function createNotifyReadyAction(): NotifyReady; type RequestPermissions = ActionWithId<"requestPermissions", { permissions: AppPermission[]; redirectPath: string; }>; declare function createRequestPermissionsAction(permissions: AppPermission[], redirectPath: string): RequestPermissions; type Actions = RedirectAction | NotificationAction | UpdateRouting | NotifyReady | RequestPermissions; declare const actions: { Redirect: typeof createRedirectAction; Notification: typeof createNotificationAction; UpdateRouting: typeof createUpdateRoutingAction; NotifyReady: typeof createNotifyReadyAction; RequestPermissions: typeof createRequestPermissionsAction; }; type Version = 1; declare const EventType: { readonly handshake: "handshake"; readonly response: "response"; readonly redirect: "redirect"; readonly theme: "theme"; readonly localeChanged: "localeChanged"; readonly tokenRefresh: "tokenRefresh"; }; type EventType = Values<typeof EventType>; type Event<Name extends EventType, Payload extends {}> = { payload: Payload; type: Name; }; type HandshakeEvent = Event<"handshake", { token: string; version: Version; saleorVersion?: string; dashboardVersion?: string; }>; type DispatchResponseEvent = Event<"response", { actionId: string; ok: boolean; }>; type RedirectEvent = Event<"redirect", { path: string; }>; type ThemeType = "light" | "dark"; type ThemeEvent = Event<"theme", { theme: ThemeType; }>; type LocaleChangedEvent = Event<"localeChanged", { locale: LocaleCode; }>; type TokenRefreshEvent = Event<"tokenRefresh", { token: string; }>; type Events = HandshakeEvent | DispatchResponseEvent | RedirectEvent | ThemeEvent | LocaleChangedEvent | TokenRefreshEvent; type PayloadOfEvent<TEventType extends EventType, TEvent extends Events = Events> = TEvent extends Event<TEventType, unknown> ? TEvent["payload"] : never; declare const DashboardEventFactory: { createThemeChangeEvent(theme: ThemeType): ThemeEvent; createRedirectEvent(path: string): RedirectEvent; createDispatchResponseEvent(actionId: string, ok: boolean): DispatchResponseEvent; createHandshakeEvent(token: string, version?: Version, saleorVersions?: { dashboard: string; core: string; }): HandshakeEvent; createLocaleChangedEvent(newLocale: LocaleCode): LocaleChangedEvent; createTokenRefreshEvent(newToken: string): TokenRefreshEvent; }; type AppBridgeState = { token?: string; id: string; ready: boolean; path: string; theme: ThemeType; locale: LocaleCode; saleorApiUrl: string; saleorVersion?: string; dashboardVersion?: string; user?: { /** * Original permissions of the user that is using the app. * *Not* the same permissions as the app itself. * * Can be used by app to check if user is authorized to perform * domain specific actions */ permissions: Permission[]; email: string; }; appPermissions?: AppPermission[]; }; type EventCallback<TPayload extends {} = {}> = (data: TPayload) => void; type AppBridgeOptions = { saleorApiUrl?: string; initialLocale?: LocaleCode; /** * Should automatically emit Actions.NotifyReady. * If app loading time is longer, this can be disabled and sent manually. */ autoNotifyReady?: boolean; initialTheme?: ThemeType; }; declare class AppBridge { private state; private refererOrigin; private subscribeMap; private combinedOptions; constructor(options?: AppBridgeOptions); /** * Subscribes to an Event. * * @param eventType - Event type. * @param cb - Callback that executes when Event is registered. Called with Event payload object. * @returns Unsubscribe function. Call to unregister the callback. */ subscribe<TEventType extends EventType, TPayload extends PayloadOfEvent<TEventType>>(eventType: TEventType, cb: EventCallback<TPayload>): () => void; /** * Unsubscribe to all Events of type. * If type not provider, unsubscribe all * * @param eventType - (optional) Event type. If empty, all callbacks will be unsubscribed. */ unsubscribeAll(eventType?: EventType): void; /** * Dispatch event to dashboard */ dispatch<T extends Actions>(action: T): Promise<void>; /** * Gets current state */ getState(): AppBridgeState; sendNotifyReadyAction(): void; private setInitialState; private listenOnMessages; } interface AppBridgeContext { /** * App can be undefined, because it gets initialized in Browser only */ appBridge?: AppBridge; mounted: boolean; } type Props$1 = { appBridgeInstance?: AppBridge; }; declare const AppContext: React.Context<AppBridgeContext>; declare function AppBridgeProvider({ appBridgeInstance, ...props }: React.PropsWithChildren<Props$1>): React.JSX.Element; declare const useAppBridge: () => { appBridge: AppBridge | undefined; appBridgeState: AppBridgeState | null; }; /** * Contains keys of SearchParams added to iframe src */ declare const AppIframeParams: { APP_ID: string; THEME: string; DOMAIN: string; SALEOR_API_URL: string; LOCALE: string; }; type HasAppBridgeState = Pick<AppBridge, "getState">; /** * Created decorated window.fetch with headers required by app-sdk Next api handlers utilities */ declare const createAuthenticatedFetch: (appBridge: HasAppBridgeState, fetch?: typeof globalThis.fetch) => typeof global.fetch; /** * Hook working only in browser context. Ensure parent component is dynamic() and mounted in the browser. */ declare const useAuthenticatedFetch: (fetch?: ((input: RequestInfo | URL, init?: RequestInit) => Promise<Response>) & typeof globalThis.fetch) => typeof window.fetch; /** * @deprecated Use AppBridge instead */ type App = AppBridge; interface DashboardTokenPayload extends jose.JWTPayload { app: string; } interface DashboardTokenProps { isTokenValid: boolean; hasAppToken: boolean; tokenClaims: DashboardTokenPayload | null; } declare const useDashboardToken: () => DashboardTokenProps; type Props = { unmounted?: ReactNode; notIframe?: ReactNode; noDashboardToken?: ReactNode; dashboardTokenInvalid?: ReactNode; }; type WithAuthorizationHOC<P> = React.FunctionComponent<P> & { getLayout?: (page: React.ReactElement) => React.ReactNode; }; /** * Most likely, views from your app will be only accessibly inside Dashboard iframe. * This HOC can be used to handle all checks, with default messages included. * Each error screen can be passed into HOC factory * * If screen can be accessible outside Dashboard - omit this HOC on this page * */ declare const withAuthorization: (props?: Props) => <BaseProps extends React.ComponentProps<NextPage>>(BaseComponent: React.FunctionComponent<BaseProps>) => WithAuthorizationHOC<BaseProps>; export { ActionType, type Actions, type App, AppBridge, AppBridgeProvider, type AppBridgeState, AppContext, AppIframeParams, DashboardEventFactory, type DashboardTokenPayload, type DashboardTokenProps, type DispatchResponseEvent, EventType, type Events, type HandshakeEvent, type LocaleChangedEvent, type NotificationAction, type NotificationPayload, type NotifyReady, type PayloadOfEvent, type RedirectAction, type RedirectEvent, type RedirectPayload, type RequestPermissions, type ThemeEvent, type ThemeType, type TokenRefreshEvent, type UpdateRouting, type UpdateRoutingPayload, type Version, actions, createAuthenticatedFetch, useAppBridge, useAuthenticatedFetch, useDashboardToken, withAuthorization };