Skip to content

Commit

Permalink
Upgrade to vite 5
Browse files Browse the repository at this point in the history
  • Loading branch information
airhorns committed Jun 17, 2024
1 parent 26ed6d0 commit 258b542
Show file tree
Hide file tree
Showing 22 changed files with 725 additions and 382 deletions.
2 changes: 2 additions & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,8 @@ jobs:
steps:
- uses: actions/checkout@v3
- uses: ./.github/actions/setup-test-env
- name: Build JS
run: pnpm build
- name: Run Lint
run: pnpm run lint

Expand Down
6 changes: 3 additions & 3 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,8 @@
"lint:fix": "prettier --loglevel warn --write \"packages/**/*.{ts,tsx}\" && eslint \"packages/**/*.{ts,tsx}\" --quiet --fix",
"release": "pnpm -F=fastify-renderer publish",
"preinstall": "npx only-allow pnpm",
"prerelease": "pnpm -F=fastify-renderer run gitpkg publish",
"test": "vitest --no-threads"
"prerelease": "pnpm -F=fastify-renderer exec gitpkg publish",
"test": "vitest --pool=forks --run"
},
"repository": {
"type": "git",
Expand Down Expand Up @@ -44,7 +44,7 @@
"eslint-plugin-react": "^7.33.2",
"eslint-plugin-react-hooks": "^4.6.0",
"fs-extra": "^11.1.0",
"vitest": "^0.34.6",
"vitest": "^1.0.4",
"playwright-chromium": "^1.39.0",
"prettier": "^2.8.8",
"prettier-plugin-organize-imports": "^3.2.3",
Expand Down
20 changes: 13 additions & 7 deletions packages/fastify-renderer/package.json
Original file line number Diff line number Diff line change
@@ -1,13 +1,19 @@
{
"name": "fastify-renderer",
"version": "0.4.2",
"version": "0.5.0",
"description": "Simple, high performance client side app renderer for Fastify.",
"exports": {
".": {
"require": "./node/index.js"
"default": "./node/index.js",
"import": "./node/index.js"
},
"./client/react": {
"default": "./client/react/index.js"
"default": "./client/react/index.js",
"import": "./client/react/index.js"
},
"./client/react/DefaultLayout": {
"default": "./client/react/DefaultLayout.js",
"import": "./client/react/DefaultLayout.js"
},
"./package": "./package.json",
"./package.json": "./package.json"
Expand All @@ -29,7 +35,7 @@
"lint:fix": "prettier --loglevel warn --write \"{src,test}/**/*.{ts,tsx}\" && eslint \"{src,test}/**/*.{ts,tsx}\" --quiet --fix",
"prepublishOnly": "npm run build",
"test": "run-s build test:unit lint",
"test:unit": "vitest"
"test:unit": "vitest --run"
},
"repository": {
"type": "git",
Expand Down Expand Up @@ -67,8 +73,8 @@
"path-to-regexp": "^6.2.1",
"sanitize-filename": "^1.6.3",
"stream-template": "^0.0.10",
"vite": "^2.9.15",
"wouter": "^2.7.5"
"vite": "^5.3.1",
"wouter": "^2.11.0"
},
"peerDependencies": {
"fastify": "^4.24.2",
Expand Down Expand Up @@ -109,4 +115,4 @@
"README.md",
"LICENSE"
]
}
}
2 changes: 1 addition & 1 deletion packages/fastify-renderer/src/client/react/matcher.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { Key, pathToRegexp } from 'path-to-regexp'
import { MatcherFn } from 'wouter'
import { MatcherFn } from 'wouter/matcher'

