blade
Version:
React at the edge.
77 lines (74 loc) • 2.56 kB
JavaScript
//#region private/universal/utils/constants.ts
const CLIENT_ASSET_PREFIX = "client";
const PUBLIC_ASSET_PREFIX = "public";
const DEFAULT_PAGE_PATH = "blade-default-pages";
const CUSTOM_HEADERS = {
bundleId: "X-Bundle-Id",
subscribe: "X-Subscribe"
};
const DEFAULT_COOKIE_MAX_AGE = 31536e3;
//#endregion
//#region private/universal/utils/paths.ts
const populatePathSegments = (defaultHref, params) => {
let href = defaultHref;
const currentQuery = Object.assign({}, params);
const pathSegments = Array.from(href.matchAll(/\[(.*?)\]/g));
for (const pathSegment of pathSegments) {
const [segment, segmentName] = pathSegment;
let value = currentQuery[segmentName.replace("...", "")];
if (!value) continue;
if (Array.isArray(value)) value = value.join("/");
href = href.replace(segment, value);
}
return href === "/" ? href : href.replace(/\/$/, "");
};
const getOutputFile = (bundleId, ext, chunk) => {
return `${CLIENT_ASSET_PREFIX}/${chunk ? "chunk" : "main"}.${bundleId}.${ext}`;
};
const getPublicFile = (...args) => {
return `${PUBLIC_ASSET_PREFIX}/${getOutputFile(...args)}`;
};
//#endregion
//#region private/universal/utils/index.ts
/**
* Generate pseudo-random unique identifiers.
*
* @returns A unique identifier.
*/
const generateUniqueId = () => {
return crypto.getRandomValues(new Uint32Array(1))[0].toString();
};
/**
* Generates a function that can be used to set new cookies.
*
* @param serverContext - A server context object.
*
* @returns The function that can be used for setting cookies.
*/
const getCookieSetter = (serverContext) => {
const { collected, cookies } = serverContext;
return (name, value, options) => {
const cookieSettings = {
maxAge: DEFAULT_COOKIE_MAX_AGE,
httpOnly: !options?.client,
path: options?.path || "/"
};
if (value === null) {
cookieSettings.expires = /* @__PURE__ */ new Date(Date.now() - 1e6);
delete cookieSettings.maxAge;
delete cookies[name];
} else if (typeof value !== "string") {
let message = "Cookies can only be set to a string value, or `null` ";
message += `for deleting them. Please adjust "${name}".`;
throw new Error(message);
}
if (!collected.cookies) collected.cookies = {};
collected.cookies[name] = {
value,
...cookieSettings
};
cookies[name] = value;
};
};
//#endregion
export { populatePathSegments as a, DEFAULT_COOKIE_MAX_AGE as c, getPublicFile as i, DEFAULT_PAGE_PATH as l, getCookieSetter as n, CLIENT_ASSET_PREFIX as o, getOutputFile as r, CUSTOM_HEADERS as s, generateUniqueId as t, PUBLIC_ASSET_PREFIX as u };