Files
xo-stack/packages/docs/src/.vitepress/theme/utils/useXOCashLibs.ts
T

79 lines
2.2 KiB
TypeScript

import { watch, onMounted, reactive } from 'vue';
export type ImportedLib = {
versions: string[];
selectedVersion: string;
libTypes: string;
};
export type XOCashLibs = {
'@xocash/stack': ImportedLib;
'@xocash/primitives': ImportedLib;
};
const xocashLibs = reactive<XOCashLibs>({
'@xocash/stack': {
versions: [],
selectedVersion: '',
libTypes: '',
},
'@xocash/primitives': {
versions: [],
selectedVersion: '',
libTypes: '',
},
});
export const useXOCashLibs = (): XOCashLibs => {
// Get versions from npm registry
const getVersions = async (): Promise<string[]> => {
const response = await fetch('https://registry.npmjs.org/@xocash/stack');
const data = await response.json();
const versions = Object.keys(data.versions);
return versions;
};
const getTypes = async (packageName: string, version: string) => {
const response = await fetch(
`https://cdn.jsdelivr.net/npm/${packageName}@${version}/dist/types-bundled.d.ts`,
);
const content = await response.text();
return content;
};
// Update the types file when the selected version changes.
watch(
() => xocashLibs['@xocash/stack'].selectedVersion,
async (newVersion) => {
const stackTypes = await getTypes('@xocash/stack', newVersion);
const primitivesTypes = await getTypes('@xocash/primitives', newVersion);
// Only set the types file if the selected version has not been changed while fetching the types.
if (xocashLibs['@xocash/stack'].selectedVersion === newVersion) {
xocashLibs['@xocash/stack'].libTypes = stackTypes;
xocashLibs['@xocash/primitives'].libTypes = primitivesTypes;
}
},
);
// Fetch the versions and set the selected version when the component is mounted.
onMounted(async () => {
xocashLibs['@xocash/stack'].versions = await getVersions();
// Only update the selected version if it is not already set.
if (!xocashLibs['@xocash/stack'].selectedVersion) {
xocashLibs['@xocash/stack'].selectedVersion =
xocashLibs['@xocash/stack'].versions[
xocashLibs['@xocash/stack'].versions.length - 1
];
}
});
return xocashLibs;
};