78 lines
2.4 KiB
JavaScript
78 lines
2.4 KiB
JavaScript
import { createDefu } from "defu";
|
|
import { parseURL, withLeadingSlash } from "ufo";
|
|
import { createRouter, toRouteMatcher } from "radix3";
|
|
import { createConsola } from "consola";
|
|
export const logger = createConsola({
|
|
defaults: {
|
|
tag: "@nuxt/sitemap"
|
|
}
|
|
});
|
|
const merger = createDefu((obj, key, value) => {
|
|
if (Array.isArray(obj[key]) && Array.isArray(value))
|
|
obj[key] = Array.from(/* @__PURE__ */ new Set([...obj[key], ...value]));
|
|
return obj[key];
|
|
});
|
|
export function mergeOnKey(arr, key) {
|
|
const res = {};
|
|
arr.forEach((item) => {
|
|
const k = item[key];
|
|
res[k] = merger(item, res[k] || {});
|
|
});
|
|
return Object.values(res);
|
|
}
|
|
export function splitForLocales(path, locales) {
|
|
const prefix = withLeadingSlash(path).split("/")[1];
|
|
if (locales.includes(prefix))
|
|
return [prefix, path.replace(`/${prefix}`, "")];
|
|
return [null, path];
|
|
}
|
|
const StringifiedRegExpPattern = /\/(.*?)\/([gimsuy]*)$/;
|
|
export function normalizeRuntimeFilters(input) {
|
|
return (input || []).map((rule) => {
|
|
if (rule instanceof RegExp || typeof rule === "string")
|
|
return rule;
|
|
const match = rule.regex.match(StringifiedRegExpPattern);
|
|
if (match)
|
|
return new RegExp(match[1], match[2]);
|
|
return false;
|
|
}).filter(Boolean);
|
|
}
|
|
export function createPathFilter(options = {}) {
|
|
const urlFilter = createFilter(options);
|
|
return (loc) => {
|
|
let path = loc;
|
|
try {
|
|
path = parseURL(loc).pathname;
|
|
} catch {
|
|
return false;
|
|
}
|
|
return urlFilter(path);
|
|
};
|
|
}
|
|
export function createFilter(options = {}) {
|
|
const include = options.include || [];
|
|
const exclude = options.exclude || [];
|
|
if (include.length === 0 && exclude.length === 0)
|
|
return () => true;
|
|
return function(path) {
|
|
for (const v of [{ rules: exclude, result: false }, { rules: include, result: true }]) {
|
|
const regexRules = v.rules.filter((r) => r instanceof RegExp);
|
|
if (regexRules.some((r) => r.test(path)))
|
|
return v.result;
|
|
const stringRules = v.rules.filter((r) => typeof r === "string");
|
|
if (stringRules.length > 0) {
|
|
const routes = {};
|
|
for (const r of stringRules) {
|
|
if (r === path)
|
|
return v.result;
|
|
routes[r] = true;
|
|
}
|
|
const routeRulesMatcher = toRouteMatcher(createRouter({ routes, strictTrailingSlash: false }));
|
|
if (routeRulesMatcher.matchAll(path).length > 0)
|
|
return Boolean(v.result);
|
|
}
|
|
}
|
|
return include.length === 0;
|
|
};
|
|
}
|