/*
* This function specifies how strings like /app/:users/:items* are transformed into regular expressions to pass into path-to-regexp.
Expand Down
6 changes: 5 additions & 1 deletion packages/fastify-renderer/src/client/react/package.json
Original file line number Diff line number Diff line change
@@ -1,4 +1,8 @@
{
"sideEffects": false,
"module": "./index.js"
"type": "module",
"exports": {
".": "./index.js",
"./DefaultLayout": "./DefaultLayout.js"
}
}
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import 'wouter'

declare module 'wouter' {
export interface RouterProps {
export interface RouterObject {
navigationHistory?: NavigationHistory
}

Expand Down
3 changes: 2 additions & 1 deletion packages/fastify-renderer/src/node/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ const plugin: FastifyPluginAsync<FastifyRendererOptions> = async (fastify, incom

fastify.setRenderConfig({
base: incomingOptions.base || '',
layout: incomingOptions.layout || require.resolve('./renderers/react/DefaultLayout.tsx'),
layout: incomingOptions.layout || require.resolve('fastify-renderer/client/react/DefaultLayout'),
document: incomingOptions.document || DefaultDocumentTemplate,
})

Expand Down Expand Up @@ -149,6 +149,7 @@ const plugin: FastifyPluginAsync<FastifyRendererOptions> = async (fastify, incom
fastify.addHook('onReady', async () => {
fastify[kRendererViteOptions] = {
clearScreen: false,
appType: 'custom',
...plugin.vite,
plugins: [...(plugin.vite?.plugins || []), ...plugin.renderer.vitePlugins()],
server: {
Expand Down
2 changes: 1 addition & 1 deletion packages/fastify-renderer/src/node/renderers/Renderer.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { FastifyReply, FastifyRequest } from 'fastify'
import { Plugin, ResolvedConfig, ViteDevServer } from 'vite'
import type { Plugin, ResolvedConfig, ViteDevServer } from 'vite'
import { Template } from '../DocumentTemplate'

/** The options configuring a plugin encapsulation context's renders */
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,8 @@ import path from 'path'
import querystring from 'querystring'
import type { ReactElement } from 'react'
import { URL } from 'url'
import { Plugin, ResolvedConfig, ViteDevServer } from 'vite'
import { normalizePath } from 'vite/dist/node'
import type { Plugin, ResolvedConfig, ViteDevServer } from 'vite'
import { normalizePath } from 'vite'
import { FastifyRendererPlugin } from '../../Plugin'
import { RenderBus } from '../../RenderBus'
import { wrap } from '../../tracing'
Expand Down Expand Up @@ -43,11 +43,8 @@ export class ReactRenderer implements Renderer {
devServer?: ViteDevServer
renderables!: RenderableRegistration[]
tmpdir!: string
clientModulePath: string

constructor(readonly plugin: FastifyRendererPlugin, readonly options: ReactRendererOptions) {
this.clientModulePath = require.resolve('../../../client/react/index.ts')
}
constructor(readonly plugin: FastifyRendererPlugin, readonly options: ReactRendererOptions) {}

vitePlugins() {
return [
Expand All @@ -58,6 +55,10 @@ export class ReactRenderer implements Renderer {
]
}

async clientModulePath() {
return 'fastify-renderer/client/react'
}

async prepare(renderables: RenderableRegistration[], viteConfig: ResolvedConfig, devServer?: ViteDevServer) {
this.viteConfig = viteConfig
this.renderables = renderables
Expand Down Expand Up @@ -322,7 +323,7 @@ export class ReactRenderer implements Renderer {
return id
}
},
load: (id) => {
load: async (id) => {
if (id.startsWith(CLIENT_ENTRYPOINT_PREFIX)) {
const url = new URL('fstr://' + id)
const entrypoint = id.replace(CLIENT_ENTRYPOINT_PREFIX, '/@fs/').replace(/\/hydrate\.jsx\?.+$/, '')
Expand All @@ -343,7 +344,7 @@ export class ReactRenderer implements Renderer {
import { routes } from ${JSON.stringify(
ReactRenderer.ROUTE_TABLE_ID + '?' + querystring.stringify(queryParams)
)}
import { Root } from ${JSON.stringify(this.clientModulePath)}
import { Root } from ${JSON.stringify(await this.clientModulePath())}
import Layout from ${JSON.stringify(layout)}
import Entrypoint from ${JSON.stringify(entrypoint)}
Expand Down Expand Up @@ -375,7 +376,7 @@ export class ReactRenderer implements Renderer {
return id
}
},
load: (id) => {
load: async (id) => {
if (id.startsWith(SERVER_ENTRYPOINT_PREFIX)) {
const entrypoint = id.replace(SERVER_ENTRYPOINT_PREFIX, '').replace(/\/ssr\.jsx\?.+$/, '')
const url = new URL('fstr://' + id)
Expand All @@ -385,7 +386,7 @@ export class ReactRenderer implements Renderer {
// server side processed entrypoint for a particular route generated by fastify-renderer
import React from 'react'
import ReactDOMServer from 'react-dom/server'
import { Router, RenderBusContext } from ${JSON.stringify(this.clientModulePath)}
import { Router, RenderBusContext } from ${JSON.stringify(await this.clientModulePath())}
import Layout from ${JSON.stringify(layout)}
import Entrypoint from ${JSON.stringify(entrypoint)}
Expand Down Expand Up @@ -432,7 +433,7 @@ export class ReactRenderer implements Renderer {
return id
}
},
load: (id) => {
load: async (id) => {
if (id.startsWith(ReactRenderer.ROUTE_TABLE_ID)) {
const url = new URL('fstr://' + id)
const lazy = !!url.searchParams.get('lazy')!
Expand Down
1 change: 0 additions & 1 deletion packages/fastify-renderer/src/node/tsconfig.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
{
"extends": "../../../../tsconfig.json",
"include": ["./"],
"compilerOptions": {
"target": "ES2019",
"outDir": "../../node",
Expand Down
2 changes: 1 addition & 1 deletion packages/fastify-renderer/src/node/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ import {
} from 'fastify'
import { IncomingMessage, Server, ServerResponse } from 'http'
import { ReactElement } from 'react'
import { InlineConfig, SSROptions, ViteDevServer } from 'vite'
import { InlineConfig, SSROptions, type ViteDevServer } from 'vite'
import { FastifyRendererPlugin, ImperativeRenderable } from './Plugin'
import { RenderOptions, PartialRenderOptions } from './renderers/Renderer'
import { kRendererPlugin, kRendererViteOptions, kRenderOptions } from './symbols'
Expand Down
22 changes: 0 additions & 22 deletions packages/fastify-renderer/test/FastifyRenderer.spec.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,4 @@
import { promises as fs } from 'node:fs'
import path from 'path'
import * as Vite from 'vite'
import FastifyRenderer, { build } from '../src/node'
import { FastifyRendererPlugin } from '../src/node/Plugin'
import { kRenderOptions } from '../src/node/symbols'
Expand Down Expand Up @@ -62,16 +60,10 @@ describe('FastifyRenderer', () => {
})

test('should close vite devServer when fastify server is closing in dev mode', async () => {
const devServer = await Vite.createServer()
const closeSpy = vi.spyOn(devServer, 'close')
vi.spyOn(Vite, 'createServer').mockImplementation(async () => devServer)

server = await newFastify()
await server.register(FastifyRenderer, { ...options, devMode: true })
await server.listen({ port: 0 })
await server.close()

expect(closeSpy).toHaveBeenCalled()
})

test('should do nothing if the registered route is not renderable', async () => {
Expand Down Expand Up @@ -101,18 +93,4 @@ describe('build()', () => {
const server = await newFastify()
void expect(build(server)).rejects.toThrow()
})

test('should build client and server side assets', async () => {
const server = await newFastify()
await server.register(FastifyRenderer, options)
await server.listen({ port: 0 })

vi.spyOn(fs, 'writeFile').mockImplementation(vi.fn(() => null as any))
vi.spyOn(path, 'join').mockImplementation(vi.fn(() => null as any))
const viteBuildSpy = vi.spyOn(Vite, 'build').mockImplementation(vi.fn(() => null as any))

await build(server)

expect(viteBuildSpy).toHaveBeenCalledTimes(2)
})
})
7 changes: 2 additions & 5 deletions packages/fastify-renderer/test/Plugin.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@ import fs from 'node:fs'
describe('FastifyRendererPlugin', () => {
beforeEach(() => {
vi.clearAllMocks()
vi.spyOn(fs, 'readFileSync')
})

test('should create a new instance with default options', async () => {
Expand All @@ -21,25 +20,23 @@ describe('FastifyRendererPlugin', () => {
expect(plugin.hooks).toEqual([])
expect(plugin.clientOutDir).toEqual(path.join(process.cwd(), 'dist', 'client', plugin.viteBase))
expect(plugin.serverOutDir).toEqual(path.join(process.cwd(), 'dist', 'server'))
expect(fs.readFileSync).toHaveBeenCalledTimes(0)
})

test('should create a new instance with the provided options', async () => {
const options: FastifyRendererOptions = {
outDir: '/tmp/out/dir',
renderer: { type: 'react', mode: 'sync' },
devMode: false,
devMode: true,
assetsHost: 'https://custom.asset.host',
}
const plugin = newFastifyRendererPlugin(options)

expect(plugin.devMode).toEqual(false)
expect(plugin.devMode).toEqual(true)
expect(plugin.viteBase).toEqual('/.vite/')
expect(plugin.assetsHost).toEqual(options.assetsHost)
expect(plugin.hooks).toEqual([])
expect(plugin.clientOutDir).toEqual(path.join(options.outDir as string, 'client', plugin.viteBase))
expect(plugin.serverOutDir).toEqual(path.join(options.outDir as string, 'server'))
expect(fs.readFileSync).toHaveBeenCalledTimes(2)
})

describe('clientAssetPath()', () => {
Expand Down
2 changes: 1 addition & 1 deletion packages/fastify-renderer/test/fixtures/test-layout.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import React, { Suspense } from 'react'
import { LayoutProps } from '../../src/client/react'
import { LayoutProps } from '../../client/react'

// eslint-disable-next-line react/display-name
export default function (props: LayoutProps) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ const testLayoutComponent = require.resolve(path.join(__dirname, '..', 'fixtures
describe('ReactRenderer', () => {
test('should create an instance and initialize the client module path', async () => {
const renderer = newReactRenderer()
expect(renderer.clientModulePath).not.toBeUndefined()
expect(await renderer.clientModulePath()).not.toBeUndefined()
})

describe('vitePlugins()', () => {
Expand Down
2 changes: 1 addition & 1 deletion packages/test-apps/simple-react/build.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { build } from '../../fastify-renderer/src/node'
import { build } from 'fastify-renderer'
import { server } from './server'

void server().then(async (server) => {
Expand Down
2 changes: 1 addition & 1 deletion packages/test-apps/simple-react/helpers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ let pages: Page[] = []
let server: FastifyInstance
let err: Error

export const port = 3001
export const port = 3001 + parseInt(process.env.VITEST_WORKER_ID!) - 1
export const rootURL = `http://localhost:${port}`

beforeAll(async ({ filepath }) => {
Expand Down
4 changes: 2 additions & 2 deletions packages/test-apps/simple-react/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -10,12 +10,12 @@
"license": "MIT",
"dependencies": {
"fastify": "^4.23.2",
"fastify-renderer": "*",
"fastify-renderer": "workspace:*",
"path-to-regexp": "^6.2.1",
"react": "*",
"react-dom": "*",
"stream-template": "^0.0.10",
"wouter": "^2.7.5"
"wouter": "^2.11.0"
},
"devDependencies": {
"@playwright/test": "^1.39.0",
Expand Down
2 changes: 1 addition & 1 deletion packages/test-apps/simple-react/server.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import type { FastifyRequest } from 'fastify'
import os from 'os'
import renderer from '../../fastify-renderer/src/node'
import renderer from '../../fastify-renderer'
import { newFastify } from '../../fastify-renderer/test/helpers'
import { CustomDocumentTemplate } from './CustomDocumentTemplate'

Expand Down
5 changes: 3 additions & 2 deletions packages/test-apps/simple-react/test/build.spec.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,11 @@
import { build } from '../../../fastify-renderer/src/node'
import FR from 'fastify-renderer'
import { server as getServer } from '../server'
import { describe, test } from 'vitest'

describe('simple-react building assets', () => {
test('can run the build', async () => {
const server = await getServer()
await server.ready()
await build(server)
await (FR as any).build(server)
})
})
Loading

0 comments on commit 258b542

Please sign in to comment.