78 lines
2.3 KiB
JavaScript
78 lines
2.3 KiB
JavaScript
import { ref } from 'vue';
|
|
import { h as useRoute, m as useNuxtApp, p as useRequestEvent } from '../server.mjs';
|
|
import { parse, serialize } from 'cookie-es';
|
|
import { appendHeader } from 'h3';
|
|
import destr from 'destr';
|
|
import { isEqual } from 'ohash';
|
|
|
|
const CookieDefaults = {
|
|
path: "/",
|
|
watch: true,
|
|
decode: (val) => destr(decodeURIComponent(val)),
|
|
encode: (val) => encodeURIComponent(typeof val === "string" ? val : JSON.stringify(val))
|
|
};
|
|
function useCookie(name, _opts) {
|
|
var _a;
|
|
const opts = { ...CookieDefaults, ..._opts };
|
|
const cookies = readRawCookies(opts) || {};
|
|
const cookie = ref(cookies[name] ?? ((_a = opts.default) == null ? void 0 : _a.call(opts)));
|
|
{
|
|
const nuxtApp = useNuxtApp();
|
|
const writeFinalCookieValue = () => {
|
|
if (!isEqual(cookie.value, cookies[name])) {
|
|
writeServerCookie(useRequestEvent(nuxtApp), name, cookie.value, opts);
|
|
}
|
|
};
|
|
const unhook = nuxtApp.hooks.hookOnce("app:rendered", writeFinalCookieValue);
|
|
nuxtApp.hooks.hookOnce("app:redirected", () => {
|
|
unhook();
|
|
return writeFinalCookieValue();
|
|
});
|
|
}
|
|
return cookie;
|
|
}
|
|
function readRawCookies(opts = {}) {
|
|
var _a;
|
|
{
|
|
return parse(((_a = useRequestEvent()) == null ? void 0 : _a.req.headers.cookie) || "", opts);
|
|
}
|
|
}
|
|
function serializeCookie(name, value, opts = {}) {
|
|
if (value === null || value === void 0) {
|
|
return serialize(name, value, { ...opts, maxAge: -1 });
|
|
}
|
|
return serialize(name, value, opts);
|
|
}
|
|
function writeServerCookie(event, name, value, opts = {}) {
|
|
if (event) {
|
|
appendHeader(event, "Set-Cookie", serializeCookie(name, value, opts));
|
|
}
|
|
}
|
|
const useContentPreview = () => {
|
|
const getPreviewToken = () => {
|
|
return useCookie("previewToken").value || false || void 0;
|
|
};
|
|
const setPreviewToken = (token) => {
|
|
useCookie("previewToken").value = token;
|
|
useRoute().query.preview = token || "";
|
|
};
|
|
const isEnabled = () => {
|
|
const query = useRoute().query;
|
|
if (Object.prototype.hasOwnProperty.call(query, "preview") && !query.preview) {
|
|
return false;
|
|
}
|
|
if (query.preview || useCookie("previewToken").value) {
|
|
return true;
|
|
}
|
|
return false;
|
|
};
|
|
return {
|
|
isEnabled,
|
|
getPreviewToken,
|
|
setPreviewToken
|
|
};
|
|
};
|
|
|
|
export { useContentPreview as u };
|
|
//# sourceMappingURL=preview-38d6e135.mjs.map
|