index.ts
58 lines
| 1 | /** |
| 2 | * External dependencies |
| 3 | */ |
| 4 | import { isAtomicSite, isSimpleSite } from '@automattic/jetpack-shared-extension-utils'; |
| 5 | import debugFactory from 'debug'; |
| 6 | |
| 7 | const initialState = window?.JP_CONNECTION_INITIAL_STATE; |
| 8 | const debug = debugFactory( 'jetpack-ai-assistant:connection' ); |
| 9 | let hasCheckedConnection = false; |
| 10 | |
| 11 | const debugOnce = content => { |
| 12 | if ( ! hasCheckedConnection ) { |
| 13 | debug( content ); |
| 14 | hasCheckedConnection = true; |
| 15 | } |
| 16 | }; |
| 17 | |
| 18 | /** |
| 19 | * Return the initial connection status. |
| 20 | * |
| 21 | * @returns {boolean} true if the user is connected, false otherwise. |
| 22 | */ |
| 23 | export function isUserConnected(): boolean { |
| 24 | if ( isSimpleSite() ) { |
| 25 | debugOnce( 'Simple site connected � |
| 26 | ' ); |
| 27 | return true; |
| 28 | } |
| 29 | |
| 30 | if ( isAtomicSite() ) { |
| 31 | debugOnce( 'Atomic site connected � |
| 32 | ' ); |
| 33 | return true; |
| 34 | } |
| 35 | |
| 36 | if ( initialState?.connectionStatus?.isUserConnected ) { |
| 37 | debugOnce( 'Jetpack user is connected � |
| 38 | ' ); |
| 39 | return true; |
| 40 | } |
| 41 | |
| 42 | debugOnce( 'User is not connected ❌' ); |
| 43 | return false; |
| 44 | } |
| 45 | |
| 46 | export function canUserPurchasePlan(): boolean { |
| 47 | if ( isSimpleSite() ) { |
| 48 | // Roles on simple sites can't be inferred from the connection status. |
| 49 | return true; |
| 50 | } |
| 51 | |
| 52 | const permissions = |
| 53 | initialState?.userConnectionData?.currentUser?.permissions ?? |
| 54 | ( {} as { manage_options?: boolean } ); |
| 55 | |
| 56 | return ! permissions.manage_options === false; |
| 57 | } |
| 58 |