Skip to content

Commit

Permalink
fix: improved hooks
Browse files Browse the repository at this point in the history
  • Loading branch information
harlan-zw committed Jul 7, 2023
1 parent 8cb66e9 commit 00108c3
Show file tree
Hide file tree
Showing 9 changed files with 55 additions and 25 deletions.
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,7 @@ export default defineNuxtConfig({

### Demos

- [Dynamic URLs - StackBlitz](https://stackblitz.com/edit/nuxt-starter-dyraxc?file=package.json)
- [Dynamic URLs - StackBlitz](https://stackblitz.com/edit/nuxt-starter-dyraxc?file=server%2Fapi%2F_sitemap-urls.ts)


### Set Site URL (required when prerendering)
Expand Down
11 changes: 6 additions & 5 deletions src/kit.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,15 @@ import { addTemplate, loadNuxtModuleInstance, normalizeSemanticVersion, useNuxt
import { resolve } from 'pathe'
import { satisfies } from 'semver'
import type { NuxtModule } from 'nuxt/schema'
import type { MaybePromise } from './runtime/types'

export function extendTypes(module: string, template: () => string) {
export function extendTypes(module: string, template: () => MaybePromise<string>) {
const nuxt = useNuxt()
// paths.d.ts
addTemplate({
filename: `${module}.d.ts`,
getContents: () => {
const s = template()
filename: `module/${module}.d.ts`,
getContents: async () => {
const s = await template()
return `// Generated by ${module}
${s}
export {}
Expand All @@ -18,7 +19,7 @@ export {}
})

nuxt.hooks.hook('prepare:types', ({ references }) => {
references.push({ path: resolve(nuxt.options.buildDir, `${module}.d.ts`) })
references.push({ path: resolve(nuxt.options.buildDir, `module/${module}.d.ts`) })
})
}

Expand Down
23 changes: 17 additions & 6 deletions src/module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,18 +4,20 @@ import {
addServerPlugin,
createResolver,
defineNuxtModule, extendPages,
findPath, hasNuxtModule, useLogger,
findPath, hasNuxtModule, resolvePath, useLogger,
} from '@nuxt/kit'
import { joinURL, withBase, withoutLeadingSlash } from 'ufo'
import { installNuxtSiteConfig, requireSiteConfig, updateSiteConfig } from 'nuxt-site-config-kit'
import { addCustomTab } from '@nuxt/devtools-kit'
import type { NuxtPage } from 'nuxt/schema'
import { dirname, join } from 'pathe'
import { version } from '../package.json'
import { extendTypes, getNuxtModuleVersion, hasNuxtModuleCompatibility } from './kit'
import type {
ModuleComputedOptions, ModuleRuntimeConfig,
MultiSitemapsInput, SitemapEntry,
SitemapFullEntry,
SitemapOutputHookCtx,
SitemapRenderCtx,
SitemapRoot,
} from './runtime/types'
Expand Down Expand Up @@ -145,10 +147,11 @@ export interface ModuleOptions extends SitemapRoot {

export interface ModuleHooks {
/**
* @deprecated use `sitemap:prerender`
* @deprecated use `sitemap:resolved` or `sitemap:output`
*/
'sitemap:generate': (ctx: SitemapRenderCtx) => Promise<void> | void
'sitemap:prerender': (ctx: SitemapRenderCtx) => Promise<void> | void
'sitemap:resolved': (ctx: SitemapRenderCtx) => Promise<void> | void
'sitemap:output': (ctx: SitemapOutputHookCtx) => Promise<void> | void
}

export default defineNuxtModule<ModuleOptions>({
Expand Down Expand Up @@ -306,9 +309,9 @@ export default defineNuxtModule<ModuleOptions>({
})
})

extendTypes('nuxt-simple-sitemap', () => {
extendTypes('nuxt-simple-sitemap', async () => {
return `
import type { SitemapItemDefaults } from 'nuxt-simple-sitemap/dist/runtime/types'
import type { SitemapOutputHookCtx, SitemapRenderCtx, SitemapItemDefaults } from '${join(dirname(await resolvePath('nuxt-simple-sitemap')), 'runtime/types')}'
interface NuxtSimpleSitemapNitroRules {
index?: boolean
Expand All @@ -317,7 +320,15 @@ interface NuxtSimpleSitemapNitroRules {
declare module 'nitropack' {
interface NitroRouteRules extends NuxtSimpleSitemapNitroRules {}
interface NitroRouteConfig extends NuxtSimpleSitemapNitroRules {}
}`
}
// extend nitro hooks
declare module 'nitropack/dist/runtime/types' {
interface NitroRuntimeHooks {
'sitemap:resolved': (ctx: SitemapRenderCtx) => void | Promise<void>
'sitemap:output': (ctx: SitemapOutputHookCtx) => void | Promise<void>
}
}
`
})

if (typeof config.urls === 'function')
Expand Down
19 changes: 13 additions & 6 deletions src/prerender.ts
Original file line number Diff line number Diff line change
Expand Up @@ -93,11 +93,10 @@ export function setupPrerenderHandler(moduleConfig: ModuleOptions, buildTimeMeta
}

const callHook = async (ctx: SitemapRenderCtx) => {
// deprecated hook
// @ts-expect-error runtime type
await nuxt.hooks.callHook('sitemap:generate', ctx)
// @ts-expect-error runtime type
await nuxt.hooks.callHook('sitemap:prerender', ctx)
// @ts-expect-error runtime type
await nuxt.hooks.callHook('sitemap:resolved', ctx)
}

const options: BuildSitemapIndexInput = {
Expand All @@ -117,22 +116,30 @@ export function setupPrerenderHandler(moduleConfig: ModuleOptions, buildTimeMeta

// rendering a sitemap_index
const { xml, sitemaps } = await buildSitemapIndex(options)
await writeFile(resolve(nitro.options.output.publicDir, 'sitemap_index.xml'), xml)
const indexHookCtx = { sitemap: xml, sitemapName: 'index' }
await nuxt.hooks.callHook('sitemap:output', indexHookCtx)
await writeFile(resolve(nitro.options.output.publicDir, 'sitemap_index.xml'), indexHookCtx.sitemap)
const generateTimeMS = Date.now() - start
logs.push(`/sitemap_index.xml (${generateTimeMS}ms)`)
// now generate all sub sitemaps
for (const sitemap of sitemaps) {
const sitemapXml = await buildSitemap({
let sitemapXml = await buildSitemap({
...options,
sitemap,
})
const ctx = { sitemap: sitemapXml, sitemapName: sitemap.sitemapName }
await nuxt.hooks.callHook('sitemap:output', ctx)
sitemapXml = ctx.sitemap
await writeFile(resolve(nitro.options.output.publicDir, `${sitemap.sitemapName}-sitemap.xml`), sitemapXml)
const generateTimeMS = Date.now() - start
logs.push(`/${sitemap.sitemapName}-sitemap.xml (${generateTimeMS}ms)`)
}
}
else {
const sitemapXml = await buildSitemap(options)
let sitemapXml = await buildSitemap(options)
const ctx = { sitemap: sitemapXml, sitemapName: moduleConfig.sitemapName }
await nuxt.hooks.callHook('sitemap:output', ctx)
sitemapXml = ctx.sitemap
await writeFile(resolve(nitro.options.output.publicDir, moduleConfig.sitemapName), sitemapXml)
const generateTimeMS = Date.now() - start
logs.push(`/${moduleConfig.sitemapName} (${generateTimeMS}ms)`)
Expand Down
4 changes: 2 additions & 2 deletions src/runtime/middleware/[sitemap]-sitemap.xml.ts
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ export default defineEventHandler(async (e) => {
if (!sitemap) {
const nitro = useNitroApp()
const callHook = async (ctx: SitemapRenderCtx) => {
await nitro.hooks.callHook('sitemap:sitemap-xml', ctx)
await nitro.hooks.callHook('sitemap:resolved', ctx)
}
// merge urls
sitemap = await buildSitemap({
Expand All @@ -58,7 +58,7 @@ export default defineEventHandler(async (e) => {
})

const ctx = { sitemap, sitemapName }
await nitro.hooks.callHook('sitemap:sitemap:output', ctx)
await nitro.hooks.callHook('sitemap:output', ctx)
sitemap = ctx.sitemap

if (useCache)
Expand Down
4 changes: 2 additions & 2 deletions src/runtime/routes/sitemap.xml.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ export default defineEventHandler(async (e) => {
if (!sitemap) {
const nitro = useNitroApp()
const callHook = async (ctx: SitemapRenderCtx) => {
await nitro.hooks.callHook('sitemap:sitemap-xml', ctx)
await nitro.hooks.callHook('sitemap:resolved', ctx)
}

sitemap = await buildSitemap({
Expand All @@ -48,7 +48,7 @@ export default defineEventHandler(async (e) => {
})

const ctx = { sitemap, sitemapName: 'sitemap' }
await nitro.hooks.callHook('sitemap:sitemap:output', ctx)
await nitro.hooks.callHook('sitemap:output', ctx)
sitemap = ctx.sitemap

if (useCache)
Expand Down
10 changes: 8 additions & 2 deletions src/runtime/routes/sitemap_index.xml.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { defineEventHandler, setHeader } from 'h3'
import { prefixStorage } from 'unstorage'
import { buildSitemapIndex } from '../sitemap/builder'
import type { ModuleRuntimeConfig } from '../types'
import type { ModuleRuntimeConfig, SitemapRenderCtx } from '../types'
import { createSitePathResolver, useRuntimeConfig, useStorage } from '#imports'
import { getRouteRulesForPath } from '#internal/nitro/route-rules'
import pages from '#nuxt-simple-sitemap/pages.mjs'
Expand All @@ -24,11 +24,17 @@ export default defineEventHandler(async (e) => {
await cache.removeItem(key)
}

const nitro = useNitroApp()
const callHook = async (ctx: SitemapRenderCtx) => {
await nitro.hooks.callHook('sitemap:resolved', ctx)
}

if (!sitemap) {
sitemap = (await buildSitemapIndex({
moduleConfig,
buildTimeMeta,
getRouteRulesForPath,
callHook,
nitroUrlResolver: createSitePathResolver(e, { canonical: false, absolute: true, withBase: true }),
canonicalUrlResolver: createSitePathResolver(e, { canonical: !process.dev, absolute: true, withBase: true }),
relativeBaseUrlResolver: createSitePathResolver(e, { absolute: false, withBase: true }),
Expand All @@ -38,7 +44,7 @@ export default defineEventHandler(async (e) => {
const nitro = useNitroApp()

const ctx = { sitemap, sitemapName: 'sitemap' }
await nitro.hooks.callHook('sitemap:sitemap:output', ctx)
await nitro.hooks.callHook('sitemap:output', ctx)
sitemap = ctx.sitemap

if (useCache)
Expand Down
2 changes: 1 addition & 1 deletion src/runtime/sitemap/entries/normalise.ts
Original file line number Diff line number Diff line change
Expand Up @@ -136,7 +136,7 @@ export async function normaliseSitemapData(data: SitemapEntry[], options: BuildS
}

// do first round normalising of each entry
const ctx: SitemapRenderCtx = { urls: normaliseEntries(entries), sitemapName: options.sitemap?.naame || 'sitemap' }
const ctx: SitemapRenderCtx = { urls: normaliseEntries(entries), sitemapName: options.sitemap?.sitemapName || 'sitemap' }
// call hook
if (options.callHook)
await options.callHook(ctx)
Expand Down
5 changes: 5 additions & 0 deletions src/runtime/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,11 @@ export interface SitemapRenderCtx {
urls: ResolvedSitemapEntry[]
}

export interface SitemapOutputHookCtx {
sitemapName: string
sitemap: string
}

export type Changefreq =
| 'always'
| 'hourly'
Expand Down

0 comments on commit 00108c3

Please sign in to comment.