vike
Version:
The Framework *You* Control - Next.js & Nuxt alternative for unprecedented flexibility and dependability.
59 lines (58 loc) • 2.62 kB
JavaScript
// Public usage
export { getGlobalContext };
export { getGlobalContextSync };
// Internal usage
export { createGetGlobalContextClient };
import { createGlobalContextShared, getGlobalContextSyncErrMsg, } from '../../shared/createGlobalContextShared.js';
import { getGlobalContextSerializedInHtml } from './getJsonSerializedInHtml.js';
import { assert, assertUsage, genPromise, getGlobalObject, objectAssign } from './utils.js';
const globalObject = getGlobalObject('createGetGlobalContextClient.ts', (() => {
const { promise: globalContextPromise, resolve: globalContextPromiseResolve } = genPromise();
return {
globalContextPromise,
globalContextPromiseResolve,
};
})());
function createGetGlobalContextClient(virtualFileExports, isClientRouting, addGlobalContext) {
assert(globalObject.isClientRouting === undefined || globalObject.isClientRouting === isClientRouting);
globalObject.isClientRouting = isClientRouting;
// Eagerly call onCreateGlobalContext() hook
getGlobalContext();
return getGlobalContext;
async function getGlobalContext() {
// Cache
if (globalObject.globalContext &&
// Don't break HMR
globalObject.globalContext._virtualFileExports !== virtualFileExports) {
return globalObject.globalContext;
}
// Create
const globalContext = await createGlobalContextShared(virtualFileExports, globalObject, async (globalContext) => {
const globalContextAddendum = {
/**
* Whether the environment is client-side or server-side / pre-rendering.
*
* We recommend using `import.meta.env.SSR` instead, see https://vike.dev/globalContext
*/
isClientSide: true,
};
objectAssign(globalContextAddendum, getGlobalContextSerializedInHtml());
objectAssign(globalContextAddendum, await addGlobalContext?.(globalContext));
return globalContextAddendum;
});
assert(globalObject.globalContext);
globalObject.globalContextPromiseResolve(globalObject.globalContext);
// Return
return globalContext;
}
}
// The type is never used: it's the type of the server-side getGlobalContext() that is used.
async function getGlobalContext() {
const globalContext = await globalObject.globalContextPromise;
return globalContext;
}
function getGlobalContextSync() {
const { globalContext } = globalObject;
assertUsage(globalContext, getGlobalContextSyncErrMsg);
return globalContext;
}