From 8dfadc8526cd8090806fabd75878983e40ee0fee Mon Sep 17 00:00:00 2001 From: harlan Date: Mon, 1 Jul 2024 14:14:43 +1000 Subject: [PATCH] fix: warn when providing non-serializable `urls` Fixes #285 --- src/module.ts | 4 ++-- src/util/nuxtSitemap.ts | 12 +++++++++++- 2 files changed, 13 insertions(+), 3 deletions(-) diff --git a/src/module.ts b/src/module.ts index 115b05f8..c082b6a7 100644 --- a/src/module.ts +++ b/src/module.ts @@ -551,7 +551,7 @@ declare module 'vue-router' { name: 'sitemap:urls', description: 'Set with the `sitemap.urls` config.', }, - urls: await resolveUrls(config.urls), + urls: await resolveUrls(config.urls, { path: 'sitemap:urls', logger }), }) // we want to avoid adding duplicates as well as hitting api endpoints multiple times resolvedConfigUrls = true @@ -625,7 +625,7 @@ declare module 'vue-router' { name: `sitemaps:${sitemapName}:urls`, description: 'Set with the `sitemap.urls` config.', }, - urls: await resolveUrls(definition.urls), + urls: await resolveUrls(definition.urls, { path: `sitemaps:${sitemapName}:urls`, logger }), }) definition!.dynamicUrlsApiEndpoint && sitemapSources[sitemapName].push({ context: { diff --git a/src/util/nuxtSitemap.ts b/src/util/nuxtSitemap.ts index 4eb106c0..24c86945 100644 --- a/src/util/nuxtSitemap.ts +++ b/src/util/nuxtSitemap.ts @@ -4,15 +4,25 @@ import type { Nuxt } from '@nuxt/schema' import { useNuxt } from '@nuxt/kit' import { extname } from 'pathe' import { defu } from 'defu' +import type { ConsolaInstance } from 'consola' import type { SitemapDefinition, SitemapUrl, SitemapUrlInput } from '../runtime/types' import { createPathFilter } from '../runtime/utils-pure' import type { CreateFilterOptions } from '../runtime/utils-pure' -export async function resolveUrls(urls: Required['urls']): Promise { +export async function resolveUrls(urls: Required['urls'], ctx: { logger: ConsolaInstance, path: string }): Promise { if (typeof urls === 'function') urls = urls() // resolve promise urls = await urls + // we need to validate that the urls can be serialised properly for example to avoid circular references + try { + urls = JSON.parse(JSON.stringify(urls)) + } + catch (e) { + ctx.logger.warn(`Failed to serialize ${typeof urls} \`${ctx.path}\`, please make sure that the urls resolve as a valid array without circular dependencies.`) + ctx.logger.error(e) + return [] + } return urls }