| 1 |
import { getPluginsShape, pluginShape } from '@auto-launch/fetchers/shape'; |
| 2 |
import { |
| 3 |
failWithFallback, |
| 4 |
fetchWithTimeout, |
| 5 |
retryTwice, |
| 6 |
setStatus, |
| 7 |
} from '@auto-launch/functions/helpers'; |
| 8 |
import { AI_HOST } from '@constants'; |
| 9 |
import { digest } from '@shared/api/digest'; |
| 10 |
import { reqDataBasics } from '@shared/lib/data'; |
| 11 |
import { __ } from '@wordpress/i18n'; |
| 12 |
import { z } from 'zod'; |
| 13 |
|
| 14 |
const { pluginGroupId } = window.extSharedData; |
| 15 |
const fallback = { sitePlugins: [] }; |
| 16 |
const url = `${AI_HOST}/api/site-plugins`; |
| 17 |
const method = 'POST'; |
| 18 |
const headers = { 'Content-Type': 'application/json' }; |
| 19 |
|
| 20 |
const shapeLocal = z.object({ |
| 21 |
selectedPlugins: z.array(pluginShape), |
| 22 |
}); |
| 23 |
|
| 24 |
export const handleSitePlugins = async ({ |
| 25 |
siteProfile = {}, |
| 26 |
requiredOnly = false, |
| 27 |
showStatus = true, |
| 28 |
}) => { |
| 29 |
if (showStatus) { |
| 30 |
// translators: this is for a action log UI. Keep it short |
| 31 |
setStatus(__('Setting up site functionality', 'extendify-local')); |
| 32 |
} |
| 33 |
|
| 34 |
const body = JSON.stringify({ |
| 35 |
...reqDataBasics, |
| 36 |
...siteProfile, |
| 37 |
siteProfile, |
| 38 |
siteObjective: siteProfile.objective, |
| 39 |
pluginGroupId, |
| 40 |
requiredOnly, |
| 41 |
}); |
| 42 |
|
| 43 |
const response = await retryTwice(() => |
| 44 |
fetchWithTimeout(url, { method, headers, body }), |
| 45 |
).catch((error) => { |
| 46 |
return { ok: false, statusText: error.message, status: 0 }; |
| 47 |
}); |
| 48 |
|
| 49 |
if (!response?.ok) { |
| 50 |
digest({ |
| 51 |
error: { |
| 52 |
message: response.statusText, |
| 53 |
name: 'FetchError', |
| 54 |
status: response.status, |
| 55 |
}, |
| 56 |
details: { source: 'auto-launch', caller: 'handleSitePlugins' }, |
| 57 |
}); |
| 58 |
return fallback; |
| 59 |
} |
| 60 |
|
| 61 |
const { selectedPlugins } = await failWithFallback( |
| 62 |
async () => shapeLocal.parse(await response.json()), |
| 63 |
fallback, |
| 64 |
{ caller: 'handleSitePlugins' }, |
| 65 |
); |
| 66 |
return getPluginsShape.parse({ sitePlugins: selectedPlugins }); |
| 67 |
}; |
| 68 |
|