Skip to content

Commit

Permalink
feat!: upgrade to new major nitropack/h3 (#589)
Browse files Browse the repository at this point in the history
  • Loading branch information
danielroe committed Oct 24, 2022
1 parent 81fc9c8 commit cddc4d0
Show file tree
Hide file tree
Showing 12 changed files with 156 additions and 230 deletions.
4 changes: 2 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -50,12 +50,12 @@
"fs-extra": "^10.1.0",
"get-port-please": "^2.6.1",
"globby": "^13.1.2",
"h3": "^0.7.21",
"h3": "^0.8.5",
"hash-sum": "^2.0.0",
"knitwork": "^0.1.2",
"magic-string": "^0.26.7",
"mlly": "^0.5.16",
"nitropack": "^0.5.4",
"nitropack": "^0.6.0",
"node-fetch": "^3.2.10",
"nuxi": "3.0.0-rc.12",
"ohash": "^0.1.5",
Expand Down
8 changes: 4 additions & 4 deletions playground/nuxt.config.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { defineEventHandler } from 'h3'
import { defineNuxtConfig } from '..'

// @ts-ignore
Expand All @@ -7,10 +8,9 @@ export default defineNuxtConfig({
components: true,
serverMiddleware: [
{
handle (req, _res, next) {
req.spa = req.url.includes('?spa')
next()
}
handle: defineEventHandler((event) => {
event.req.spa = event.req.url.includes('?spa')
})
}
],
modules: [
Expand Down
2 changes: 1 addition & 1 deletion playground/server/api/hello.ts
Original file line number Diff line number Diff line change
@@ -1 +1 @@
export default () => 'Hello API'
export default defineEventHandler(() => 'Hello API')
4 changes: 2 additions & 2 deletions playground/server/api/hey/index.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
export default () => ({
export default defineEventHandler(() => ({
foo: 'bar',
baz: 'qux'
})
}))
9 changes: 4 additions & 5 deletions src/nitro.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import { addPluginTemplate, resolvePath, tryImportModule, useNuxt } from '@nuxt/
import { joinURL, stringifyQuery, withBase, withoutTrailingSlash } from 'ufo'
import { resolve, join, dirname, normalize } from 'pathe'
import { createNitro, createDevServer, build, writeTypes, prepare, copyPublicAssets, prerender } from 'nitropack'
import { dynamicEventHandler, toEventHandler } from 'h3'
import { dynamicEventHandler } from 'h3'
import type { Nitro, NitroEventHandler, NitroDevEventHandler, NitroConfig } from 'nitropack'
import { Nuxt, NuxtPage } from '@nuxt/schema'
import { defu } from 'defu'
Expand Down Expand Up @@ -65,7 +65,6 @@ export async function setupNitroBridge () {
rootDir: resolve(nuxt.options.rootDir),
srcDir: resolve(nuxt.options.srcDir, 'server'),
dev: nuxt.options.dev,
preset: nuxt.options.dev ? 'nitro-dev' : undefined,
buildDir: resolve(nuxt.options.buildDir),
scanDirs: nuxt.options._layers.map(layer => join(layer.config.srcDir, 'server')),
renderer: resolve(distDir, 'runtime/nitro/renderer'),
Expand Down Expand Up @@ -251,8 +250,8 @@ export async function setupNitroBridge () {
})

// Setup handlers
const devMidlewareHandler = dynamicEventHandler()
nitro.options.devHandlers.unshift({ handler: devMidlewareHandler })
const devMiddlewareHandler = dynamicEventHandler()
nitro.options.devHandlers.unshift({ handler: devMiddlewareHandler })
const { handlers, devHandlers } = await resolveHandlers(nuxt)
nitro.options.handlers.push(...handlers)
nitro.options.devHandlers.push(...devHandlers)
Expand Down Expand Up @@ -359,7 +358,7 @@ export async function setupNitroBridge () {
nuxt.hook('build:compile', ({ compiler }) => {
compiler.outputFileSystem = { ...fsExtra, join } as any
})
nuxt.hook('server:devMiddleware', (m) => { devMidlewareHandler.set(toEventHandler(m)) })
nuxt.hook('server:devHandler', (h) => { devMiddlewareHandler.set(h) })
}

// nuxt generate
Expand Down
4 changes: 2 additions & 2 deletions src/runtime/composables.ts
Original file line number Diff line number Diff line change
Expand Up @@ -197,9 +197,9 @@ export const navigateTo = (to: RawLocation, options: NavigateToOptions = {}): Pr
const router = useRouter()
if (process.server && useNuxtApp().ssrContext) {
// Server-side redirection using h3 res from ssrContext
const res = useNuxtApp().ssrContext?.res
const event = useNuxtApp().ssrContext?.event
const redirectLocation = joinURL(useRuntimeConfig().app.baseURL, router.resolve(to).fullPath || '/')
return sendRedirect(res, redirectLocation)
return sendRedirect(event, redirectLocation)
}
// Client-side redirection using vue-router
return options.replace ? router.replace(to) : router.push(to)
Expand Down
4 changes: 2 additions & 2 deletions src/runtime/cookie.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { Ref, ref, watch } from 'vue'
import { parse, serialize, CookieParseOptions, CookieSerializeOptions } from 'cookie-es'
import { appendHeader } from 'h3'
import type { CompatibilityEvent } from 'h3'
import type { H3Event } from 'h3'
import destr from 'destr'
import { useNuxtApp } from './app'
import { useRequestEvent } from './ssr'
Expand Down Expand Up @@ -64,7 +64,7 @@ function writeClientCookie (name: string, value: any, opts: CookieSerializeOptio
}
}

function writeServerCookie (event: CompatibilityEvent, name: string, value: any, opts: CookieSerializeOptions = {}) {
function writeServerCookie (event: H3Event, name: string, value: any, opts: CookieSerializeOptions = {}) {
if (event) {
// TODO: Try to smart join with existing Set-Cookie headers
appendHeader(event, 'Set-Cookie', serializeCookie(name, value, opts))
Expand Down
10 changes: 6 additions & 4 deletions src/runtime/nitro/renderer.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { createRenderer } from 'vue-bundle-renderer/runtime'
import type { SSRContext } from 'vue-bundle-renderer/runtime'
import { CompatibilityEvent, getQuery } from 'h3'
import { H3Event, getQuery } from 'h3'
import devalue from '@nuxt/devalue'
import type { RuntimeConfig } from '@nuxt/schema'
import type { RenderResponse } from 'nitropack'
Expand Down Expand Up @@ -37,9 +37,11 @@ interface NuxtSSRContext extends SSRContext {
url: string
noSSR: boolean
redirected?: boolean
event: CompatibilityEvent
req: CompatibilityEvent['req']
res: CompatibilityEvent['res']
event: H3Event
/** @deprecated use `ssrContext.event` instead */
req: H3Event['req']
/** @deprecated use `ssrContext.event` instead */
res: H3Event['res']
runtimeConfig: RuntimeConfig
error?: any
nuxt?: any
Expand Down
6 changes: 3 additions & 3 deletions src/runtime/ssr.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
/* eslint-disable no-redeclare */
import type { CompatibilityEvent } from 'h3'
import type { H3Event } from 'h3'
import { NuxtAppCompat, useNuxtApp } from './app'

export function useRequestHeaders<K extends string = string> (include: K[]): Record<K, string>
Expand All @@ -11,6 +11,6 @@ export function useRequestHeaders (include?) {
return Object.fromEntries(include.filter(key => headers[key]).map(key => [key, headers[key]]))
}

export function useRequestEvent (nuxtApp: NuxtAppCompat = useNuxtApp()): CompatibilityEvent {
return nuxtApp.ssrContext?.event as CompatibilityEvent
export function useRequestEvent (nuxtApp: NuxtAppCompat = useNuxtApp()): H3Event {
return nuxtApp.ssrContext?.event as H3Event
}
31 changes: 18 additions & 13 deletions src/vite/client.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
import { join, resolve } from 'pathe'
import createVuePlugin from '@vitejs/plugin-vue2'
import { logger } from '@nuxt/kit'
import { joinURL, withLeadingSlash, withoutLeadingSlash, withTrailingSlash } from 'ufo'
import escapeRE from 'escape-string-regexp'
import { joinURL, withoutLeadingSlash } from 'ufo'
import { getPort } from 'get-port-please'
import type { ServerOptions, Connect, InlineConfig } from 'vite'
import type { ServerOptions, InlineConfig } from 'vite'
import { defineEventHandler } from 'h3'
import defu from 'defu'
import PluginLegacy from './stub-legacy.cjs'
import { mergeConfig, createServer, build } from './stub-vite.cjs'
Expand All @@ -24,6 +24,9 @@ export async function buildClient (ctx: ViteBuildContext) {
}

const clientConfig: InlineConfig = await mergeConfig(ctx.config, {
base: ctx.nuxt.options.dev
? joinURL(ctx.nuxt.options.app.baseURL.replace(/^\.\//, '/') || '/', ctx.nuxt.options.app.buildAssetsDir)
: './',
experimental: {
renderBuiltUrl: (filename, { type, hostType }) => {
if (hostType !== 'js' || type === 'asset') {
Expand Down Expand Up @@ -104,18 +107,20 @@ export async function buildClient (ctx: ViteBuildContext) {
const viteServer = await createServer(clientConfig)
ctx.clientServer = viteServer
await ctx.nuxt.callHook('vite:serverCreated', viteServer, { isClient: true, isServer: false })
const baseURL = joinURL(ctx.nuxt.options.app.baseURL.replace(/^\./, '') || '/', ctx.nuxt.options.app.buildAssetsDir)
const BASE_RE = new RegExp(`^${escapeRE(withTrailingSlash(withLeadingSlash(baseURL)))}`)
const viteMiddleware: Connect.NextHandleFunction = (req, res, next) => {
const viteMiddleware = defineEventHandler(async (event) => {
// Workaround: vite devmiddleware modifies req.url
const originalURL = req.url
req.url = req.url.replace(BASE_RE, '/')
viteServer.middlewares.handle(req, res, (err: unknown) => {
req.url = originalURL
next(err)
const originalURL = event.req.url
if (!originalURL.startsWith(clientConfig.base!)) {
event.req.url = joinURL('/__url', originalURL)
}
await new Promise((resolve, reject) => {
viteServer.middlewares.handle(event.req, event.res, (err: Error) => {
event.req.url = originalURL
return err ? reject(err) : resolve(null)
})
})
}
await ctx.nuxt.callHook('server:devMiddleware', viteMiddleware)
})
await ctx.nuxt.callHook('server:devHandler', viteMiddleware)

ctx.nuxt.hook('close', async () => {
await viteServer.close()
Expand Down
4 changes: 2 additions & 2 deletions test/bridge.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ describe('errors', () => {
description: process.env.NUXT_TEST_DEV ? expect.stringContaining('<pre>') : '',
message: 'This is a custom error',
statusCode: 500,
statusMessage: 'Internal Server Error',
statusMessage: '',
url: '/error'
})
})
Expand Down Expand Up @@ -143,7 +143,7 @@ describe('dynamic paths', () => {
\\"buildAssetsDir\\": \\"/_nuxt/\\"
},
\\"nitro\\": {
\\"routes\\": {},
\\"routeRules\\": {},
\\"envPrefix\\": \\"NUXT_\\"
},
\\"public\\": {
Expand Down

0 comments on commit cddc4d0

Please sign in to comment.